Day-Trader Shadow

Day-Trader Shadow

The day-trader shadow (arb_bot/daytrader_shadow/) is a paper-only research service for an intraday opening-range-breakout method on NIFTY 500 stocks. It records signals and a notional ₹5,00,000 account, with a descriptive target of 12% a year after modeled costs. Results do not establish profitability or readiness to allocate capital. It never places orders or imports the live bot, execution engine or command handler; tests/daytrader_shadow/test_import_isolation.py pins that boundary. Paper promotion changes the research configuration only.

Session, universe and signals

RuleDefault
Normal NSE session09:15–15:30 IST; timestamps use IST
UniverseNIFTY 500 membership for the requested date; placeholder DUMMY symbols excluded
Opening range09:15, 09:20 and 09:25 five-minute bars; known at 09:30
Trigger windowClosed bars after the opening range, no earlier than 09:30 and no later than 14:45
Exit cutoff15:15, using the 15:10–15:15 bar when evidenced
Market dataYahoo .NS five-minute bars (live); Dhan historical five-minute bars (backfill); public dated instrument-tick metadata

The first eligible bar that closes above the opening-range high creates a signal. The default stop is the range midpoint, rounded down to the instrument's dated tick; the target is entry plus 2× entry-to-stop risk, rounded to that tick. The actual trigger close is stored rather than reconstructed from the slipped entry. A signal is evidence of the rule firing; it is not necessarily an account trade.

Pre-open history assigns setup tags. Each signal receives exactly one, in this precedence: breakout_20d > bull_flag > reclaim_ma20 > oversold_bounce > oversold, otherwise orb_only. A valid history observation with no tags permits orb_only; unavailable history does not.

Forward observations and historical replay

A forward paper decision persists its observation time, admission outcome and reserved quantity. A signal first observed more than max_signal_age_seconds = 300 seconds after its trigger is recorded as missed; it does not receive an earlier trigger-price account fill. Eligible decisions reserve cash and risk before entering a pending state.

A pending decision can fill only from a subsequent eligible observed bar. The model uses the first bar open at or after the recorded decision time, plus entry slippage, once that bar is available. Risk and cash constraints are checked again at that price; the reserved quantity cannot increase. An expired or invalid fill is rejected. Recorded admissions and fills are not replaced or resized when a late download reveals an earlier-triggering stock.

This is a bar-based model fill, not a broker fill or proof that an executable quote existed at that price. Historical replay computes a separate counterfactual account from archived signals. Its fills and allocations may differ from the forward account; a missed forward observation is never repaired by claiming a retrospective forward trade.

Account sizing, cash and loss controls

The default ₹5,00,000 account uses whole shares: planned after-cost loss at the modeled stop is capped at 1% per trade, position value at 75%, cash buffer at 10%, and entries at three per session. Minimum reward:risk is 1.0. Start-of-day equity is the basis for percentage limits. Simultaneous candidates are ordered by traded value, with a stable symbol tie-break.

Admission debits entry value and entry charges. An exit releases modeled sale proceeds less exit charges: losses reduce subsequent buying power and profits increase it. Reserved pending and open exposure consumes cash and risk; it cannot be reused as though the trade had already closed.

The 3% daily setting applies both to accumulated planned risk and to a separate loss halt. Realized net losses include costs. Forward admission also considers observable losses on filled open positions; missing or stale marks block new admission. A latched loss halt remains in force for the session. Gaps, halts and missing prices can still produce losses beyond the planned stop or daily threshold; neither setting guarantees a maximum loss.

Costs, dated ticks and evidenced exits

Rules version 2 includes the cost identity dhan-nse-intraday-2026-11-15-v2 in the config hash. The research schedule in costs.py records the Dhan schedule observed on 15 November 2026: brokerage min(₹20, 0.03%) per side, sell-side STT 0.025%, NSE transaction charges 0.0030699%, SEBI fees 0.0001%, IPFT 0.0000001%, buy-side stamp duty 0.003%, and 18% GST on brokerage, exchange, SEBI and IPFT charges. STT and stamp are rounded to rupees, other components to paise, half up, per modeled executed order. Entry and exit prices each include 5 bps adverse slippage. This schedule does not claim those rates applied on every historical date. Legacy results retain their fee identity.

