Full Transparency

Under the hood

No black boxes. Tradewink runs 75+ concurrent AI loops that monitor markets, generate strategies, execute trades, and improve themselves — all in real time. Here is exactly how it works.

System Architecture

From market signal to filled order

Data flows down through AI analysis and risk checks before reaching your broker. Outcomes flow back up to retrain models and sharpen future trades. Every node is a real component running in production.

Input Layer

Discord

24 Cogs, 50+ commands

Web Dashboard

31 routes, real-time WebSocket

REST API

32 endpoints, scoped keys

Core Orchestrator

App

Composition root + 81 core modules

Domain Services

Watchlist, Strategy, Portfolio

Clerk Auth

RS256 JWT, per-user scoping

Autonomous Agent

10 Loop Groups

75+ concurrent, market-hours aware

Strategy + Options + Crypto

Stocks, options, futures, forex

Event Bus

Priority async queue + streams

Data Layer

19 Data Providers

Polygon, Finnhub, ORATS, UW

5 Real-Time Streams

Alpaca, Polygon, Finnhub, OANDA, SEC

PostgreSQL + Redis

Dual DB, 5-layer cache

AI Layer

51 AI Modules

Claude, FinBERT, ML, RL

Multi-Agent Teams

Bull/Bear debate, consensus

Self-Improvement

Retrainer, prompt evolution, RAG

Trading Layer

Risk Manager

PDT, limits, circuit breaker

11 Brokers

Stocks, options, futures, forex, crypto

Per-User Keys

Fernet-encrypted, OAuth2

Concurrent Loops

75+ autonomous loops, running right now

Every loop adapts its speed to market conditions. Full speed during market hours, reduced cadence after hours, minimal overnight.

AutonomousAgent initialized — 75+ concurrent loops active
Market Intelligence: Earnings / Insider / SEC / News / Congress
Real-Time Monitoring: Momentum / Macro / Options / Dark Pool
Strategy Engine: Scan / Update / Exit / Sell Confidence
Trade Execution: Screen / Evaluate / Size / AI Score / Execute
Self-Improvement: ML Retrainer / Calibration / Prompt Evolution
Portfolio Health: Risk / Trim / Anomaly / Daily Planning
Options Loops: Flow / GEX / Dark Pool / Max Pain / Wheel
Crypto Loops: Momentum / BTC Dominance / Fear+Greed (24/7)
+ 30 more concurrent loops running right now...
All loops market-hours aware / adaptive cadence / self-improving

Market Intelligence

Scans earnings calendars, insider buys, SEC filings, dark pool prints, and news events — across every ticker.

Earnings ProximityInsider ActivitySEC FilingsNews EventsCongressional Trades

Real-Time Monitoring

Tracks price movements, volatility regimes, options gamma exposure, and institutional dark pool activity in real time.

Intraday MomentumMacro RegimeOptions FlowGEX AnalysisDark Pool Scanner

Strategy Engine

Generates buy/sell strategies via AI, monitors active positions, manages trailing stops, and rotates between factor exposures.

Strategy ScanStrategy UpdateExit StrategySell ConfidenceFactor Rotation

Trade Execution

The execution pipeline: screens candidates, evaluates with AI, sizes positions via Kelly Criterion, and executes through your broker.

Day Trade ScanDay Trade MonitorPre-Market ScanPosition SizingRisk Management

Self-Improvement

Reviews every trade outcome, retrains ML models, adjusts confidence scores, and A/B tests prompt variations to get smarter over time.

Outcome TrackingML RetrainerCalibrationPrompt EvolutionBehavior Analysis

Portfolio Health

Monitors portfolio balance, flags overweight positions, detects statistical anomalies, and generates daily trading plans.

Concentration RiskTrim AlertsAccount TierAnomaly DetectionDaily Planning

Execution Pipeline

From scan to filled order

The autonomous day trading system runs this 6-step pipeline every scan cycle. Each step has safety gates, AI scoring, and risk checks.

STEP 01

Pre-Scan Gates

  • Consistency checker verifies cross-module state
  • HMM regime detection on SPY proxy
  • Intraday regime overlay (5-min efficiency ratio)
  • Monk mode: skip quiet hours, regime transitions, pre-earnings
  • Micro account auto-detection per user
