Functional Workflows & Diagrams

Functional Reference

How Intellect FinLab works end-to-end β€” every major workflow, decision flow, and system behaviour with flow diagrams. From market open to trade close to session wealth accounting.

Full Trade LifecycleSignal Pipeline Risk Gates (8 checks)LP Shield Flows Wealth CompoundingAlert Routing Backtest PipelineAI Discovery
πŸ”­
Section 01
System Overview
Intellect FinLab is an end-to-end autonomous options trading system. Once running, every step from signal to close to wealth accounting is fully automated.
⚑
Core Principle

Every decision in the system is deterministic, auditable, and recoverable. No signal is acted on without passing all risk gates. No trade closes without updating the lifecycle DB. No session ends without reconciling the wealth model against the plan.

End-to-End System Flow β€” Market Open to Wealth Updated
Market DataIBKR bars
β†’
80+ Scannerstechnical signals
β†’
Signal Poolthread-safe store
β†’
Strategy Enginepattern + Veera Rules
β†’
Risk Gates8 checks
β†’
Executionstrike pick Β· submit
β†’
LP Shieldmonitor Β· protect
β†’
Close & Wealthaudit Β· compound
01
πŸ“‘
Market Data Ingestion
IBKR price feeds stream real-time bar data across all 6 instruments. FreshnessMonitor flags stale feeds before they influence decisions.
LIVE
02
πŸ”
Signal Scanning β€” 80+ Scanners
Each scanner evaluates technical conditions on its timeframe. 4-layer defence stack: config gate β†’ market hours β†’ cooldown β†’ bar identity. Signal published to pool on pass.
concurrent
03
🧠
Strategy Evaluation β€” Hunter Loop
Hunter Loop wakes instantly when pool.publish() fires. Evaluates all enabled strategies in priority order. Pattern match + Veera Rules + context/trigger confirmation.
<3ms
04
⛩️
Risk Preflight β€” 8 Gates
Market gate Β· existing position Β· daily loss limit Β· max positions Β· gamma exposure Β· staleness guard Β· capital sufficiency Β· option viability. ALL must pass.
GATED
05
πŸ“
Options Selection Pipeline
Delta-target strike selection via GreekCache + LiquidityFilter. DeltaStrikePicker finds closest delta match. ExpiryUtils resolves 0DTE contract.
<8ms
06
⚑
Order Submission
Market BUY via ib_async. OrderStatusCache provides O(1) confirmation. Fill event dispatched by V2FillDispatcher to lifecycle bridge β†’ DB write.
~35ms fill
07
πŸ›‘οΈ
Loss Protection Daemon
LP thread arms immediately on fill. Grace period β†’ fast poll (5s/10min) β†’ normal poll (30s). Rules 1–6 active. Limit sell T1 placed and monitored.
ARMED
08
πŸ’°
Close & Wealth Accounting
On SELL_FILLED: lifecycle DB β†’ CLOSED β†’ WealthManager updates capital β†’ milestone check β†’ TradeDiary β†’ ws/wealth WebSocket β†’ Telegram + email alerts.
+5ms
πŸš€
Section 02
Startup Sequence
Deterministic 10-step startup sequence completing in under 10 seconds. Every step logged with [STARTUP] prefix. System is trade-ready after step 10.
1
Build Container
build_container() instantiates all 40+ services and wires dependencies via DI. Container stored on FastAPI app state.
2
DB Path Authority
DBPathAuthority validates all 3 DB paths exist and are accessible. Detects stale duplicates or mismatched environment paths.
3
Startup Invariant Check
StartupInvariantChecker validates config integrity, environment consistency, and required table presence.
4
Apply Config
RuntimeControlService loads all config domains from config DB into live services. Establishes initial state.
5
Runtime Sync
RuntimeSyncWorker starts IBKR state sync loop. Heartbeat established β€” notify_tick() begins firing on bar events.
6
Delta Ladder Pre-Activation
DeltaLadderWorker pre-activates ES, SPX, NQ symbols so greek data is available before first scanner fires.
7
Lifecycle Reload
TradeLifecycleService reloads all active (non-closed) trades from lifecycle DB into RuntimeStore. In-progress positions resume monitoring.
8
Promotion Sync
PromotionSyncWorker imports any un-promoted legacy diary entries into the modern lifecycle DB.
9
Broker Reconcile
BrokerTradeReconciler (delayed 8s to let IBKR settle) reconciles TWS fills with lifecycle DB. Catches any fills that landed during restart.
10
Trade Story Service Init
TradeStoryService initialises timeline service. System is now fully trade-ready. [STARTUP COMPLETE] logged.
πŸ”„
Section 03
Full Trade Lifecycle
Every trade passes through a deterministic sequence. Each stage transition is atomic β€” written to the lifecycle DB before the next step begins. Crash-recoverable at any stage.
⏱️
Micro-Timing Breakdown

