QuantStudio -- second-ltp-v10

This is an independent intraday research engine, not verified reference platform engine parity.
All times are Asia/Kolkata. Each strategy uses one index or MCX symbol and 1-24 option legs.
Source data: existing daily Parquet files on E:, read only, one session at a time.
Partial recovered sources are excluded. Missing sessions are not invented; date
ranges run only available catalog sessions. Every skipped session has a reason.

Basic-editor execution assumptions (imported-rule extensions follow below):
- Source precision is one second. Same-second records for a contract are collapsed
  to the final source block/tick. This is a second-snapshot simulation, not an
  ordered exchange event replay. Source files themselves remain unchanged.
- Backwards timestamps are sorted chronologically for simulation and reported.
- Entry uses the last known positive price at or before entry, within quote age.
  Available expiry/strike candidates require a valid price at entry: no future
  prices participate. Expiry rank 0 means earliest available unexpired expiry,
  rank 1 the next. This is not a weekly/monthly exchange expiry-calendar rule.
- ATM is the closest fresh listed strike to SPOT at entry, ties to lower strike.
  Offset is signed ascending listed-strike steps, for both calls and puts.
  Candidate strikes are those with fresh prices at entry. Sparse chains can
  therefore skip physical strikes; use fixed strikes for exact strike placement.
  Premium selection minimizes absolute price difference, ties to lower strike.
- Straddle Width uses the nearest fresh common CE/PE ATM strike, same expiry,
  then target strike = ATM + multiplier*(ATM CE+PE) for CE, minus for PE.
  Positive multipliers move outwards; negative reverse direction; zero selects
  ATM. The nearest fresh selected-side strike wins, ties to lower strike.
- Closest Delta selects the nearest absolute modelled delta (0.30 means 30-delta)
  using fresh entry-time option premium and spot. BSM IV is solved per contract
  inside 0.0001%-500% annual volatility; invalid/unidentifiable prices are excluded.
  Delta is signed positive CE / negative PE in reports. Model delta/IV are derived,
  NOT decoded exchange/vendor Greeks. Rate/dividend are explicit annual percent
  assumptions (defaults zero), continuously compounded; expiry time defaults to
  15:30 IST, editable. Time uses actual calendar seconds / 365 days. Candidate
  quotes may have different ages inside the configured limit. No future prices.
  Trade reports expose spot, IV, delta or straddle premium/target-strike evidence.
- Basic legs enter at the common entry time; imported gates can delay each leg.
  Current-size lots expand to P&L units; old unit definitions remain unchanged.
  Historical lot-size changes are not inferred.
- BUY pays LTP + slippage; SELL receives LTP - slippage, at entry and exit.
  No negative simulated prices are permitted. Fills are LTP assumptions, not
  executable bid/ask prices. No volume, liquidity, queue or partial-fill model.
- Every union timestamp of selected contract updates is evaluated as one snapshot.
  Latest quotes must be within max_quote_age for all active legs. A violation
  excludes the entire day, including earlier simulated trades. Skips stay visible.
- Leg SL/target measures signed raw-LTP movement from executed entry price,
  in premium percentage or points. Zero disables the respective rule.
  A crossed threshold fills at observed LTP with slippage, not at threshold price.
- Portfolio SL/target uses net liquidation P&L of active legs plus realized P&L,
  including round-trip fees and exit slippage. Zero disables the rule.
- Scheduled exit has first priority at exit time, then portfolio risk, then leg
  risk. No risk exit is evaluated at the entry snapshot. Portfolio risk exits all
  remaining active legs. Leg exits leave other legs active. No re-entry in v1.
- Fee per leg per side is a fixed INR amount; no automatic tax/brokerage schedule.
  Enter all intended costs explicitly. Zero means a zero-cost simulation.
- Intraday MTM is net liquidation value including both side fees. Daily equity
  sums closed-day P&L; daily drawdown starts with a zero-P&L high-water mark.
  It is not account equity, margin usage, return percentage or intraday drawdown.