STEP 02

Screen

  • 50+ default tickers + micro universe + Finviz dynamic sourcing
  • Volume, ATR%, gap, RSI, relative volume scoring
  • S&P 500 heatmap movers merged automatically
  • Watchlist tickers prioritized with +15 point boost
STEP 03

Evaluate

  • StrategyEngine + IntradayStrategyEngine analysis
  • Momentum, mean-reversion, breakout, VWAP, ORB strategies
  • Support/resistance integration (pivot, volume, SMA)
  • Signal discretization (5-tier: Strong Buy to Strong Sell)
STEP 04

AI Score

  • Single Claude call per candidate (default, fast)
  • Conviction 0-100 adjusts composite score
  • Opt-in: full 3-agent team evaluation (deeper analysis)
  • Historical trade lessons fed into scoring context
STEP 05

Size & Execute

  • Risk-based, ATR-based, half-Kelly (most conservative wins)
  • Regime-adjusted sizing + cost-aware modeling
  • Smart executor: VWAP/TWAP slicing for large orders
  • Risk check, confirmation, broker submit, audit log
STEP 06

Monitor & Exit

  • MFE/MAE tracking updated every tick
  • Trailing stop with broker sync (cancel old, submit new)
  • Regime-shift exit: AI debate on trending-to-choppy flip
  • Max hold time exit (90 min configurable)
  • Post-trade reflection via AI (lessons stored in DB)

Pipeline runs in both global broker mode (single scan for all) and per-user broker mode (individual scan/evaluate/execute per user).

Deep Dive

Trade loop internals

Every scan cycle runs 13 stages — from lock acquisition to post-trade reflection. Each stage has its own caching, error handling, and performance envelope.

Loop Entry & Lock

<1s0
  • Acquire distributed lock (TTL = scan_interval + 30s)
  • Per-user iteration if user_ids present, else global mode
  • Interval: config.strategy_scan_interval_secs
  • Adaptive threshold adjusts confidence gate on accuracy history

Input

User IDs, config

Output

Lock acquired, user context

Circuit Breaker

<1s0
  • Check session.consecutive_losses >= max_consecutive_losses
  • Pause trading for the day if threshold hit
  • Configurable threshold (default: 2 consecutive losses)
  • Resets on next trading day or manual override

Input

Session state

Output

Continue / pause decision

Regime Detection

1-3s1 data
  • HMM-based (hmmlearn Baum-Welch or manual EM fallback)
  • SPY daily closes, 1-year lookback, 10s timeout
  • Output: RegimeState {bull, sideways, bear, unknown}
  • Cached per-cycle (shared across users): TTL = max(scan_interval, 300s)
  • Intraday overlay: 5-min SPY efficiency ratio (trending/choppy/neutral)

Input

SPY OHLCV (1Y daily + 1D 5-min)

Output

RegimeState + intraday regime

Monk Mode & Reconcile

1-2s1-2 broker
  • Quiet hours: skip first/last 15 min of market
  • Regime transitions: reduce sizing (not block)
  • Pre-earnings quiet period per ticker (applied later)
  • Position reconciliation: sync with broker reality
  • Handles bracket stop/target fills that happened externally

Input

Time, regime, broker positions

Output

Trade/skip decision, synced positions

Config Snapshot & Tier Detection

<1s1 broker
  • Deep-copy config to ScanContext (prevents user leakage)
  • Auto-detect micro account: equity < $1,000
  • Micro mode adjusts: min_price=$2.50, max_price=$50, 3% risk
  • Per-user pref auto-wiring via config_target fields
  • Excluded tickers & sectors applied from user prefs

Input

Broker account, user prefs

Output

ScanContext (isolated config copy)

Candidate Screening

5-15s50-100 data
  • Universe: 200+ default + 80 micro + Finviz dynamic + watchlist
  • Async concurrent quote + 1Y OHLCV fetch per ticker
  • Scoring: RVOL(25) + ATR%(20) + gap(20) + RSI(15) + liquidity(10) + 52W(15)
  • Filters: open positions, user exclusions, entry backoff, data integrity
  • Watchlist boost: +15 pts, options flow boost: +12 pts
  • Output: ranked ScreenerCandidates (max 10 returned)

