A full breakdown of the Vektor AI trading system — every module, every signal stage, and every design decision that went into it.
For the technically curious — every v2 system, every layer, every number. v2 additions are marked v2.
Primary model: GradientBoostingClassifier (50 estimators, max_depth 3) — intentionally shallow to avoid overfitting on limited trade history. Online learning via SGDClassifier with partial_fit — updates immediately after every trade close without a full refit. Both run in parallel: the batch GB model handles historical pattern recognition while the SGD model adapts in real time. SHAP TreeExplainer surfaces feature importances per prediction. Bayesian uncertainty quantification estimates confidence intervals. Experience replay buffer periodically re-trains on high-value historical trades to prevent recency bias.
Connects directly to Hyperliquid’s WebSocket liquidation stream. Every liquidation event is logged with symbol, side, size, price, and timestamp. A 5-minute rolling window aggregates long vs. short liquidation value. When the total crosses a threshold and the rate of new liquidations drops sharply, a cascade-exhaustion signal fires. Intensity is classified into four tiers.
Three-layer aggregation pipeline. Layer 1: RSS feeds from BBC, CoinDesk, CoinTelegraph, MarketWatch, Al Jazeera (free) — Reuters removed, returns blocked responses. Layer 2: CryptoPanic API with ‘important’ filter (free tier). Layer 3: TheNewsAPI (paid). All headlines pass through a keyword pre-screen, MD5 deduplication (persisted to disk across restarts), and DeepSeek classifier. MacroSentimentState decays to neutral after a configurable TTL with no corroborating signals — ensuring old news can’t bleed into live entries.
Programmatically renders OHLCV candlestick charts using Pillow — including EMA overlays, volume bars, and S/R level annotations. The rendered image is base64-encoded and sent to GPT-4 Vision with a structured prompt requesting: pattern classification, support/resistance identification, risk level assessment (low/medium/high), and a confidence score. The vision score is combined with quantitative agent scores in the consensus calculation. No result caching — a fresh chart is rendered and analysed on every scan where vision is enabled.
Polls Hyperliquid’s meta endpoint for open interest and funding rate across all symbols every 5 minutes. Funding rate is annualised for comparison. A crowded-score is computed from the combination of OI change (24h delta) and funding rate deviation. Funding rate thresholds: ±20% annualised = moderate crowding; ±50% annualised = extreme crowding. Combined crowded-score: beyond ±0.5 = moderate; beyond ±0.8 = extreme crowding action triggered. Extreme crowded-long reduces long entries; extreme crowded-short reduces short entries.
Fetches 15m, 1h, and 4h candles concurrently (asyncio.Semaphore(8)) for every candidate symbol. Bullish signal: Price > EMA20 > EMA50. Bearish: Price < EMA20 < EMA50. 4h is a hard gatekeeper — disagreement kills the trade. Cache TTLs: 15m=4min, 1h=14min, 4h=59min. Warm-cache cycles consume zero API calls, enabling aggressive re-scanning.
v2 change: Claude now writes the strongest argument against each trade before deciding. The default disposition changed from “approve unless reason to reject” to “scrutinise, then decide.” Introduced after live data showed 15 stop-loss trades with 0% win rate passed the original gate unchallenged. Each candidate prompt now includes full enrichment snapshot (MACD, OBV, CVD, Supertrend, Market Structure), indicator conflict flags, current drawdown %, and all agent confidence scores. Claude returns a bear_case field alongside each verdict. Rules: 3+ conflicts = REJECT unless R:R >2.5:1; drawdown >8% = REDUCE_SIZE on marginal setups; >3 same-direction positions = automatic REDUCE_SIZE. Verdicts: APPROVE (full size), REJECT (dropped, bear_case logged), REDUCE_SIZE (0.25–0.75× multiplier). Fail-open on timeout.
Before DeepSeek triage sees a single symbol, every symbol is enriched across 10 independent passes running concurrently (asyncio.Semaphore(8)). All layers are fail-open — any error logs a warning and leaves defaults in place. All candle data reuses shared Binance fetches; OBV, CVD, Supertrend, and Pivot Points add zero extra API calls by importing fetch_candles directly from momentum_indicators.py.
① VWAP Filter — rolling 24h VWAP from 1h candles. Price vs VWAP determines BUY_OK / SELL_OK / CONFLICT. CONFLICT signals are penalised in triage.
② Pre-Market Range (stocks only) — 4:00–9:30 AM ET high/low + first-30-min range. Breakout direction matched to signal. CON = penalise; CONFIRMED = boost.
③ Volume Delta — 20-candle buy/sell pressure split via candle body directionality. BULL_DIV and BEAR_DIV flags are high-value reversal signals. vd_filter: CONFIRMED / CONFLICT / NEUTRAL.
④ Momentum Indicators — MACD (12/26/9) bias + crossover + divergence; Stochastic RSI overbought/oversold; Bollinger Bands (20, 2σ) + Keltner Channels (20 EMA, 1.5×ATR) for TTM Squeeze. COILING = BB inside KC (breakout pending). FIRING = BB expanding out — aligned with MTF direction it is a must-pass. mi_signal: STRONG_LONG/SHORT / CONFIRMED / CONFLICT / NEUTRAL.
⑤ Market Structure — 4h candles, 60-bar lookback, 3-candle pivot confirmation. Sequence labelled HH/HL (uptrend) or LH/LL (downtrend). ms_bias: BULLISH / BEARISH / RANGING / BROKEN. structure_break = True → reversal candidate, not trend follow.
⑥ Liquidity Sweep Detector — 1h candles, 50-bar lookback. SWEEP_LOW fires when price wicks below a confirmed swing low and the candle body closes above it (institutional accumulation). SWEEP_HIGH is the inverse. A sweep aligned with the MTF direction bypasses all other filters and is guaranteed to pass triage. Opposing sweep = hard reject. Absolute session high/low always included as liquidity anchors.
⑦ OBV + CVD — On-Balance Volume (per-candle ±volume, 10-bar slope + 5-bar divergence); Cumulative Volume Delta (body-proportional buy/sell split, 20-candle net delta). vol_confirm: STRONG_BULL / STRONG_BEAR / BULL / BEAR / CONFLICT / NEUTRAL.
⑧ Supertrend + Pivot Points — Supertrend(10, 3.0): ATR-based ratcheting band; BULL_FLIP / BEAR_FLIP on direction change (fresh flip = highest-conviction). Classic Pivot Points from prior 24h: P = (H+L+C)/3; R1/R2/S1/S2 derived. pp_st_signal: BREAKOUT_LONG/SHORT (ST flip + pivot break), STRONG_LONG/SHORT (trend + above/below pivot), BOUNCE_LONG/SHORT.
Built from live win-rate analysis of 32 pre-v2 closed trades. Rather than scanning all 92 symbols every iteration, symbols are tiered by actual performance. Tier A — proven performers (100% WR in live data): AVAX, WIF, SUI, CRV, SNX, APT, NEAR, MAG7, SEMIS, ROBOT, INFOTECH, BNB, LINK, INJ, JTO. Scanned every iteration. Tier B — neutral or mixed results: SOL, XRP, DOGE, OP, ARB, NVDA, TSLA, META, COPPER, PLATINUM, and ~30 others. Scanned every 3rd iteration. Tier C — permanently excluded: BTC (0% WR), ETH (0% WR), AAPL (0% WR), GOLD (0% WR), BRENTOIL (−31.9% avg PnL), AMD, COIN, MSTR, NATGAS, SEI, AAVE. The rationale: our 35-dimension indicator suite produces no measurable edge on these assets. Major coins (BTC, ETH) are too efficient; high-cap stocks move on fundamentals not technicals; specific commodities show only macro sensitivity that our models can’t reliably capture.
The tier filter applies after the market-hours symbol filter, reducing 92 symbols to ~22 per iteration. Config: production_config.py — symbol_tier_a, symbol_tier_b, symbol_tier_c lists. Toggle: use_symbol_tiers = True. Re-evaluation: every 50 closed trades, rolling win rates are computed per symbol and tiers are automatically adjusted.
Data insight: pre-v2 R:R was 0.53× (avg win +.25 vs avg loss −.14). At any win rate below 65%, this guarantees negative expectancy regardless of accuracy. The R:R gate computes TP distance / SL distance from the actual entry price (after stops are finalised), and blocks any entry below 1.5:1. At 1.5:1 with 40% WR: expectancy = exactly 0.00/trade. At 2:1 with 40% WR: expectancy = +/bin/sh.20/trade.
Dynamic TP widening addresses a second data problem: pre-v2 take_profit exits averaged +5.70 (100% WR, 2 trades) while stale exits averaged +.90 (100% WR, 5 trades). TPs were set too tight — winners were being time-exited instead of profit-exited. The fix reads the enrichment_snapshot field on each opportunity to check indicator alignment: if OBV+CVD vol_confirm (STRONG_BULL/BEAR) + Supertrend direction + MACD bias all agree with the trade direction → TP set to 7× ATR. Moderate alignment (2 of 3) → 5× ATR. Default (mixed) → 4× ATR. The same logic applies to static stops proportionally.
Data insight: live pre-v2 trade data showed DeepSeek’s confidence scores are inversely calibrated. 85%+ confidence produced 0% win rate (1 trade). 80–85% produced 0% win rate. 75–80% produced 43% win rate. 70–75% was the only band that worked: 75% win rate (4 trades). Higher confidence = worse outcome. This is a known property of large language models — they are systematically overconfident and their raw logit outputs don’t correspond to real probabilities.
Platt scaling (isotonic / logistic regression) maps raw model confidence scores → actual win probabilities using historical trade outcomes as training labels. Input features: [ai_confidence, strategy_confidence, technical_confidence]. Output: calibrated win probability that reflects actual historical accuracy at each confidence level. The calibrator is applied in multi_agent_coordinator.py just before the consensus threshold check — a raw 0.82 might map to 0.51 (near-random), preventing Kelly from massively oversizing a position. Safe passthrough: below 50 closed v2 trades, calibrate() returns the raw score unchanged. State persisted to calibrator_state.json. Auto-retrains every 25 new trades once active.
Three-layer fix for a crypto-centric worldview that previously blocked crude oil longs during bear regimes. Layer 1 — Strategy agent system prompt: upgraded from "crypto specialist" to "multi-asset perpetuals strategist" with explicit cross-asset macro rules: rising oil → inflation fears → Fed hawkish → rising yields → short growth tech. Layer 2 — Batch strategy prompt: when a scan batch contains non-crypto symbols (CL, BRENTOIL, GOLD, TSLA…), the regime mandate switches to asset-class-scoped — crypto bear for crypto, independent evaluation for commodities and equities. Intermarket macro context block injected per batch. Layer 3 — Post-pipeline filter: STRONG_BEAR long block now calls _is_crypto(symbol) via AssetClassifier — only crypto longs are blocked; energy/stock/forex longs pass through.
When the bot has pipeline-approved opportunities blocked by position limits or correlation caps, it can intelligently close a stale position to make room. Trigger A (max positions full): fires when len(positions) ≥ MAX_POSITIONS. Evaluates all open positions for displacement eligibility: age ≥45 min, PnL in [−1.5%, +2.0%], incoming confidence at least 15 percentage points higher. Closes the weakest candidate. Trigger B (same-side correlation cap): fires when same_side_count ≥ MAX_SAME_DIRECTION. Requires 30 min age, PnL in [−1.5%, +2.5%], 18% confidence edge. Decrements the side count in-memory so the new trade can proceed in the same iteration. Both triggers are wrapped in try/except — any error silently skips displacement without crashing the main loop. Maximum 1 displacement per iteration. Telegram notification on every displacement close.
Position sizing uses a 7-factor Kelly (v2): base Kelly capped at 25% multiplied by independent factors for volatility (ATR%: <1.5% → 1.1×, >5% → 0.6×), regime (STRONG → 1.15×, UNKNOWN → 0.65×), asset category (commodity → 0.70×, stock → 0.80×), OI liquidity (>0M → 1.05×, <M → 0.70×), indicator alignment (all 3 agree → 1.10×, 0/3 → 0.80×), drawdown scalar, and MTF confidence scalar. Combined multiplier floored at 0.20× and capped at 1.20×. ATR (14-period) sets stop distances — stops scale with actual volatility, not fixed percentages. The Dynamic Risk Manager auto-tightens all thresholds when drawdown exceeds 5%: minimum confidence rises, Kelly fraction shrinks, max open positions reduces. Symbol Protection V2 tracks every symbol’s performance history and applies 3-day, 7-day, or 30-day blocks on underperformers — with a probation mode that allows limited re-entry for redemption. The Liquidation Protection Engine monitors real-time distance-to-liquidation, warns at 10%, fires critical alerts at 5%, and calculates exact margin injection needed to reach a safe distance.
Aggregates MTF signals across all tracked assets to classify the current market environment into one of 6 states. Regime drives two downstream effects: a position size multiplier and a confidence boost/penalty applied before the 65% threshold check. STRONG_BULL/BEAR trigger +10% confidence for aligned trades and −20% for counter-trend trades. CHOPPY halves position size (0.5×) and suppresses entries. Regime is also used by the Cross-Asset Macro layer to scope the STRONG_BEAR long block to crypto only — commodity and equity longs are evaluated independently.
STRONG_BULL — ≥55% assets bullish + correlation ≥0.40. Full size, +10% confidence on longs, −20% on shorts.
BULL — 40–55% bullish, moderate correlation. 0.9× size.
NEUTRAL — 45–55% mixed. 0.7× size, no bias.
BEAR / STRONG_BEAR — mirror of Bull/Strong Bull on short side.
CHOPPY — ≥50% neutral assets or correlation <0.20. 0.5× size, no directional bias. Entries suppressed.
Leverage is never fixed — it is computed per trade from three inputs: AI confidence score, 24h volatility, and per-market max leverage fetched live from the exchange. Markets have hard caps that vary significantly (SOL/BTC/ETH up to 101×, WIF capped at 10×). The engine maps confidence + volatility into one of 4 tiers, then scales within that tier’s range. Win rate below 65% applies an additional 0.75× Kelly-style reduction to the recommended leverage.
CONSERVATIVE — confidence <0.65. Leverage 1–3×.
MODERATE — confidence 0.65–0.75. Leverage 3–10×.
AGGRESSIVE — confidence 0.75–0.90. Leverage 10–50×.
MAXIMUM — confidence ≥0.90 + market allows ≥50×. Up to 75% of market max, hard-capped at 100×.
Volatility factors: low vol = 1.0× multiplier; high vol = 0.65×; extreme = 0.5×.
Before any expensive AI agent runs, DeepSeek processes all 92 symbols in a single batch call to prune them down to 8–12 high-probability candidates. The triage prompt is not generic — each symbol receives a system prompt and analysis criteria tailored to its asset class. This prevents crypto volatility heuristics from being applied to crude oil, or gold macro logic from being applied to altcoins. Confidence thresholds are also adjusted per class: stocks require +5% higher confidence (slower-moving, fundamentals matter more); commodities get −5% (stronger, longer trends; fewer false positives).
Crypto triage — technical-primary. Momentum, liquidation levels, funding sentiment. Time sensitivity: high. Threshold: base.
Equity triage — technical + fundamental catalysts. Pre-market range, earnings, float. Time sensitivity: medium. Threshold: +5%.
Commodity triage — macro-primary. Oil supply/OPEC, Fed/yields for gold, geopolitical events. Time sensitivity: low. Threshold: −5%.
Every closed trade is archived in a structured journal and run through the Reflection Agent before the meta-learner receives its update. The agent grades each trade A–F across three dimensions: timing quality, sizing quality, and exit quality. Grade score feeds a lessons summary stored alongside the trade record. Pattern analysis runs across the rolling journal to detect session-specific win rates (Asian / London / NY), regime-specific performance, and strategy effectiveness per asset class. Dynamic StrategyWeights are updated after each analysis cycle and consulted at triage time to bias future entries toward what’s been working.
Sits alongside Symbol Protection V2 to provide a deeper diagnostic layer. Where Symbol Protection blocks/probates based on loss counts, the ML Analyzer asks why a symbol is failing. It analyses loss patterns across regime type, confidence level, and consecutive-loss streaks. Outputs: a primary failure issue, a confidence score, contributing factors, and concrete recommendations (e.g. “require >70% confidence for this symbol”, “avoid during STRONG_BEAR regime”, “tighten stops from 5% to 3%”). If the pattern is severe enough (4+ consecutive losses, chronic underperformance), the analyzer issues an ML veto that blocks the symbol independent of Symbol Protection’s block/probation state. Cross-symbol comparison finds similar assets that are performing well and flags them as study candidates.
Automated reporting system that fires on a configurable schedule. Daily reports (default midnight UTC) summarise the day’s closed trades: total PnL, win rate, best and worst trade, open positions count, and a streak indicator. Weekly reports (default Sunday) roll up 7-day performance with Sharpe ratio, max drawdown for the period, and per-symbol breakdown. All daily stats are dual-written to SQLite (primary) and JSON (fallback) and retained for 90 rolling days. Reports are delivered to a configured Telegram chat — the same channel that receives real-time trade alerts and displacement notifications.