Technical Architecture

Every layer.
Every number.

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.

🧠
Meta-Learner v2.1 — Stacked Ensemble + Online Learning
Adaptive ML · Gradient Boosting + SGD Online Learning + SHAP

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.

GradientBoosting (50 est.)SGD partial_fitSHAPConcept driftExperience replayscikit-learnnumpy
Liquidation Cascade Detector
WebSocket stream · 5-min rolling window

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.

WebSocketRolling windowasyncioHyperliquid API
70%
Historical win rate
5m
Lookback window
4
Intensity tiers
📰
News Sentiment Engine
3-min poll cycle · MD5 dedup · TTL decay · source authority weighting (v2)

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.

DeepSeek classifierMD5 dedupTTL decayfeedparseraiohttp
👁️
GPT-4 Vision Agent
GPT-4 Vision · base64 chart rendering · per-scan call

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.

GPT-4 VisionChart renderingPillowbase64OpenAI API
📈
OI + Funding Rate Monitor
Hyperliquid meta endpoint · 5-min cache

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.

Crowded-score −1 to +1Annualised funding5-min cacheHyperliquid meta API
🕐
Multi-Timeframe Analyzer
15m / 1h / 4h · tiered TTL cache · async concurrency

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.

EMA20/EMA50Tiered TTL cacheHard 4h gateasyncioSemaphore(8)
🧠
Contrarian Claude Gate v2
1 Claude call per scan · bear case mandatory · portfolio-aware · fail-open

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.

Bear case mandatory (v2)Enrichment per candidate (v2)APPROVE / REJECT / REDUCE_SIZEFail-openbear_case logged per signal25s timeout
1
API call per scan
25s
Timeout (fail-open)
3
Verdict types
v2
Bear case added
📡
Signal Enrichment Engine — 10 Parallel Layers · 35 Dimensions
Pre-triage enrichment · 10 passes · zero cloud API calls · updated v2

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.

Sweep aligned = guaranteed passSqueeze FIRING = must-passStructure break = reversal flagOpposing sweep = hard rejectZero extra API calls
10
Parallel passes
35
Dimensions/symbol
92
Symbols enriched
~3s
Typical latency
0
Cloud API calls
🏆
Symbol Tier System v2
Data-driven symbol exclusion · 3 tiers · every 50-trade re-evaluation

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.pysymbol_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.

Live WR data-driven (v2)Tier C = 0% WR in live data92 → ~22 per iterationRe-evaluated every 50 tradesToggle: use_symbol_tiers
3
Tier levels
15
Tier A symbols
19
Tier C excluded
50
Trades per re-eval
⚖️
R:R Gate & Dynamic TP Widening v2
Minimum 1.5:1 required · 7× ATR on strong alignment · data-driven TP targets

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.

R:R ≥ 1.5:1 required (v2)7× ATR on 3-indicator alignmentReads enrichment_snapshotData: pre-v2 R:R was 0.53×TP widening at entry, not mid-trade
1.5:1
Min R:R gate
ATR TP on strong align
ATR TP default
0.53×
Pre-v2 actual R:R
🔬
Platt Scaling Confidence Calibrator v2
Logistic regression calibration · activates at 50 closed v2 trades · auto-retrains every 25 new trades

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.

Pre-v2 data: 85% conf = 0% WR70–75% = only working bandLogistic regression on live outcomesActivates at 50 closed v2 tradesSafe passthrough below thresholdcalibrator_state.json
50
Trades to activate
25
Trades per retrain
3
Input features
0%
WR at 85%+ conf (pre-v2)
🌐
Cross-Asset Macro Intelligence
Strategy · Coordinator · Pipeline · added 2026-03-09

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.

Oil → inflation → Fed → yields chainAsset-class-scoped regimeAssetClassifier gating
92
Markets covered
5
Asset classes
3
Fix layers
0
Non-crypto longs blocked
🔄
Opportunity Displacement Engine
Core pipeline · added 2026-03-09

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.

Max-positions triggerCorrelation-cap triggerConfidence-edge gatingFail-safe wrappedMin age: 30–45 minPnL window: −1.5% to +2.5%Max 1 per iteration
2
Trigger types
15%
Min confidence edge (A)
18%
Min confidence edge (B)
1
Max per iteration
⚙️
Risk Engine — 7-Factor Kelly + ATR + Dynamic Risk + Symbol Protection v2
7-factor Kelly (v2) · ATR stops · Dynamic risk · Symbol protection

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.

7-Factor Kelly (v2)R:R gate 1.5:1 (v2)ATR stopsDynamic risk tighteningSymbol block/probationLiq. protection engineCorrelation guardDaily loss limit 10%Max drawdown 20%
25%
Max Kelly fraction
14
ATR period
10%
Daily loss limit
20%
Max drawdown
🌊
Market Regime Detector
6 regime states · MTF-derived · position size & confidence modifiers

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.

6 regime states+10% / −20% confidence mod0.5× size in chopMTF-derivedCrypto-scoped bear block
6
Regime states
+10%
Trend confidence boost
−20%
Counter-trend penalty
0.5×
Size in CHOPPY
⚖️
Dynamic Leverage Engine
4 confidence tiers · per-market max detection · volatility-adjusted

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×.

4 confidence tiersPer-market max detectionVolatility factor 0.5–1.0×Win-rate Kelly reductionHard cap 100×
4
Leverage tiers
0.65
Min confidence to trade
100×
Hard cap
0.5×
Extreme vol factor
🎯
Asset-Specific Triage (DeepSeek)
3 asset-class prompts · per-class confidence thresholds · time-sensitivity scoring

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%.

3 asset-class prompts92 → 8–12 symbolsPer-class confidence adj.Single DeepSeek batch call~.50 saved per scan
3
Triage prompt types
92→12
Symbol reduction
+5%
Equity threshold adj.
−5%
Commodity threshold adj.
📓
Reflection Agent & Trade Journal
Post-trade analysis · A–F grading · session & regime pattern detection · meta-learner feeder

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.

A–F trade gradingSession win rates (Asian/London/NY)Regime performance trackingDynamic strategy weightsFeeds meta-learnerPersisted journal
5
Grade levels (A–F)
3
Session windows
100%
Trade coverage
🔬
Symbol ML Analyzer
Per-symbol failure analysis · ML veto · recovery plans · cross-symbol comparison

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.

ML veto on chronic failureRegime-specific failure detectionCross-symbol comparisonRecovery plan generationIntegrates with Symbol Protection V2
4+
Losses triggers ML veto
3
Failure dimensions
5
Similar symbols compared
📊
Performance Reporter
Daily & weekly Telegram reports · Sharpe ratio · 90-day rolling history · SQLite-backed

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.

Daily + weekly cadenceSharpe ratio90-day rolling historySQLite + JSON dual-writeTelegram deliveryBest/worst trade highlights
2
Report cadences
90
Days history retained
2
Storage backends
VEKTOR — Technical Architecture
Overview Signal Pipeline Live Demo Pricing