Scanner fire T+0ms β†’ Preflight complete T+3ms β†’ SafeLock acquired T+5ms β†’ Strike picked T+8ms β†’ Order submitted T+12ms β†’ Fill confirmed T+35ms β†’ LP armed T+36ms β†’ Telegram alert T+~800ms (async, non-blocking)

Trade Stage Progression β€” Full Lifecycle
SCANNER SIGNAL
β†’
STRATEGY PASS
β†’
HUNTER OK
β†’
OPTION SELECTED
β†’
WEALTH SIZED
β†’
BUY SUBMITTED
β†’
BUY FILLED
β†’
SELL SUBMITTED
β†’
SELL FILLED
β†’
CLOSED
β†’
WEALTH UPDATED
πŸ“‘
Section 04
Signal Pipeline β€” Scanner to Pool
Scanners run on their own timer loop via ScannerRunner and evaluate technical conditions on each cycle. When all 4 defence gates pass, the signal is published to SignalPool.
CategoryRepresentative ScannersLogic Type
FibonacciSPX_FIB_1HR_CALL/PUT Β· ES_FIB_CALL_1HRState-based β€” fires while price is in fib zone
EMA CrossSPX_V3_CALL/PUT Β· ES_CALL_V3 Β· NQ_CALL_V3Cross-based β€” fires on the actual cross bar
MACDSPX_10MIN_MACD_UP/DOWN Β· SPX_1HR_MACD_UPCross-based β€” MACD signal line cross
Momentum / SMISPX_10MIN_MOMENTUM_UP/DOWN Β· SPX_4HR_STOCHASTICState-based β€” SMI Ergodic level threshold
ADX / TrendSPX_ADX_5M Β· ES_ADX_5MThreshold β€” ADX > 20 strength gate
RSISPX_15M_RSI_OVERSOLDThreshold β€” RSI level reversal
Zone BreakoutSPX_ZONE_BREAKOUT_CALL/PUT Β· ES_ZONE_BREAKOUTState β€” price outside consolidation box
TrifectaSPX_EMA21_TRIFECTA_CALL/PUTMulti-condition AND β€” EMA21 + MACD + momentum
CorrelatedSPY_21_200_CALL/PUT Β· VIX_21_200_CALL/PUTCross-based on correlated instrument
🧠
Section 05
Strategy Evaluation Flow
Every Hunter Loop cycle evaluates all enabled strategies in priority order. The first strategy whose scanner patterns appear in the Signal Pool (within the confirmation window) proceeds to risk gates.
Strategy Evaluation Cycle
Signal Poolsnapshot()
β†’
Strategy Listpriority order
β†’
Pattern Matchcall/put in pool?
β†’
Veera Rulesmarket regime pre-filter
β†’
Hunter Gatecontext + trigger
β†’
Risk Preflightall 8 checks
πŸ•
Multi-Scanner Confirmation Window

If a strategy requires 2+ scanner patterns (e.g. SPX_FIB_1HR_CALL AND SPX_ADX_5M), both must appear in the Signal Pool within scanner_confirmation_window_minutes (default 5 min) of each other. This prevents stale signals from creating false entries.

