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/FastAPI
Process + FastAPIsrc/main.pyLoads env overlays, creates FastAPI app, startup lifespan, status/admin endpoints, flatten controls.
entrypoint
Payload Schemasrc/webhook/parser.pyPydantic model validates action, symbol, strategy, secret, price, tp/sl, script attribution.
schema
Router + Dispatchersrc/webhook/router.pyFast gates, lane gates, strategy lookup, account loading, risk checks, broker fanout.
core brain
Strategy Registrysrc/strategies/__init__.pyMaps strategy strings from alerts to concrete StrategyGuard instances.
REGISTRY
Guard Basesrc/strategies/base.pySession window check, diagnostic fire count persistence, fire refund support.
session
Risk Layersrc/risk/*.pyContract sizing, daily cap, crypto loss gates, Lucid rules, Tradovate runner manager.
risk
Tradovate Adaptersrc/brokers/tradovate/*.pyToken auth, REST order placement, OSO verification, active trade tracking.
REST OSO
Rithmic Adaptersrc/brokers/rithmic/*.pyWebSocket sessions, protobuf codec, quote guard, three-order bracket, state tracker.
WebSocket
Kraken/Breakoutsrc/brokers/kraken/*.pyREST auth, UI executor, crypto symbols, position state, OCA/UI close monitors.
UI + REST
Trade Loggingsrc/logging/trade_logger.pyAppends JSONL entries with strategy, account, broker/platform/lane attribution.
audit
Specssrc/brokers/futures_specs.py
src/brokers/crypto_specs.py
Instrument tick sizes, tick values, precision, min order sizes, validation.
math truth
Reports + Scriptsscripts/build_*report*.pyConsume trade logs and journal data for daily/weekly operational reporting.
reports

Live Webhook Sequence

What actually happens after TradingView posts
HTTP 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 different

Tradovate / 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
PathOwnerMeaning
config/accounts.jsonrouter account loaderSensitive account config. Hot-reloaded. Do not use as the primary live enable/disable mechanism.
data/runtime_disabled*.jsonruntime account endpointsPersistent account-disable gate that overrides account config.
data/trades.jsonltrade_loggerAppend-only trade/block/outcome audit stream used by reporting.
data/fire_counts.jsonStrategyGuardET-date diagnostic fire counts. Counts are currently not the global execution block.
data/rithmic_state.jsonRithmic position trackerPending/active Buler state restored at startup for combined/buler lanes.
data/kraken_state.jsonKraken position trackerActive Breakout state restored at startup for combined/breakout lanes.

Archived TypeScript Flow

What the TS files did before the Python rewrite
archive/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 TSCurrent Python EquivalentMajor Upgrade
Express app in server.tsFastAPI app in src/main.py plus router in src/webhook/router.pyMore endpoints, async background dispatch, operational controls.
Simple token field body.tokenPydantic WebhookPayload.secret aliases webhookSecret/secretSchema validation, strategy allowlist, source/script gates.
One Tradovate account from envHot-loaded multi-account config with Tradovate, Rithmic, Kraken account classesMulti-broker concurrent routing and runtime disables.
Tradovate market or OSO onlyTradovate OSO, Rithmic three-order bracket, Kraken REST/UI bracketBroker-specific execution safety and monitors.
Console logging onlydata/trades.jsonl, state files, reports, status endpointsDurable audit trail and recovery surface.