Reports: result.json, strategy.json, trades.csv, daily.csv, equity.csv, intraday.csv.
Reports are written and read back for byte verification in the configured results_path.
AirLiveDrive manages its C: cache/upload spool; no additional full dataset copy.
Dates with no source record have unknown market-session availability, not zero P&L.
Descriptive source labels except CRUDEOIL remain inferred; numeric IDs authoritative.

Not yet implemented: positional trades, arbitrary signal/indicator conditions,
delta-range/IV selection, optimizer,
intraday exchange schedules, historical lot-size/margin masters, or broker/live execution.
The previous 72 trade-price checks validate decoded prices, not full engine parity.

Selection references (not proof of reference platform parity):
https://docs.algotest.in/Time-Based-Algo-Trading/How-to-Master-Backtesting-on-AlgoTest/features/algotest-glossary/
https://www.optionseducation.org/referencelibrary/faq/option-price-behavior
https://www.optionseducation.org/advancedconcepts/volatility-the-greeks

Current-size lots and MCX extension:
QUANTITY AND MCX UPDATE -- 2026-10-07

New editor strategies default to whole lots. Backend expands lots once into the
rupee P&L multiplier before entry costs, leg exits, strategy SL and shared daily
SL are evaluated. A 1-point gain on 2 NIFTY lots is 2*65 = INR130 gross.
Fixed fee remains per leg per side, not per lot. Slippage scales with quantity.
Current sizes apply to ALL selected historical dates as requested; this is NOT
historical lot-size reconstruction. Saved results retain their original sizing.
Legacy strategies lacking quantity_mode stay in units; editing shows legacy mode.
To normalize them, choose Lots, enter intended lots in every leg and save.

Current premium-point multipliers per lot:
NIFTY65 BANKNIFTY30 FINNIFTY60 MIDCPNIFTY120 SENSEX20 BANKEX30.
COPPER2500 CRUDEOIL100 CRUDEOILM10 GOLD100 GOLDM10 NATURALGAS1250
NATGASMINI250 SILVER30 SILVERM5 ZINC5000.
GOLD is 1kg / 10g quotation =100; GOLDM is 100g / 10g quotation =10.
Thus physical trading size is not always the premium-point multiplier.

MCX dropdown uses existing decoder labels. Only ID85 CRUDEOIL has independent
reference platform-export matching; other descriptive labels are inferred, including index
labels. Numeric IDs remain authoritative. Product multipliers assume those labels
are correct. Verify symbol identity before treating inferred-symbol INR results
as validated contract P&L. Unknown ID89 and VIX are not tradable option selections.

The default MCX profile uses synthetic forward for ATM/width/delta. It uses
fresh same-strike CE/PE pairs for the selected expiry, choosing the strike with
minimum abs(CE-PE), lower strike on tie. Synthetic forward F=K+exp(r*T)*(CE-PE).
Each quote must be known at entry and within the age limit; pair times can differ.
No fresh pair means exclusion, not fallback. Fixed strike and premium selection
do not require a pair. Underlying reference is audited in reference_spot for
schema compatibility, with reference_method=same_expiry_synthetic_forward.
MCX delta is Black76 forward delta (discounted by exp(-r*T)); dividend is ignored.
MCX default assumed expiry time is 23:30 IST, editable. Set the appropriate entry,
exit and expiry times yourself: no DST/historical exchange-session master exists.
Intraday only; no overnight holdings, exercise or futures devolvement.