⛩️
Section 06
Risk Gate Decision Flow
Risk gates are evaluated sequentially. ANY failure blocks the trade. The blocking reason is logged and optionally alerted. Gates can never be bypassed.
#GateCheckFail Action
1Market GateIs the trading gate OPEN?Block β€” log MARKET_GATE_CLOSED, alert if configured
2Existing PositionNo open position in same instrument + directionBlock β€” DUPLICATE_POSITION logged
3Daily Loss LimitToday's PnL > configured daily loss ceilingBlock β€” auto-close market gate, CRITICAL alert
4Max Open PositionsOpen count < configured maxBlock β€” wait for existing position to close
5Gamma ExposureNet gamma within configured upper/lower boundsBlock β€” GAMMA_OVEREXPOSED
6Staleness GuardPrice feed freshness within thresholdBlock β€” STALE_PRICE_FEED
7Capital SufficiencyWealthManager has capital for β‰₯ 1 contractBlock β€” INSUFFICIENT_CAPITAL
8Option ViabilityGreeks loaded, IV not extreme, bid price availableBlock β€” retry after greek freshness
πŸ”€ Risk Gate Decision Tree β€” Sequential Evaluation
Strategy PASS
Gate OPEN?
YES βœ“
NO β†’ BLOCK
No Dup Position?
YES βœ“
NO β†’ BLOCK
Loss Limit OK?
YES βœ“
NO β†’ CLOSE GATE
Max Positions?
OK βœ“
FULL β†’ WAIT
Gamma OK?
OK βœ“
OVER β†’ BLOCK
Capital OK?
OK βœ“
LOW β†’ BLOCK
βœ“ EXECUTE
πŸ›‘οΈ
Section 07
Loss Protection Flow
LossProtection starts its daemon thread the moment a fill is confirmed and stops only when the position fully closes. Rules 1–6 run in coordinated polling loops.
LP Daemon Lifecycle
BUY FILLEDLP.start()
β†’
Grace Periodprotect sell 15 min
β†’
Fast Pollevery 5s Β· first 10min
β†’
Normal Pollevery 30s Β· after 10min
β†’
3:30PM GateEOD handling
β†’
EOD Forcemarket sell 15:55

3:30PM Handling Modes

ModeActionUse When
modify_to_entryAtomic cancel-replace: moves limit sell to entry + breakeven % (default +1%). Ensures exit at breakeven or better.Default β€” protects against late-day reversal
alert_onlySends Telegram + email alert only. Sell order unchanged. Operator decides action.Manual oversight preference
force_closeMarket sell at exactly 3:30PM ET. No price protection.Risk-limited environments only
πŸšͺ
Section 08
Exit & Close Flow
Four exit pathways β€” all converge on TradeCloseService, the single close path. On close: lifecycle DB updates, wealth model updates, alert dispatched, Trade Story finalised.
Exit PathwayTriggerOrder Type
Target Hit (T1/T2/T3)Limit sell placed at entry fills at target priceLimit sell β€” placed at entry, monitored by LP
Trail StopV2PositionWatchdog detects reversal below trail thresholdAtomic cancel-replace to stop price
EOD Force CloseRule 5 β€” 15:55 ET non-negotiableMarket sell β€” no exceptions
Manual CloseOperator presses Close button in dashboard Positions pageLimit sell at mid-price
Post-Close Actions β€” Automatic Chain
SELL_FILLED
β†’
CLOSEDlifecycle DB
β†’
WEALTH_UPDATEDcapital + ladder
β†’
TradeDiarylog with greeks
β†’
Alert DispatchTelegram + email
β†’
ws/wealth firesdashboard updates
βš™οΈ
Section 09
Config System Flow
All configuration flows through the config DB. Changes made in the operator console take effect within 5 seconds via TTL cache expiry β€” no restart required.
Config Change Propagation
Operator UIConfig Console
β†’
FastAPI RoutePUT /config/:domain
β†’
ConfigServicewrite to config.db
β†’
TTL Expires5s max lag
β†’
Services Re-readchange is live
🎯
Section 10
Instrument Configuration Reference
Per-instrument settings in config_options table. Each of the 6 instruments is configured independently β€” different deltas, different entry windows, different gamma bounds.
ParameterPurposeRecommended
delta_callTarget delta for call strike selection. Higher = more ITM.0.30
delta_putTarget delta for put strike selection.0.25
trade_preferencePrimary instrument for contract sizingES
contract_months0 = 0DTE Β· 1 = weekly Β· 2 = monthly0 (0DTE)
entry_start_timeEarliest allowed entry time (ET)09:45
entry_end_timeLatest allowed entry (LP handles anything after)15:00
gamma_upper_boundMax net gamma β€” long gamma limit0.15
gamma_lower_boundMin net gamma β€” negative exposure toleranceβˆ’0.10
call_side_enabledAllow call entries without affecting putstrue
put_side_enabledAllow put entries without affecting callstrue
πŸ”¬
Section 11
Strategy Configuration Reference
Each strategy in config_veera_strategies is independently configured. Creating a new strategy from the UI generates a DB row β€” no code change required.
πŸ”‘
Key Strategy Config Fields

