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.
Discord
24 Cogs, 50+ commands
Web Dashboard
31 routes, real-time WebSocket
REST API
32 endpoints, scoped keys
App
Composition root + 81 core modules
Domain Services
Watchlist, Strategy, Portfolio
Clerk Auth
RS256 JWT, per-user scoping
10 Loop Groups
75+ concurrent, market-hours aware
Strategy + Options + Crypto
Stocks, options, futures, forex
Event Bus
Priority async queue + streams
19 Data Providers
Polygon, Finnhub, ORATS, UW
5 Real-Time Streams
Alpaca, Polygon, Finnhub, OANDA, SEC
PostgreSQL + Redis
Dual DB, 5-layer cache
51 AI Modules
Claude, FinBERT, ML, RL
Multi-Agent Teams
Bull/Bear debate, consensus
Self-Improvement
Retrainer, prompt evolution, RAG
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 activeMarket Intelligence: Earnings / Insider / SEC / News / CongressReal-Time Monitoring: Momentum / Macro / Options / Dark PoolStrategy Engine: Scan / Update / Exit / Sell ConfidenceTrade Execution: Screen / Evaluate / Size / AI Score / ExecuteSelf-Improvement: ML Retrainer / Calibration / Prompt EvolutionPortfolio Health: Risk / Trim / Anomaly / Daily PlanningOptions Loops: Flow / GEX / Dark Pool / Max Pain / WheelCrypto Loops: Momentum / BTC Dominance / Fear+Greed (24/7)+ 30 more concurrent loops running right now...All loops market-hours aware / adaptive cadence / self-improvingMarket Intelligence
Scans earnings calendars, insider buys, SEC filings, dark pool prints, and news events — across every ticker.
Real-Time Monitoring
Tracks price movements, volatility regimes, options gamma exposure, and institutional dark pool activity in real time.
Strategy Engine
Generates buy/sell strategies via AI, monitors active positions, manages trailing stops, and rotates between factor exposures.
Trade Execution
The execution pipeline: screens candidates, evaluates with AI, sizes positions via Kelly Criterion, and executes through your broker.
Self-Improvement
Reviews every trade outcome, retrains ML models, adjusts confidence scores, and A/B tests prompt variations to get smarter over time.
Portfolio Health
Monitors portfolio balance, flags overweight positions, detects statistical anomalies, and generates daily trading plans.
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.
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
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
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)
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
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
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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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