Sources reviewed:
NSE/FAOP/70616 (3 Oct 2025), sizes applicable to Jan2026 onward expiries:
https://nsearchives.nseindia.com/content/circulars/FAOP70616.pdf
NSE current contract information:
https://www.nseindia.com/static/products-services/equity-derivatives-contract-information
BSE disclosure on Sensex20/Bankex30:
https://nsearchives.nseindia.com/corporate/BSE_19112024165318_NSEIntimation.pdf
MCX energy contract specifications:
https://classic.mcxindia.com/products/energy/crude-oil
https://classic.mcxindia.com/products/energy/natural-gas-mini
MCX presentation (contract units and quotation units):
https://www.nagpuricai.org/seminar-presentations/MCX-IPF-PPT-August-2023-2.pdf
Broker current contract corroboration:
https://support.zerodha.com/category/trading-and-markets/trading-faqs/f-otrading/articles/lot-size-for-index-derivatives
https://support.zerodha.com/category/trading-and-markets/trading-faqs/general/articles/how-can-i-trade-commodity-options-in-zerodha

Validation: test_lots_mcx.py and mcx_data_validation.json. Latest-session sampling
at17:10-17:11 with60s freshness completed six liquid symbols; four sparse-symbol
sessions were excluded for unavailable fresh pairs/options. Listed availability
does not guarantee every strategy/time/date can complete.

Imported advanced-rule extension (overrides basic-editor-only limitations):
STRATEGY FILE IMPORT -- 2026-10-07

Open Import strategy files, choose .slstrategies.json or .algtst, inspect mappings,
review the displayed model differences, then Import reviewed strategies. The
checkbox explicitly selects the described LTP research interpretation. Import
does not run a backtest. Edit an individual library row or select up to 1,000 rows
for a combined run. Each imported strategy retains source hash, record number,
source name, warnings and interpretation differences. Import archives the input
locally; repeated imports skip matching source hash/record IDs. Library limit 10,000. Two simultaneous runs share the CPU and 50% engine RAM budget; each can request up to 16 workers.
One unsupported active rule blocks saving the whole file; no silent partial save.

Supplied files:
- MCX - crude.slstrategies.json: six CRUDEOIL strategies map successfully.
- export_r27e3crbestmixedtimes0925.algtst:100 NIFTY/SENSEX strategies map.
- PORT V2 data-only import was added subsequently; see the reference platform profile below.
  No strategy is inferred from a filename.

User-requested expiry normalization:
CRUDE imports use nearest available unexpired option expiry at each initial or
strategy re-entry selection. Old fixed dates and Current Month labels are stored
as source_expiry, not imposed on subsequent sessions. Re-entry AT COST keeps the
same contract by definition. Existing native explicit expiry_date rules remain
available internally and are not silently replaced for other source formats.

Implemented for the supplied readable files:
- Closest Premium (SAE rule): only positive fresh quotes in the selected expiry
  and CE/PE side are eligible. Target >= Rs 10 permits at most target x 1.40;
  target < Rs 10 permits at most target x 2.00. No lower percentage bound.
  Nearest premium wins; equal distance selects the lower strike. No eligible
  quote means no selection; never exceed the cap or borrow another expiry.
  This cap does not apply to profit-target exits or Premium <= / >= rules.
  All legs are selected before initial entry. For plain Closest Premium with
  next-tick handling, skip initial entry unless all legs can be selected before
  Start Time + 120 seconds (index-triggered entry: activation + 120 seconds).
  ORB and Wait & Trade / momentum strategies are exempt from this timeout;
  their existing trigger and SqOff rules apply. Re-entry timing is unchanged.
- Current-size whole lots and portfolio quantity/risk multipliers.
- ATM/listed offsets, fixed ATM strike-point offsets, closest premium, absolute
  delta, ATM straddle width with source plus/minus direction.
- Option momentum in percent/points, up/down. Select contract at scheduled entry,
  freeze its reference premium, then wait for the threshold. No future prices.
- DelayedBreadthLow/High: fixed observed-price range from scheduled entry through
  entry+Nminutes exclusive; enter at first later price at/beyond low/high.
- Leg percent/point SL and targets; step trailing SL. Every favorable X increment
  from actual entry advances stop by Y. Update after current-price exit checks.
