AB Trade-X Source Interaction Detail
Detailed static map of active Python modules, archived TypeScript files, broker adapters, state files, endpoint controls, and the exact handoffs that matter when debugging or extending the bot.
Active Runtime Source Map
Current production code is Python/FastAPIProcess + FastAPI
src/main.pyLoads env overlays, creates FastAPI app, startup lifespan, status/admin endpoints, flatten controls.entrypoint
Payload Schema
src/webhook/parser.pyPydantic model validates action, symbol, strategy, secret, price, tp/sl, script attribution.schema
Router + Dispatcher
src/webhook/router.pyFast gates, lane gates, strategy lookup, account loading, risk checks, broker fanout.core brain
Strategy Registry
src/strategies/__init__.pyMaps strategy strings from alerts to concrete StrategyGuard instances.REGISTRY
Guard Base
src/strategies/base.pySession window check, diagnostic fire count persistence, fire refund support.session
Risk Layer
src/risk/*.pyContract sizing, daily cap, crypto loss gates, Lucid rules, Tradovate runner manager.risk
Tradovate Adapter
src/brokers/tradovate/*.pyToken auth, REST order placement, OSO verification, active trade tracking.REST OSO
Rithmic Adapter
src/brokers/rithmic/*.pyWebSocket sessions, protobuf codec, quote guard, three-order bracket, state tracker.WebSocket
Kraken/Breakout
src/brokers/kraken/*.pyREST auth, UI executor, crypto symbols, position state, OCA/UI close monitors.UI + REST
Trade Logging
src/logging/trade_logger.pyAppends JSONL entries with strategy, account, broker/platform/lane attribution.audit
Specs
src/brokers/futures_specs.py
src/brokers/crypto_specs.pyInstrument tick sizes, tick values, precision, min order sizes, validation.math truth
Reports + Scripts
scripts/build_*report*.pyConsume trade logs and journal data for daily/weekly operational reporting.reports
Live Webhook Sequence
What actually happens after TradingView postsHTTP request enters POST [live webhook endpoint redacted]Router reads raw body, repairs a known malformed source_symbol pattern, JSON-decodes, and builds WebhookPayload.
Fast HTTP gates run before acceptingInvalid JSON, invalid schema, bad secret, unknown strategy, wrong script/source/symbol can reject with HTTP error instead of placing work in the background.
TradingView gets quick accepted responseLong-running broker work moves to _dispatch_webhook() so TradingView does not wait on every account order.
Background dispatch checks operational gatesWebhook pause, disabled scripts/strategies, strategy-symbol mismatch, source_symbol, script_id, symbol allowlist, lane, and exit profile gates.
Symbols normalizeFutures map continuous symbols like MES1! -> MESM6 and MNQ1! -> MNQM6. Crypto maps BTCUSD/XBTUSD into Kraken symbols like PF_XBTUSD.
StrategyGuard approves or blocksGuard enforces session window and persists diagnostic fire count in data/fire_counts.json.
Accounts are loaded and filteredconfig/accounts.json is hot-reloaded, lane scope applies, runtime disabled accounts are removed, allowed_symbols filters by resolved symbol.
Risk and quantity are calculatedFutures use account caps, settings caps, and guard overrides. Kraken uses dollar risk, TP/SL distances, notional caps, and quantity precision.
Orders fan out by broker branchTradovate and Rithmic orders gather concurrently. Kraken reserves a single slot and dispatches async background UI/REST execution.
State and logs updateSuccessful and blocked results append to data/trades.jsonl. Broker state trackers preserve active/pending positions for status, flatten, and monitors.
Broker Internals
The three execution models are intentionally differentTradovate / Lucid + Abe
src/brokers/tradovate/orders.pyREST
- auth.py owns access token cache and refresh.
- place_bracket_order() validates specs, maps action, fetches live quote when needed.
- Market entry, TP, and SL are submitted as one Tradovate OSO bracket.
- Protective child verification checks stop status and can flatten if the stop is rejected.
- position_tracker.py stores active OSO IDs for runner and flatten.
- risk/runner_manager.py polls and manages supported Tradovate positions.
Rithmic / Bulenox
src/brokers/rithmic/orders.pyprotobuf
- websocket.py owns lazy sessions, heartbeat, market-data quote sessions, and reader loop.
- proto.py encodes/decodes R | Protocol fields without protoc.
- Pre-entry quote guard rejects missing, stale, or too-far quotes before sending a market order.
- Bracket is entry market, then stop SL, then limit TP as separate order messages.
- Reader loop resolves gateway ACK 313 and observes exchange/fill notifications 351/352.
- position_tracker.py persists pending/active state to data/rithmic_state.json.
Kraken / Breakout
src/brokers/kraken/orders.pyUI executor
- auth.py signs REST requests with HMAC headers.
- symbols.py normalizes TV symbols into Kraken perp symbols.
- Router sizes qty from max risk, TP/SL distance, min profit, and exposure caps.
- If UI executor is enabled, ui_executor.py drives Breakout via Chrome CDP.
- REST path places market entry, optional stop, TP, then OCA watcher polls open positions.
- position_tracker.py persists state to data/kraken_state.json.
State Ownership
Which files carry operational memory| Path | Owner | Meaning |
|---|---|---|
| config/accounts.json | router account loader | Sensitive account config. Hot-reloaded. Do not use as the primary live enable/disable mechanism. |
| data/runtime_disabled*.json | runtime account endpoints | Persistent account-disable gate that overrides account config. |
| data/trades.jsonl | trade_logger | Append-only trade/block/outcome audit stream used by reporting. |
| data/fire_counts.json | StrategyGuard | ET-date diagnostic fire counts. Counts are currently not the global execution block. |
| data/rithmic_state.json | Rithmic position tracker | Pending/active Buler state restored at startup for combined/buler lanes. |
| data/kraken_state.json | Kraken position tracker | Active Breakout state restored at startup for combined/breakout lanes. |
Archived TypeScript Flow
What the TS files did before the Python rewritearchive/src/index.tsLoads dotenv, calls Tradovate initAuth, starts Express server on PORT.
archive/src/webhook/server.tsExpress JSON webhook, token check, action/symbol validation, chooses market vs OSO order.
archive/src/tradovate/auth.tsSingle Tradovate token cache and accessTokenRequest.
archive/src/tradovate/orders.tsMaps buy/sell, builds market or OSO order request, posts to Tradovate.
archive/src/tradovate/types.tsTypeScript interfaces for payloads and order request bodies.
archive/src/logger.tsWinston console logger.
| Legacy TS | Current Python Equivalent | Major Upgrade |
|---|---|---|
| Express app in server.ts | FastAPI app in src/main.py plus router in src/webhook/router.py | More endpoints, async background dispatch, operational controls. |
| Simple token field body.token | Pydantic WebhookPayload.secret aliases webhookSecret/secret | Schema validation, strategy allowlist, source/script gates. |
| One Tradovate account from env | Hot-loaded multi-account config with Tradovate, Rithmic, Kraken account classes | Multi-broker concurrent routing and runtime disables. |
| Tradovate market or OSO only | Tradovate OSO, Rithmic three-order bracket, Kraken REST/UI bracket | Broker-specific execution safety and monitors. |
| Console logging only | data/trades.jsonl, state files, reports, status endpoints | Durable audit trail and recovery surface. |