Production planning requires an instrument tick associated with the session date. Supplied dated metadata or the public security master observed that session is persisted in dts_instrument_ticks. Unknown or ambiguous ticks block use of the symbol. For the live and champion runs a current master never establishes a past session's tick, and ticks are not inferred from the current share price. The config's ₹0.05 fallback remains for explicit synthetic/research helpers, not the production universe. Historical backfill (the never-counted -bf research run) is the one exception: a past day with no dated ticks borrows today's master, persisted under the separate source dhan_compact_csv_current_proxy so its provenance stays visible. Only when even today's master is unavailable is the date recorded as degraded with no_dated_ticks, and the replay pauses there without downloading bars. Backfill reads its 5-minute bars from Dhan's read-only historical API (DhanBarProvider), which keeps years of history; Yahoo serves only about 60 calendar days. Dhan takes one symbol per request and caps a request near 90 days, so each symbol is fetched once per 80-day window under the operator's tenant and the replayed days read that cache. Daily closes, NIFTY and ticks stay on their usual sources; backfill downloads Yahoo's daily history once for the whole replay and slices it per day (re-fetching only symbols absent from that cache), because one ~140-day download per replayed day got the server throttled by Yahoo. A symbol absent from Dhan's current master (renamed or delisted since) is missing for that day. Off-grid Dhan rows (2026-08-06 carried 12:46 and 13:01 copies of the preceding 5-minute bar) are dropped before validation, which otherwise voids the symbol's day. A provider with Yahoo's retention still forgets never-booked days older than 60 days and starts the replay at the oldest servable day. The service re-runs backfill hourly, so a day paused by one partial response is retried without waiting for a restart.

Exit evaluation follows a contiguous sequence of valid post-entry bars and stops at an unknown interval. If a bar touches stop and target, the stop wins. A gap below the stop uses the bar open; a gap above the target uses the target, with adverse exit slippage. The 15:10 bar can evidence a 15:15 flat exit. A missing bar, absent flat-time price or no post-entry observations leaves exposure unresolved; the service does not invent a stale close or scratch at the trigger price. Unresolved exposure prevents a complete performance verdict.

An unresolved forward position also blocks every later session (recorded as missed with unresolved_prior_session), so a single absent bar would otherwise stop the paper run for good. An admin can close it from the dashboard's Unresolved positions panel on that past day, or with POST /api/daytrader-shadow/signals/{id}/resolve ({"exit_at", "price"}). The price is the operator-observed market price; adverse exit slippage is applied as for modelled exits. The exit must fall on the signal's session, after its entry, by the flat time and not in the future; only a filled, still-open position qualifies. The signal records exit_reason = manual, resolved_by and resolved_at, and the trade is booked with the run's cost model. The affected session keeps its degraded/missed quality — a manual exit unblocks later sessions but is never reported as observed evidence. Paper only: no order is placed.

A champion replaced mid-session (a deploy that changes the rules rolls it over on the spot) has traded the morning but is no longer active, so its day would never close. At the close-of-day run, settle_retired settles that run's open positions from the day's bars, books its trades and closes its day under its own version (job settle:<hash>). The deployed ledger is unaffected: the replacement owns the day from the rollover. A position the bars cannot settle leaves the day degraded with missing_exit for the manual resolve above.

Data validation and session quality

Provider observations require finite positive prices, consistent OHLC bounds, correct session dates, ordered unique five-minute timestamps and valid volume. Zero or unknown volume remains diagnostic data and cannot justify a modeled trigger, fill or exit, but a price-valid zero-volume bar still counts for the opening range and data coverage: Yahoo zeroes the 09:15 bar's volume after the close, which otherwise degraded every session. Yahoo also omits a 5-minute bar in which a thin stock did not trade, and some sessions have market-wide holes (2026-10-15 11:45-11:50). An interior gap after the opening range, with a real bar on both sides (including one that starts a position's exit path), is filled with a flat zero-volume bar at the previous close; it cannot trigger, fill or exit, and only keeps the bar sequence contiguous for coverage and exit tracking. A gap inside the opening range, before the first bar or after the last still disqualifies the stock (2026-09-21: 500 to 524 of 533). One malformed symbol is isolated from the rest of the download. Pre-open history needs the requested endpoint and sufficient valid history; missing symbols remain incomplete and can be retried independently of valid empty tag results. Before the next open Yahoo's daily row for the previous session can carry volume but a NaN close (about half of NSE on 2026-11-17); those symbols take that session's last valid 5-minute close instead, fetched in one batch and marked endpoint_close: intraday_last_bar in the tag metadata.

A complete session requires min_data_coverage_pct = 95% of the expected universe to have dated ticks, pre-open tag coverage and contiguous valid bars from session open through the flat cutoff, with no unresolved admitted account position. One usable stock out of 500 is degraded. Complete data with no signals is a valid zero-trade session.

Session qualityMeaning
completeCoverage and account closure gates passed
pendingWork is unfinished; no complete day is claimed
degradedCoverage or exit evidence is insufficient
missedA forward observation gap cannot be reconstructed as an observed forward session
legacyEarlier data lacks current quality attestation and is excluded from eligibility

Session states, coverage counts, reasons and notification state are durable per run and date in dts_sessions; scheduled work and retry timestamps live in dts_jobs. Non-complete sessions are visible in the timeline and suppress complete cumulative/annualized performance claims. Missing financial values stay unavailable rather than becoming zero. Recovery preserves the forward gap label; later reconstructed research remains replay evidence.

