Overview
How the Math Engine Works
Trade Console uses an advanced mathematical engine to convert thousands of raw broker trades into a perfect accounting ledger. Here is exactly how the data is processed:
1. The FIFO Ledger (First-In, First-Out)
The engine sorts every trade you've ever made chronologically. When you sell 100 shares of a stock, the engine "looks back" in time and mathematically consumes the oldest 100 shares you bought. This is the industry-standard accounting method for calculating true realized P&L.
2. Intraday vs. Delivery Prioritization
Before the FIFO engine looks back into history, it specifically scans the exact day of the trade. If it finds a Buy and a Sell for the same asset on the exact same date, it matches them together instantly as an Intraday Trade. Only the "leftover" shares spill over into the Delivery queue.
3. Active Positions & Live Margins
- Invested: For Equity, this is simply your Qty * Average Buy Price.
- Margin Used: For F&O Shorts, the engine pings Angel One's live Margin API to get the exact overnight span + exposure margin required for your specific strike price.
- Live CMP: When you click Refresh, the system connects to the live market to pull the Current Market Price for all open assets and calculates live Unrealized P&L.
4. Corporate Actions & Stock Splits
Split adjustment is applied to all trades (both buy and sell) that occurred before the split ex-date. This restates both sides to post-split equivalents before FIFO runs — ensuring stocks fully bought and sold pre-split show zero open position rather than phantom shares.
5. The Options Settlement Engine
If you short an option and let it expire, brokers often don't provide an Exit record in your CSV. Trade Console detects expired options, fetches historical closing prices of the underlying from Yahoo Finance for the exact expiration date, calculates whether the option expired ITM or OTM, and automatically generates the correct settlement exit.
6. IIFL F&O Symbol Handling
IIFL stores option contracts as separate columns (Code, Expiry, Strike, OptionType). Trade Console reconstructs the full contract symbol (e.g. COFORGE26FEB1440PE) so that each individual strike gets its own independent FIFO queue rather than being pooled together.
7. The Strategy Recommendation Engine
In the Closed History tab, the engine calculates the exact number of days you held an asset and automatically suggests strategies:
- 0DTE: Buy and sell an option on the exact same day.
- Overnight pre-expiry: Short an option and hold it exactly 1 day.
- Long-term Holding: Any asset held more than 180 days.
Trade Console QA README (Detailed Test Script)
Use this as the master validation checklist after any code/data change. Every item includes what to do and what should happen.
0) Global Preconditions
- Backend URL: Verify correct backend in top settings panel. Save and reload once.
- Data source mode: Confirm whether run is snapshot-only refresh or explicit recalculation flow.
- Broker state: If Zerodha connected, live broker positions should replace stale FIFO-open rows for that broker.
- Cache sanity: If results look stale, run clear action from BROKERS tab and re-upload test files.
1) Top Bar Buttons (Functional Tests)
- Theme: Click once -> dark/light toggles. Reload page -> theme persists.
- Upload: Upload CSV/XLSX -> logs show parse + sync + recalculation trigger; no browser errors.
- Contract Note: PDF upload requires settings PAN where applicable; errors are explicit and readable.
- Export: Export workbook downloads with correct sheets and non-identical tab-specific data.
- Gear (Settings modal): Opens blocking modal; background is non-interactive; close/save works.
- Refresh: Snapshot-first fast sync. Should not auto-trigger full recalculation repeatedly.
2) Filter Bar (Cross-tab Consistency)
- Broker filter: Selecting a broker only shows rows for that broker in active/closed/log tabs.
- Segment filter: EQ/FUT/OPT filtering reflects parsed symbol segment accurately.
- FY filter: Appears only where expected (Closed/Log/Chart contexts) and filters deterministically.
- Search: Symbol search matches uppercase substrings and never crashes render.
3) POSITIONS Tab (Open Positions QA)
- Columns: SYMBOL, BROKER, SEG, TYPE, SERIES, STRIKE, DIR, QTY, AVG PRICE, INVESTED, MARGIN, MTF, CMP, P&L, ROI %, STRATEGY.
- Direction logic: Long rows for net positive qty, Short rows for net negative qty positions.
- CMP/P&L: CMP refresh updates P&L and ROI. Pending fetch may temporarily show loading marker.
- MTF checkbox: For eligible EQ rows, toggling changes invested/margin treatment and ROI basis.
- Live broker merge: Connected Zerodha rows should reflect live `tc_open_positions` and remove stale FIFO-open Zerodha rows.
- No phantom rows: If broker live file says only X symbols open, positions tab should not include old closed symbols.
4) ALLOCATION Tab (Equity Weight QA)
- Scope: Only EQ open positions.
- Sort: Default descending by CURRENT VALUE.
- Value formula: CURRENT VALUE = CMP*Qty when CMP>0, otherwise fallback to Invested.
- Weight formula: Weight % = row value / total EQ value * 100.
- Bar rendering: Bar width proportional to Weight % and visually ordered high-to-low.
5) CLOSED Tab (FIFO Realized Trades QA)
- Columns: SYMBOL, BROKER, SEG, TYPE, SERIES, STRIKE, DIR, STRATEGY, FY, QTY, ENTRY, EXIT, DAYS, P&L, PERIOD.
- FIFO correctness: Entry lots consumed oldest-first after same-day intraday matching rules.
- Days held: DAYS equals Exit Date - Entry Date (calendar day basis in current implementation).
- Strategy tags: Manual tag save persists; recommendation appears only when untagged.
- Date filters: Entry >= from and Exit <= to both apply correctly.
6) TRADE BOOK Tab (Normalized Ledger QA)
- Columns: SYMBOL, BROKER, SEG, DIR, DATE, QTY, AVG PRICE, FY.
- Aggregation: Rows represent grouped standardized trade stream used by FIFO.
- Buy/Sell color coding: Buy shown green/up, Sell shown red/down.
- Manual entries: Add Trade creates new ledger row and triggers recalculation flow.
7) FY SUMMARY Tab
- Group modes: FY->Broker->Segment, FY->Broker, FY->Segment, FY only.
- Totals: Total = Realized + Unrealized for each row.
- Filter compatibility: Broker/segment filters should alter aggregate buckets correctly.
8) P&L and CHART Tabs
- P&L tab: Trend/aggregation should reflect current state arrays (open + closed).
- Stock chart tab: Symbol list loads, period buttons work, buy/sell markers align with trade dates.
- Open+history block: For selected symbol, open position card and trade history table both update.
9) CORP ACTIONS Tab
- Rows: Symbol, ex-date, ratio.
- Search: Corp symbol search filters rows instantly.
- Add/Delete: Insert and delete actions update cache and affect recalculation outcomes.
- Split handling check: Verify pre-split buy/sell quantities are restated consistently.
10) UNTRACKED + MAPPER Tabs
- Unknown symbol detection: Unmapped names appear with broker context.
- Accept mapping: Accept/Add mapping moves item from pending to mapped list.
- Recalculate: Apply & Recalculate uses updated mapping and removes false unknowns.
11) ASK AI Tab
- Prompt/response: Enter question, receive response without tab crash.
- History rendering: Message list persists while tab remains open.
12) BROKERS Tab
- Zerodha card: Connected state, token status, sync/disconnect buttons consistent.
- Uploaded Files section: Shows server archive and/or Supabase summary rows by broker.
- Clear Supabase: Clears uploaded Supabase trade data and reports before/after counts.
- Post-clear check: Refresh list should not repopulate unless broker sync/upload runs again.
13) Settings Modal (Gear)
- Fields: PAN, broker email, API credential fields, display name.
- Load: Existing values fetched from backend settings endpoint.
- Save: Success message displayed and values persist after reopen.
14) Data Pipeline Expectations (Reference)
- Upload: Parse -> normalize -> Supabase upsert with duplicate-safe trade IDs.
- Recalc: Explicitly triggered; scoped recalculation may use dirty symbols from upload response.
- Snapshot: Persisted and reused for fast refresh; recalculation updates snapshot.
- Live merge: Connected broker live open positions override stale FIFO-open rows for that broker.
Temporary QA Testing Tab (Execution Runbook)
This tab is the active, step-by-step testing script for validating uploads, loading behavior, tab rendering, and data accuracy. Use this before and after every release.
A) Test Setup (Run First)
- A1. Backend target: In top panel, verify Backend URL. Click Save, hard refresh once, verify URL persists.
- A2. Clean baseline: Open BROKERS tab -> click Clear Supabase -> confirm success log and counts.
- A3. Snapshot reset: Click Refresh with Shift once (deep rebuild), then normal Refresh once.
- A4. Console visibility: Keep system log expanded while executing upload tests; capture timestamps for failures.
B) File Loading + UI Reload Gap Tests (Critical)
- B1. Empty-state correctness: With clean baseline, open BROKERS -> Uploaded Files list should show empty state message.
- B2. Single-file trigger test: Upload one Angel One file only. Expected: uploaded list refreshes and broker summary appears without requiring full app reload.
- B3. Reappearance regression test: If older files suddenly reappear after one new upload, capture whether source is local archive or Supabase summary row.
- B4. Refresh-only behavior: Without new upload, click Refresh List three times. Expected: deterministic list; no random oscillation between empty/non-empty states.
- B5. Hard-refresh behavior: Ctrl+F5 and return to BROKERS. Expected: same uploaded summary as before refresh (if backed by Supabase data).
- B6. Clear-after-upload: Run Clear Supabase after upload; list should return to empty and stay empty across tab switches.
C) Upload Flow Tests by Broker
- C1. Zerodha: Upload valid trade file(s). Expected: success message, async calc triggered, non-empty Trade Book/Closed where applicable.
- C2. Angel One: Upload file. Expected: broker appears in Uploaded Files summary and in filtered views.
- C3. Upstox: Upload file. Expected: normalized symbols appear; no parser crash.
- C4. ICICI Direct: Upload file. Expected: trades ingested with correct broker label and visible in log.
- C5. m.Stock: Upload file. Expected: broker normalization to m.Stock and rows visible after recalculation.
- C6. IIFL: Upload file. Expected: options symbol reconstruction visible in trade book and FIFO processing.
D) Recalculation + Snapshot Behavior
- D1. Upload-triggered recalc: Upload any file and confirm calculation starts automatically once.
- D2. No infinite recalculation: Reload app after successful run; expected no automatic repeated deep rebuild loop.
- D3. Manual deep rebuild: Shift+Refresh should force explicit full recomputation.
- D4. Delta flow: Mapping changes trigger targeted recomputation (dirty symbols) when applicable.
E) Tab Rendering Integrity (No Stale Content)
- E1. README isolation: Open data tab then README. Expected: no stale data table below README.
- E2. HELP isolation: Open data tab then HELP. Expected: no stale data table below help text.
- E3. ASK isolation: Open data tab then ASK. Expected: ask panel only; no main metrics/table/filter bleed-through.
- E4. TESTING isolation: Open data tab then TESTING. Expected: runbook only; no stale data table.
- E5. Return navigation: Switch back to POSITIONS/CLOSED/LOG and verify normal controls return correctly.
F) Data Correctness Tests
- F1. Trade Book population: After successful upload, TRADE BOOK must show rows with expected broker/segment/date values.
- F2. Closed population: CLOSED tab should populate for closed lots after FIFO.
- F3. Open positions sanity: POSITIONS should not show phantom symbols absent from live broker open positions (for connected brokers).
- F4. Corp action impact: Add split in CORP ACTIONS and verify affected quantity/price restatement after recalc.
- F5. Allocation math: ALLOCATION weight percentages should total approx 100% for EQ rows.
- F6. FY buckets: FY SUMMARY totals should reconcile with realized/unrealized components.
G) ASK AI + Tooling Tests
- G1. Ask request: Submit a simple prompt. Expected: response returns without tab crash.
- G2. Ask history: Multiple prompts should preserve message order while tab remains open.
- G3. Failure handling: With bad backend URL, Ask shows readable network error message.
H) Acceptance Criteria (Release Gate)
- PASS-1: Uploaded Files state is stable across refreshes and tab switches.
- PASS-2: No stale cross-tab UI content in README/HELP/ASK/TESTING.
- PASS-3: Each broker upload path completes parse -> sync -> recalc -> visible data.
- PASS-4: Recalculation behavior is explicit (no unintended loops).
- PASS-5: Core tabs (Positions/Closed/Log/Brokers) show consistent, expected results for same dataset.
| Date | Symbol | Broker | Side | Qty | Price | Value | Note |
|---|
Trade Groups
Analyze scaled trades, log observations, and view key performance metrics.
| Trade Group | Status | Timeline | Invested | OPEN P&L | CLOSED P&L | TOTAL P&L | Days Held | Strategy | Setup |
|---|---|---|---|---|---|---|---|---|---|
| Loading trade view... | |||||||||
| No data loaded. |
Settings
Broker Automation
API Credentials
Personalisation
System Settings
Broker Selection
Connect Angel One
Enter your SmartAPI credentials to enable automated live prices. These are encrypted and stored securely.