- Re-entry at cost: same contract, next second or later, price at/better than
  original entry; observed fill plus costs, same leg SL/trailing rules reset.
- Immediate leg re-entry supported internally; strategy re-execution after SL or
  target reselects contracts at the next eligible second. Counts, cutoffs and
  configured delay enforced; no same-second exit/re-entry loop.
- Square-off-all, remaining-leg SL-to-cost, overall strategy amount/entry-premium
  percent SL, per-lot amount thresholds, combined SL continuous wait seconds,
  losing positions only on combined SL, strategy target.
- Shared portfolio daily SL/target closes every active strategy, cancels all
  pending momentum/re-entry orders and prevents the day's later scheduled entries.
  States reset next session. Realized+running net P&L and fees/slippage included.
- Weekday filters and DTE. DTE0 means expiry date. DTE1+ counts exchange trading
  dates using published 2026 NSE/BSE/MCX calendars, independently of tick coverage.
  Other years retain observed exchange dates as a fallback. Unknown calendar
  coverage through expiry excludes the session. See SCRIPT_BACKTEST.txt.

Model differences that require review on import:
AlgoTest WeeklyOldRegime is retained as source intent but is interpreted using
actual available recorded expiries; legacy synthetic-expiry adjustments are not
reproduced. Legacy profiles use synthetic forward; reference platform imports use recorded futures.
MPP/limit queues, routing latency, broker-held stops, order lead seconds and
sequential broker dispatch cannot be reconstructed from LTP. The research model
uses nominal strategy clocks and observed LTP +/- configured slippage.
All thresholds can gap. Source 15:32-15:36 exit times are preserved; missing/stale
required quotes exclude a session. No automatic exit-time correction.

Timing and accounting:
Imported rules evaluate each second using last-known quotes within max_quote_age.
Required stale active or pending quotes exclude the entire strategy-day; shared
risk mode excludes the whole shared day if required data before lock is missing.
No-fill / filtered sessions are zero-contribution completed sessions with notes;
completed-session win rate consequently includes these zero-contribution dates.
Source execution parity has NOT been established. Test results verify our explicit
rules, not matching another platform's fills, Greeks, calendars or performance.

Imported advanced rules survive Save/Update, Copy and leg removal/reordering by
the editor's row association. Expand Imported rules active in this editor to
inspect their JSON. Basic visible controls edit timing/quantity/selection/risk;
advanced momentum/re-entry/trailing rules currently come from the imported file.

Sources used for rule interpretation:
https://docs.algotest.in/Time-Based-Algo-Trading/How-to-Master-Backtesting-on-AlgoTest/features/algotest-glossary/
https://docs.algotest.in/execution-settings/trade-monitoring/
https://algotest.in/forum/d/912-re-entry-at-cost
Local user-provided MCX engine and StraddleLab importer sources, read-only.

Validation receipts: import_browser_validation.json, supplied_import_validation.json,
lots_browser_validation.json. Deterministic rules: test_import_rules.py.

Stoxxo PORT V2 import (v4):
- Data-only V2 decryption and 58-field binary leg reader; no executable or SQL.
- Reviewed time-based relative-strike MCX profiles only. Unknown columns, leg
  rules and secondary/composite variants fail explicitly. Unsupported exports
  are not treated as basic strategies. Source files are archived unchanged.
- Source fixed / CM expiry uses nearest available at each entry as requested.
- Shared reentry_total_count applies across portfolio SL and target actions.
  Per-trigger caps also apply. A completed cycle cannot retrigger while waiting.
- Source portfolio re-execute delay is stored in milliseconds and rounded up
  to data seconds. Earliest restart is the next second, before cutoff and exit.
- Modelled SafetySeconds defers own strategy risk checks after each cycle entry.
  Shared daily SL/target and scheduled exits always take precedence.