scanner_patterns_call/put β€” which scanners trigger entry Β· target_profit_pct β€” exit target (23%) Β· shield β€” rapid_shield or day_shield Β· wealth_model β€” capital plan override Β· veera_rules_enabled + individual rule toggles Β· hunterloop.mode β€” standard or context_plus_trigger Β· priority β€” evaluation order (1 = highest)

πŸ“Š
Section 12
Scanner Configuration Reference
Each scanner has independent settings in config_scanner. Global settings in config_scanner_global act as master overrides.
ParameterLevelPurpose
enabledPer-scannerEnable/disable β€” disabled scanner emits no signals and no alerts
cooldownPer-scannerMin seconds between fires β€” overrides timeframe default
emailPer-scannerEmail alert on fire (subject to global email_all toggle)
telegramPer-scannerTelegram alert on fire (subject to global telegram_all toggle)
email_allGlobalMaster email switch β€” OFF disables all scanner emails regardless
telegram_allGlobalMaster Telegram switch β€” OFF disables all scanner Telegrams
es_only_modeGlobalRestrict to ES / rapid / test scanners only β€” useful for off-hours
πŸ’°
Section 13
Wealth Model Flow
Every trade close feeds into the wealth accounting cycle. Capital progression against plan is tracked live, with weekly milestone checks and automatic ladder level advancement.
Wealth Accounting Cycle β€” Triggered on Every Trade Close
Trade CLOSEDPnL confirmed
β†’
WealthManagerupdate current_capital
β†’
Milestone CheckT1 / T2 / T3 reached?
β†’
Week Advance?target hit β†’ next week
β†’
TradeDiarylog with greeks
β†’
ws/wealth firesdashboard updates

WM235K β€” Weekly Progression Example

πŸ“ˆ WM235K β€” Compounding Curve Β· Plan vs Actual (52 weeks)
Plan Actual Projected
$500K $250K $100K $50K $35K NOW W1 W4 W8 W13 W17 W27 W40 W52
Start: $35,000 Week 17 (now): $41,280 Plan at W17: $39,800 +$1,480 ahead of plan β†— Year target: $500K+
W1$35,000 β†’ $35,800Trade start Β· base sizeβœ“ Complete
W2$35,800 β†’ $36,900T1 milestone hit Β· size upβœ“ Complete
W3$36,900 β†’ $38,100T2 milestone hit Β· size upβœ“ Complete
W4$38,100 → $39,800Active · T3 pending↗ In Progress
W5$39,800 β†’ $41,600Projectedβ€” Upcoming
W52β†’ $500,000+Annual targetπŸ† Goal
πŸ“²
Section 14
Alert System Flow
Every material event fires through the dual-lane AlertManager. Alerts are dispatched on daemon threads β€” the trading path is never blocked waiting for delivery.
IN-APPBUY FILLED: SPX 5940C @ 4.20 Γ— 2 β€” immediately visible in dashboard Live Feed
WEBSOCKETws/orders fires BUY_FILLED event β†’ React dashboard updates live positions
TELEGRAMπŸ“² BOUGHT SPX 5940C @ 4.20 Β· delta 0.30 Β· T1: 5.17 (+23%) Β· Trade #47
EMAILHTML email dispatched: order_buy template with full greek table Β· commission Β· slippage
TELEGRAMπŸ“² SOLD SPX 5940C @ 5.18 Β· +$196 Β· +23.3% Β· Hold 21m 47s Β· T1 target hit
EMAILHTML email: order_sell template with PnL breakdown Β· hold time Β· close reason Β· wealth ladder level
SCANNER BOTπŸ“‘ SPX_FIB_1HR_CALL fired Β· score 87 Β· SPX @ 5938 Β· separate Telegram channel
πŸ’‘
Dual-Bot Architecture