Input

Ticker universe, quotes, OHLCV

Output

Ranked candidates with scores

Strategy Evaluation

20-45s10-50 data
  • Max 8 concurrent evaluations (executor pool)
  • Per candidate: 3-month daily OHLCV + TechnicalAnalyzer.compute()
  • 5+ strategies: momentum, mean-reversion, breakout, VWAP, ORB, gap-fill
  • Signal discretization: 5-tier (Strong Buy to Strong Sell)
  • Strategy health check: degrade score if Sharpe < 0.25
  • Signal quality classification (ML-based, 1-5 tier)
  • Support/resistance: pivot levels, volume zones, round numbers, SMA

Input

Candidates + OHLCV + indicators

Output

StrategyReport per candidate

Composite Scoring

<1s0
  • composite = (screener_score * 0.4) + (strategy_score * 0.6)
  • Regime multiplier: 0.5x - 1.2x based on market state
  • Strategy health penalty: -0.15 if degraded
  • Intraday confirmation: +5-10 pts if 15-min aligns
  • RL strategy selector weights by historical performance
  • Gate: min_composite_score (40) + min_strategy_score (0.35)

Input

Screener + strategy scores

Output

DayTradeOpportunity list

AI Conviction Scoring

10-30s1 LLM
  • Single Claude call per candidate (batched, cost-optimized)
  • 512 token max output, ~0.1-0.2s per candidate
  • TTLCache: 500 entries, 300s TTL, key=(ticker,direction,strategy)
  • Context gathered in parallel (2s timeout): earnings, VIX, IV rank, news
  • Output: conviction 0-100, top 3 risks, reasoning
  • Conviction < 20 disqualifies; >= 80 strong signal

Input

Trade setup + 6 context sources

Output

Conviction score + risks

3-Agent Team Debate

30-45s3 LLM
  • Opt-in only (config.team_eval_enabled = true)
  • 3 agents: Bull (optimistic), Bear (skeptical), Neutral (arbiter)
  • Strong agreement: +15% score | Disagreement: -15% score
  • 45s timeout per candidate
  • Expensive but deeper analysis for high-score candidates

Input

Opportunity + market context

Output

Consensus + confidence

Position Sizing

2-5s0
  • 3 methods computed, most conservative wins:
  • Risk-based: (equity * risk%) / (entry - stop), max 2% risk
  • ATR-based: (equity * risk%) / (ATR * multiplier)
  • Half-Kelly: kelly_f * 0.5 (optional, uses historical win rate)
  • Caps: 10% position (3% micro), $25k max ($1k micro)
  • Slippage modeling: 5 bps + volume-dependent scaling
  • Cost-aware: must profit 3x total costs to justify trade
  • Correlation-aware: reduce if >0.7 correlated with holdings

Input

Opportunities + account equity

Output

PositionPlan per opportunity

Risk Check & Execution

10-60s3-10 broker
  • Risk gates: daily loss limit, position limits, PDT rule, sector concentration
  • Confidence gate: min 0.7 (adjustable per risk preset)
  • Trade routing: stocks vs options vs crypto (IV rank, account tier)
  • Smart executor: VWAP/TWAP slicing for orders > 1% ADV or > $10k
  • Broker submission: submit_order() with audit log
  • 5 risk presets: ultra-conservative to aggressive

Input

Sized opportunities

Output

ExecutionResult (order ID, fill)

Exit Monitoring Loop

Every 1s1-3 data/s
  • MFE/MAE tracking updated every tick for analytics
  • Trailing stop: ratchet up at 1 ATR (breakeven) and 2 ATR (lock profit)
  • Broker stop sync: cancel old + submit new (race-guarded)
  • 6 exit triggers: target, stop, strategy flip, regime shift, max hold, EOD
  • Regime-shift exit: AI bull/bear debate on trending-to-choppy flip
  • Post-trade reflection: AI generates lessons, stored in DB
  • Exit backoff: 300-3000s cooldown after N consecutive failures

Input

Live quotes, position state

Output

Exit orders, closed trades, lessons

Outcomes feed back into AI conviction scoring + ML retrainer (self-improving loop)