- Profit lock activates on cycle net P&L >= activation. Lock floor is floor +
  floor((peak eligible P&L - activation)/step) * raise_by. It never decreases.
  Amounts use risk_per_lot when enabled. State resets for each new cycle.
  A lock breach closes all active legs, cancels pending entries and ends the
  strategy for the day. Observed gap prices can produce P&L below the lock.
- These are disclosed LTP research semantics, not proven Stoxxo event parity.
  Vendor lock-exit action chaining, safety-clock interaction, monitoring cadence,
  premium comparison/freak protection, order retries and routing are not replayed.

v10 low-premium carry (owner extension, 13-Oct-2026):
An already open NFO/BFO/MCX option leg can retain its latest recorded positive
premium strictly below Rs 0.40 beyond max_quote_age. Exactly Rs 0.40 is excluded.
This extends the earlier exchange-specific minimum-premium exception.
It is not an immediate exit trigger: the configured exit and existing risk
rules still decide when to close. Any newer observed tick replaces the carried
premium. Never look ahead, force the premium, or fill an initial/pending/re-entry
order using this exception. Other stale prices retain the ordinary gap policy.
Fees/slippage still apply, and exit_quote_time retains the actual source time;
daily warnings disclose carried closing quotes. Existing session-exit fallback
rules remain separate. New runs use this behavior; saved reports are unchanged.

V5 missing-quote policy (subject to the v10 low-premium exception above):
New and existing definitions without an explicit policy use next_tick. A stale
active quote pauses the simulation clock until the required active-leg quotes
are fresh again. Shared-risk mode pauses the whole basket; independent members
wait separately. Risk checks, entries, and fills only resume at the actual later
time. No future price is assigned to an earlier timestamp. Scheduled entries
inside a pause are delayed (or blocked by a shared stop on resume); scheduled
exits may occur after their configured time. Pending entries retry on later ticks.
Continuous SL-wait timing resets over a gap. Gap times appear in daily warnings.
If no usable later quote exists that session, the session still reports the
unresolved data condition rather than inventing an exit or a completed P&L.
Explicit gap_policy=strict preserves the earlier exclusion model.

v8 strategy entry timing (owner correction, 13-Oct-2026; plain Closest Premium exception added 26-Oct-2026):
There is no automatic five-minute initial-entry deadline. Initial legs wait for
their configured momentum/opening-range conditions and usable quotes before
the effective strategy exit time. Entries at or after that exit are disallowed.
A condition that never triggers still produces no trade; no fill is invented.
The obsolete initial_entry_window_seconds field is discarded during validation
so existing/imported strategies also use this behavior on their next run.
Leg re-entry, portfolio re-execution, SL/target, quote-age, gap-resume, scheduled
exit and late-exit fallback rules retain their existing delays and cutoffs.
Applies to new runs of existing/imported strategies; saved reports are unchanged.
Exception: the plain initial Closest Premium selection described above now has
a two-minute deadline. ORB and momentum/Wait & Trade retain this v8 behavior.

Strategy editor: visible Strategy rules section includes combined SL in rupees
or entry-premium percent, per-lot currency basis, losing-only exit, SL to cost,
strategy re-execution limits, shared cap, delay/cutoff, and profit-lock steps.
Premium-percent SL = total quantity-weighted cycle entry premium * percentage.
It compares cycle net loss including configured fees/slippage. Risk basis does
not multiply that percentage threshold again. Zero SL disables the rule.

v6 adds optional slippage_percent (default zero). Each entry and exit adds an
adverse percentage of the observed premium, rounded to the nearest paisa using
Python rounding, in addition to configured fixed-point slippage. This cost is
part of risk-trigger calculations, not merely deducted after the backtest.
Nonzero percentage slippage uses the advanced engine. The editor exposes both
cost inputs and visible weekday / DTE controls. Choose all days, selected
weekdays, selected DTE values (0-30), or the intersection of both. DTE counts
exchange trading sessions; DTE 1 is Friday before an ordinary Monday expiry. The
selection is saved with each strategy and retained by Edit, Copy and combined
runs. All days clears inherited filters. Nonzero DTE requires calendar
coverage through expiry, not expiry-day prices; absent coverage excludes the strategy-day with a
data-gap reason, rather than retrying it as a missing quote. Script backtest
uses the same date counting; its entry-gate semantics are in SCRIPT_BACKTEST.txt.