The Scanner Bot sends scanner fire events to a separate Telegram channel β€” keeping your main alert channel clean with only trade-critical events (fills, closes, LP triggers). Each bot has its own token and chat ID, independently configurable.

πŸ”¬
Section 15
Backtest Pipeline Flow
Vectorized backtester against 2 years of 1-minute historical data. Three entry paths: scanner library, custom rule builder, or AI discovery.
Backtest Execution Flow
Select Scannersor rule builder
β†’
Historical Data2Y Β· 1-min bars
β†’
Signal Replayscanner logic on history
β†’
TQS Scoringwin rate Β· PnL Β· drawdown
β†’
Equity Curvetrade-by-trade chart
β†’
8 Gate Checkall green β†’ onboard
πŸ€–
Section 16
AI Discovery Flow
Ollama LLM integration analyses scanner signal combinations and historical performance to discover high-conviction pattern combinations not found by manual analysis.
AI Discovery Pipeline
Backtest ResultsTQS scores
β†’
Ollama LLMpattern analysis
β†’
AI Candidatesranked combinations
β†’
Load β†’ Testone-click backtest
β†’
8 Gate Checkvalidate gates
β†’
Onboard Paperwrite to config DB
πŸ“Š
Section 17
Post-Mortem Analytics
Analytics service aggregates every session's data into a comprehensive review: scanner performance leaderboard, time-of-day heatmap, win/loss streaks, and instrument breakdown.
πŸ†
Scanner Leaderboard
Every scanner ranked by win rate, total PnL, avg hold time, and trade count. Identifies top performers and underperformers for config tuning.
πŸ•
Hour-of-Day Heatmap
Win rate and PnL by hour of day across all sessions. Reveals time-of-day edges β€” identify best entry windows and periods to avoid.
πŸ“ˆ
Equity Curve Review
Session-by-session equity progression with drawdown overlays. Compare plan vs actual compounding curve against your wealth model milestones.
πŸ”—
Streak Analysis
Win/loss streak detection. Identifies regime shifts β€” when consecutive losses appear, triggers strategy review and potential scanner re-calibration.
🌐
Section 18
Dual Environment Architecture
Paper and Live environments are fully isolated β€” separate wealth DBs, separate IBKR accounts, separate runtime data directories. Never cross-contaminate.
DimensionPaperLive
IBKR Port7497 β€” TWS paper account7496 β€” TWS live account (real money)
Wealth DBruntime/paper/intellect.dbruntime/live/intellect.db
CapitalVirtual β€” no real riskReal money β€” full risk
Config DBShared β€” backend/data/config.db
Lifecycle DBShared β€” backend/runtime/intellect_finlab_next.db
Switch viaConfig Console β†’ Environment Settings (requires restart)
πŸ”
Section 19
Crash Recovery Architecture
The system is designed to recover gracefully from any crash at any point in the trade lifecycle. No human intervention required for most crash scenarios.
πŸ”₯ Crash during BUY order submission
β–Ύ

On restart: StartupReconciliation queries TWS for open orders. If BUY was submitted but not confirmed, reconciler checks fill status. If filled, creates BUY_FILLED event and resumes from there. If not filled, marks trade FAILED and cancels.

πŸ“ˆ Crash while position is open (holding)
β–Ύ

Lifecycle DB has SELL_SUBMITTED state. On restart: trade reloaded into RuntimeStore, LP daemon restarts, V2PositionWatchdog resumes monitoring. All rules re-arm from current position state.

πŸ’° Crash during wealth update
β–Ύ

If trade is CLOSED in lifecycle DB but wealth not yet updated: on startup, PromotionSyncWorker detects unpromoted closed trades and applies wealth updates from the trade diary. Idempotent β€” safe to run multiple times.

πŸ”Œ IBKR TWS disconnection mid-session
β–Ύ

ib_async fires a disconnect event. RuntimeSyncWorker suspends tick processing. LP daemon continues running but in alert-only mode. On reconnect, RuntimeSyncWorker syncs position and order state. Engine resumes automatically.