Yahoo Close is already split-normalized even when auto_adjust=False. Setup features use that convention and do not divide by split ratios a second time. Cash dividends remain price moves; this is not a dividend-reinvested total-return series. The provider archives the price convention and observed action metadata. Yahoo history can be revised, so an archived observation does not establish immutable as-filed corporate-action history.

Returns, statistics and benchmark

For a complete account, daily return is net realized P&L divided by start-of-day equity, compounded across sessions. annualised = (1 + cumulative return)^(248 / trading days) − 1. Fewer than 40 sessions gives Too early; an incomplete account gives Incomplete. Invalid/nonfinite NAV or an overflowing annualization yields an unavailable metric. Above-target descriptive performance is not proof of a durable edge.

Account win rate and net expectancy use closed, admitted account trades after modeled costs. The unconstrained signal ledger has separate gross outcomes and gross R multiples. Signal count is not account-trade count, and gross signal win rate is not the account's net win rate. Open/unresolved exposure is explicit. Drawdown cards measure the worst end-of-day fall from a peak; they do not measure intraday maximum drawdown.

Nifty 50 is a context benchmark, from the exact prior-session close before the first selected account day to the exact last selected day. It is unavailable if either endpoint is absent or the account interval is incomplete; the benchmark period is never silently shortened. Charts retain missing-data gaps.

Backfill and durable recovery

Backfill requests one year (trading_days_per_year, 248) of trading sessions before the forward run's start, never overlapping its forward period. It is a separate -bf research run behind Backfill (not counted), with its own statistics. Unavailable ticks or Dhan bars can prevent completion. Backfill runs outside 09:00–15:45 IST, rechecking before each date to spare the forward collection window.

Historical processing stops at its first unresolved date and resumes the unfinished chronological prefix. It does not skip an earlier failure, size later sessions from an incomplete equity chain and then insert the missing day underneath them. Forward jobs persist completion per run and date, with retry/backoff state. A successful champion does not complete a failed challenger. Restart recovery detects overdue forward sessions and preserves missed/degraded status rather than presenting overnight reconstruction as real-time observation. Weekly review is complete only after its result is durable; failed attempts can retry. End-of-day retries are spaced to avoid a tight universe-wide download loop; a session already marked missed is not retried that evening. Bar-archive retries stop once the date leaves Yahoo's 60-day intraday retention, and a legacy archive day is never retried (it needs explicit repair). Today's in-progress session is not reported as an incomplete closed day, so intraday performance and today's realised P&L stay visible until end-of-day processing.

Learning: research champion and challenger

Sunday review starts at 10:00 IST and uses up to the last 60 qualified archived sessions, requiring at least 20 usable review days. It reports P&L by setup, hour and exit reason, plus costs. With no active challenger, proposed candidate or pending promotion, greedy search tries at most 200 variants or 1,800 seconds. A candidate needs at least 30 in-sample trades and a three-percentage-point annualized advantage to become a paper challenger. A config hash already present in run history is not nominated again.

Learnable knobAllowed values
target_r1.5, 2.0, 2.5, 3.0
stop_ruleor_mid, or_low
entry_end11:30, 12:30, 13:30, 14:45
or_minutes15, 30
enabled_setupsAny nonempty subset of the six setup labels above
min_traded_value0, ₹1 crore, ₹5 crore

Sizing, loss limits, costs, slippage, fills and capital are frozen. Each search comparison scores champion, incumbent and candidate variants on identical qualified dates. If any variant lacks its required opening-range coverage or has an admitted unresolved exit, that date is skipped for the whole comparison. A 30-minute opening-range candidate cannot gain by dropping a losing date only from its own score. In-sample search only nominates research candidates.

Forward assessment is fixed to the first 40 session dates observed across either run after the challenger's start. All 40 dates require complete paired data; missing, degraded or legacy dates are not replaced by later favorable dates. The candidate needs at least 30 forward trades, positive after-cost per-trade expectancy, annualized return above 12%, at least a three-point annualized advantage, and end-of-day drawdown no greater than max_promotion_drawdown_pct = 10%.

The lower bound of an approximate paired daily 95% edge interval must also be positive. Returns are paired by date, with a conservative t approximation at the 40-session horizon. Serial dependence and repeated candidate selection remain unadjusted: this is a research filter, not a significance claim for allocating capital. There is no early proposal from repeatedly checking after 20 days. At the fixed horizon successful candidates become proposed; unsuccessful or incomplete candidates retire. Every assessment remains capital_eligible = false.

Paper promotion and selected account history