Expiry research uses a bounded vectorized version of the same paired-leg basket
rules without re-entry, leg exits or trailing. First/last expiry shortlist runs
are replayed against the production engine; synthetic parity tests cover gaps,
delayed entry/exit, costs and premium stops. Research excludes exits after 23:00.

reference platform PORT V2 PROFILE -- 2026-10-10
Existing strategies retain their saved settings. Re-import older reference platform portfolios
or explicitly edit Costs & Data to select the corrected profile. Old results remain
historical records and are not rewritten.
- Data-only decoding supports reviewed unprotected V2 exports. SQL is parsed as
  literal fields and never executed. Unknown active rules block the entire import.
- Saved expiry is preserved by default; nearest expiry is an explicit override.
  Imported portfolios start disabled. Source hash, record, profile, expiry and
  FreakProtect choice are part of duplicate prevention and stored provenance.
- A saved re-execution count is shared across SL and target restarts. Zero delay
  restarts at the exit snapshot. Positive delays and cutoff still apply.
- Execution lookup uses the first raw record at an exact timestamp, and the last
  preceding record between timestamps. Signal filtering never substitutes fills.
- MCX ATM selection uses the first fresh recorded future whose expiry is on/after
  the option expiry. Missing futures do not silently fall back to synthetic prices.
  All 180 reference underlying-entry values match this lookup in the five sessions.
- PORT does not contain global FreakProtect settings. Import review requires the
  user to check Strong (reviewed default) or Off against the source backtest.
  Off uses the last source signal quote each second. Strong first filters raw
  option ticks: for prices above 25 and intervals under 7 seconds, reject moves
  exceeding 2.7% (maximum old/new premium >=200), 5.5% (>100), or 11% otherwise.
  Strong then maintains separate per-execution protection: for premiums above 20,
  reject changes within 7 seconds exceeding 2.5% (new premium >=200), 5% (>100),
  or 10% otherwise. Rejected ticks do not update filter state. Threshold equality
  is accepted. Duplicate records are processed before taking each last snapshot.
  Each new leg execution initializes its own state from the known entry quote.
- Risk checks use accepted signal quotes; actual close price/accounting use the
  independent execution lookup. Thus realized P&L can differ from the threshold.
  Configured costs still apply; reference replay uses zero fees and slippage.
- Dynamic slippage is not enabled automatically or implemented as a vendor model.
  Fixed-point and percentage costs remain explicit editor settings. The reference
  metadata records dynamic slippage Off; its audited fills match raw tick prices.

VERIFIED SCOPE
Saved reference platform v1.0.2.114 run 11 (ROLING), six CRUDEOIL ATM 3000/3000 REX3
portfolios, nearest expiry, FreakProtect Strong, dynamic slippage Off.
Dates: 2026-09-28, 2026-09-29, 2026-09-30, 2026-10-01, 2026-10-05.
30/30 cases and 180/180 trades match contract, side, quantity, entry/exit time,
entry/exit price and net P&L exactly. Combined P&L is INR113,980.
The previous seven differences are resolved without date-specific adjustments.
Other dates/strategies, intraday equity/drawdown, all vendor protection rules and
the currently open v1.0.2.115 are not certified. See reference platform_verification.json
and Backtest Results -> reference platform comparison for the evidence and its scope.

