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 system, every layer, every number.
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.
A single Claude API call reviews all finalists from the multi-agent consensus stage together. The prompt includes current open positions, portfolio correlation, market regime, and each candidate's signal data. Claude returns structured verdicts — APPROVE, REJECT, or REDUCE_SIZE with a multiplier (0.25–0.75×) — for each trade simultaneously. This holistic, portfolio-aware review catches risks that per-trade agent scoring misses: duplicate exposure, correlated positions, marginal risk/reward in context. Results logged per signal in scan_log.json and visible as colour-coded badges in the dashboard Signals tab. Fail-open: any timeout or API error approves all candidates so the pipeline never stalls.
Before DeepSeek triage sees a single symbol, every one of the 92 is enriched across 8 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.
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 Kelly Criterion capped at 25% of Kelly to prevent over-concentration. Kelly fraction is calculated from rolling win rate and avg win/loss ratio. 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.