Telegram only notifies. An admin can promote or reject a proposed paper version through POST /api/daytrader-shadow/versions/<hash>/promote or /reject; other states return 409. The actor and decision time are recorded. Promotion first sets promotion_pending with the next maintained session as its effective date. Today's selected configuration remains stable; activation at that boundary records the deployment timeline and retains former versions' research histories.

The selected paper account carries its actual modeled closing NAV into the newly selected champion's next session. Its continuous return curve follows only the configurations selected on their effective dates. GET /api/daytrader-shadow/deployed returns that track's days, cum_return, quality and deployments. Incomplete selected sessions suppress its complete return.

A version's research history also contains its own hypothetical pre-promotion sessions. If the selected account's handover NAV differs from that version's prior research balance, the difference is exposed as capital_flow, not trading P&L. Version returns compound daily time-weighted returns, rather than comparing raw opening and final NAV across that handover; net P&L sums the daily trading results. Research APIs accept optional version=<config_hash> to inspect retained versions. Neither history represents actual deployed money, and a candidate's earlier hypothetical gains do not become the selected account's earlier gains.

Dashboard and API

The admin-only dashboard and /api/daytrader-shadow/* APIs show summary, session quality, signals, account positions, closed trade history, statistics, versions and the latest review. The account endpoint includes open positions with blank P&L until an evidenced exit. History filters cover dates, recent-session ranges, symbol, outcome and exit reason; totals follow the filters. Each day's signals remain separately inspectable. Switching run or date clears the previous view while loading, so stale requests cannot relabel another selection's trades. Decisions refresh the affected views.

Rules in use, last cycle time, coverage counts and unresolved exposure accompany performance. All figures belong to the selected frozen version or explicitly identified deployment track. Backfill and challenger research are not silently substituted for selected forward history.

Live intraday P&L. For today's live run the page subscribes to /ws/daytrader-shadow (admin session cookie, like /ws/live; query kind/version), which pushes a daytrader_tick every WS_TICK_INTERVAL seconds in market hours and a heartbeat otherwise. While the socket is down the page polls GET /api/daytrader-shadow/live. Each tick carries today's realised P&L, every filled open position marked to its Dhan LTP (read-only quote, shared 5-second cache, paced with the bot's quote quota, resolved under the operator's tenant because socket ticks run off-request) less exit slippage and both legs' costs — the same mark the runner uses for the daily-loss check — and the total. A missing quote leaves unrealised and total unknown rather than zero, and a quote already past the stop or target is flagged. This is a display mark only: the paper engine still books exits from 5-minute bars at its cycles, so the booked exit can differ from the live mark.

Config identity, persistence and operating limits

The service polls every 5 minutes from 09:35 to 10:30 IST, where opening-range breakouts cluster, then hourly at 11:00, 12:00, 13:00, 14:00 and 15:00, with end-of-day processing from 15:40. A universe fetch takes about a minute, so an opening cycle sees a trigger roughly two minutes after its bar closes, inside the five-minute freshness limit. Hourly-only polling saw 185 of 192 triggers on 2026-11-17 too late. After 10:30 the hourly cadence still leaves most later triggers missed, and the page can be an hour stale. A real-time feed, executable-quote checks, liquidity/queue modeling and broker reconciliation would be separate experiments, not capabilities of these paper results.

The shadow calendar fails closed outside maintained years, currently through 2026. Exceptional-hours sessions are excluded. Unsupported years do not fall back to weekday trading, and next/previous-session lookup stops at an unsupported boundary. The calendar must be maintained before processing a new year. This does not change the live options bot's shared calendar.

ShadowConfig fieldCurrent default / effect
rules_version2; separates changed entry, exit and account semantics
cost_model_versiondhan-nse-intraday-2026-11-15-v2; explicit rounded fee schedule
max_signal_age_seconds300; later first observations are missed
min_data_coverage_pct95; minimum session/entry coverage gate
max_promotion_drawdown_pct10; maximum forward end-of-day drawdown for paper nomination
min_days_for_verdict / annual_target40 / 0.12; descriptive reporting threshold and annual target

These are frozen values in arb_bot/daytrader_shadow/config.py, not main-bot runtime settings. The hash includes rule and fee identities. A changed rules version or non-learnable value starts a new research champion and retires candidates built against the old configuration, including pending promotions. Previous records are retained; legacy rows are not relabeled as qualified version-2 evidence.

PostgreSQL stores runs, signals and observation/admission decisions, account trades/days, session work, dated ticks, deployments, reviews and qualified bar/tag archives in dts_* tables. Migration 117 adds the evidence, quality and deployment records to the earlier run/history schema. Do not reset runtime records to retry a job. Rolling back application code can leave the separate daytrader-shadow container running; remove that service explicitly with docker compose rm -sf daytrader-shadow when retiring it.

Credit

The method originated in day-trader-skill by Jakeschincariol (MIT licence, commit 3d0f4ef); the observation, account and quality controls above define this NSE paper implementation.