LATE INDEX EXIT FALLBACK -- 2026-10-10
For NSE/BSE index options, the default late_exit_policy is index_1530_fallback.
When the requested exit is after 15:30 and the final positive option tick in
the source session cannot cover that exit within max_quote_age, the effective
scheduled exit is 15:30. The requested time stays in the saved strategy.
This is a retrospective data-availability convention, not an assertion about
the exchange calendar. Later recorded sessions keep the requested exit.
Spot-only updates do not establish option-session coverage. Isolated stale
contracts on an otherwise extended session follow ordinary quote-gap rules.
The closing quote must be positive, at or before 15:30, and within quote age
unless it qualifies for the v10 recorded low-premium carry above.
There is no invented fill and no entry at or after the effective exit.
MCX is unaffected. Set late_exit_policy=strict to disable this fallback.
Daily warnings and trade fields requested_exit_time, session_exit_time and
exit_fallback record the decision. Shared baskets use each member session exit.


PARALLEL WORKERS AND MEMORY
The engine detects physical RAM and targets 50% for the Python server plus its day workers (32 GB computer: 16 GB; 8 GB VPS: 4 GB). It starts conservatively using the largest catalogued combined session: 0.5 GB process overhead, 384 bytes per tick and 0.025 GB per strategy, with a 0.75 GB minimum. Missing size metadata retains the conservative fallback of at least 2 GB per symbol, larger for large baskets. Auto starts with at most four workers; a selected count is the maximum, limited by CPU threads, available sessions and sixteen workers.
After completed days provide measured worker peak working sets, the scheduler sizes future workers from the highest observed peak and largest measured source, projected to active days and the next twice-maximum-worker sessions, with a 35% margin and a 0.25 GB minimum. The calibration is updated as larger days complete. A tiny early source is not permanently extrapolated to the largest day years later; approaching larger sources still reserve headroom before admission. It measures whole-engine resident RAM and available system RAM at most once per second. It can add two workers every two seconds when headroom permits. It reserves 10% of the engine budget, plus 10% of physical RAM for other programs (minimum 0.5 GB, maximum 2 GB). If RAM pressure rises it stops dispatching new dates and retires idle workers; busy workers finish their current day before retirement. Missing telemetry reverts to conservative allowances. The coordinator and buffered results are included in measurements. This is a soft admission budget, not an OS-enforced cap: active days may produce transient peaks above the target.
Free workers can start later dates while earlier dates are still running. Results are merged chronologically, with at most twice the current worker admission limit retained as running or buffered dates; when that limit decreases the existing buffer drains before new submissions. Cancellation stops new submissions and saves already submitted dates. Resource displays distinguish the current worker admission limit from actual resident Python worker processes; those may differ during startup, retirement and the final days of a run.
The resource strip reports resident working memory summed over the Python server and its direct Python workers, separate from the desktop shell. Shared pages can be counted in more than one process. CPU percentage is normalized to all machine CPU threads. Measurements update at most once a second. The app does not allocate extra RAM simply to fill its budget.

CPU WORK REDUCTION -- 2026-10-10
Engine build cpu-efficient-snapshots-v1 reuses the quote index for repeated
lookups at one timestamp, rechecking quote age and the execution lookup policy
each time. A different timestamp, including a backwards strategy clock, performs
a fresh search. Loaded quote arrays remain read-only during simulation.
Unchanged positions reuse their liquidation calculation within one snapshot;
re-entry creates a new position and is recalculated even at that same timestamp.
Realized totals retain NumPy's summation order but update only after closes.
Small active-leg scans avoid temporary NumPy arrays, cutoff times are parsed
once per strategy state, and repeated report time labels use a bounded cache.
Duplicate-tick counts use vectorized counting without changing tick ordering.
These optimizations do not throttle CPU, change worker/RAM limits, skip market
snapshots, change fills/risk rules, or reduce report detail. CPU can still exceed
50% momentarily; total CPU-seconds and elapsed time are separate measurements.
The health endpoint and saved execution metadata expose the loaded engine build.

