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 system, every layer, every number.

🧠
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

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)
🧠
Claude Final Gate Validator
1 Claude call per scan · portfolio-aware · fail-open

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.

claude-sonnet-4Portfolio-awareAPPROVE / REJECT / REDUCE_SIZEFail-open25s timeoutStructured verdicts
1
API call per scan
25s
Timeout (fail-open)
3
Verdict types
📡
Signal Enrichment Engine — 8 Parallel Layers · 35 Dimensions
Pre-triage enrichment · 8 passes · zero cloud API calls · added 2026-03-09

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.

Sweep aligned = guaranteed passSqueeze FIRING = must-passStructure break = reversal flagOpposing sweep = hard rejectZero extra API calls
8
Parallel passes
35
Dimensions/symbol
92
Symbols enriched
~3s
Typical latency
0
Cloud API calls
🌐
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 — Kelly + ATR + Dynamic Risk Manager + Symbol Protection
Kelly sizing · ATR stops · Dynamic risk · Symbol protection

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.

Kelly CriterionATR 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