RUN AND REPORT TIMING -- 2026-10-11
New runs record monotonic wall-clock timings separately from worker CPU time:
- Backtest run time: execution setup, source loading, simulation, chronological
  merging, daily CSV streaming and worker shutdown.
- Report save time: final streamed-file checksum verification, report summaries,
  serialization, writes/readback verification and saved-history update.
- Total time: run time plus report save time; parallel worker durations are not
  added together. It excludes client polling/display delay and the small final
  timing-metadata commit itself. Rendering a saved report later does not change
  its recorded original run time.
Timings update while running/saving and are persisted in result.json and the
standalone HTML report. Fixed-size verified metadata slots avoid rewriting large
reports just to record the time taken to save them. Old elapsed_seconds remains
the legacy scheduler measurement for compatibility, not total time. Old reports
without measured save time show Not recorded for both save and total time.

EXPIRY AND REPORT STORAGE -- 2026-10-11
Imported commodity CM means the nearest unexpired monthly contract, rolling
into the following month after expiry. Explicit fixed dates and independently
configured calendar-month restrictions retain their meaning. The editor shows
imported restrictions; choosing an available-expiry rank explicitly clears them.
Entry preparation stops if the requested expiry does not exist in the session's
contract inventory. Transient missing quotes continue retrying on later recorded
ticks, without using future prices or extending the configured exit time.
New intraday.csv and strategy_intraday.csv files are stored as lossless .csv.gz
files. Every CSV row is retained; no sampling is applied. App downloads stream
normal decompressed CSV with bounded memory. Old uncompressed CSV reports remain
supported. The stored .gz files may also be extracted with a gzip-capable tool.
Expiry-only read preflight (zero-dte-footer-v1)
For advanced strategies with DTE [0] and next-tick quote handling, new runs
inspect Parquet expiry min/max statistics before loading ticks. If every row
group proves that the session date is absent, the date produces a zero-P&L
no-trade result with an explicit metadata-exclusion note. No prices are read
or simulated for that source. Possible expiry dates, incomplete statistics,
other DTE settings and strict quote handling use the original simulation.
Independent symbol groups require every member to qualify. Shared portfolio
or tag risk requires every member of the whole basket to qualify; mixed
baskets retain their original shared clock. Dates stay in chronological daily
reports. On these no-trade dates, tick-level data warnings and flat intraday
rows are replaced by the metadata exclusion and a zero point at entry time.
Saved source evidence records read_mode=expiry_metadata_only; execution
records tick_files_avoided. Existing saved reports are not rewritten.
Mounted-drive providers can still perform network I/O for metadata reads.


Optional index movement entry (16-Oct-2026):
index_movement = {points: positive decimal, direction: either|up|down,
monitor_time: HH:MM:SS}. monitor_time is optional for legacy definitions and
defaults to strategy entry_time there; newly enabled UI rules use 09:15:00.
NSE/BSE indices only, default disabled. Capture a fresh execution-policy SPOT
quote at monitor_time (preceding quotes within max_quote_age allowed).
No futures/synthetic replacement or forward rebasing. Missing baseline excludes
the day even with next_tick. Monitor net displacement, not cumulative travel,
on the per-second clock extended back to monitor_time. Inclusive +/-X or signed
X latches once per daily state, strictly before its effective exit. The latch
survives a price reversal. Option selection and entry rules start at the later
of the threshold hit and strategy Start Time; positions cannot open earlier. Strict monitoring
gaps exclude the session; next_tick waits for fresh SPOT and discloses gaps.
At this later activation select every leg and start its option momentum/ORB rules. An
option quote gap can still delay selection under existing gap rules. Keep
exit, shared/tag risk priority, filters and costs unchanged. Re-execution and
leg re-entry retain activation, without another index-movement wait. Shared
clock gaps retain their existing no-evaluation semantics. Save reference and
trigger and activation timestamps, actual quote timestamps, prices and rule in reports.
No threshold hit yields a zero-trade day. Historical reports are unchanged.
