How HedgeVision works — end to end.

Five complete workflow walkthroughs. Step-by-step. Full transparency into every decision the platform makes on your behalf.

The Complete Signal Lifecycle

From market data to filled order in under 60 seconds.

1APScheduler triggers generate_signals_job (every 5 minutes for crypto, aligned with market open for equities)
2SuperIntelEngine.generate_signals() called per ticker
3MicrostructureAgent runs first — OBI check. Wall detection. If veto, stop.
4Data fetched from TimescaleDB (OHLCV, features) and Redis (whale signal, sentiment, macro)
5PerplexitySentimentService called — cached for 1hr, real-time on cache miss
6All 22 models launched via asyncio.gather() — results arrive concurrently
7WeightedVote ensemble combines (25/45/15/15 tier weights)
8Threshold check: signal > 0.1 AND confidence > 0.1 required to proceed
9PPO meta-controller adjusts final weights based on current regime
10CVaR pre-check before entering LangGraph
11Signal enters GraphOrchestrator — full LangGraph deliberation (research, debate, allocator, red_team, sanity, execution)
12Decision Gateway: Auto / Trader / Senior based on confidence
13If approved: ExecutionService, BrokerRouter, broker adapter, fill
14Observer records outcome, position memory, model scoring, retraining trigger if degraded

Signal Flow — APScheduler → Engine → LangGraph → Broker

Signal Flow Diagram

LangGraph Deliberation

How HedgeVision debates a trade.

1research_agent

Perplexity is chosen for real-time web access. The narrative contains current market conditions, recent news, and relevant context that grounds the debate.

2debate_agent

Three simultaneous LLM calls in parallel — Bull, Bear, and Neutral. dissent_score is computed from the disagreement. 0.0 means unanimous consensus; 1.0 means maximum disagreement across agents.

3deep_research

Triggered when dissent > 0.7. Maximum 3 loops. The ResearchService performs a focused deep dive on the specific hypothesis causing disagreement, then injects findings back into the debate.

4allocator_agent

Kelly Criterion computes optimal position size. Four constraints are applied: correlation check, volatility targeting, sector limits, and ATR-based stops. Any constraint breach rejects the allocation.

5red_team_node

An adversarial LLM (GPT-3.5-turbo chosen for instruction-following, not creativity). Its explicit job is to find every reason NOT to take the trade. kill_reason is a human-readable explanation.

6sanity_guard_node

The 5% price check compares LLM-cited prices against live market data. Hallucination detection catches contradictions with TimescaleDB records. Any failure is an unconditional veto.

7execution_agent

Generates the IC-level deal memo with 10 sections. Includes debate summary, risk metrics, hedge recommendations. Routes through DecisionGateway for approval tier determination.

LangGraph StateGraph — Deliberation Flow

LangGraph Orchestration Graph

Risk Pipeline

How HedgeVision protects capital — 8 stages, any can veto.

0MicrostructureVeto

Runs before LLM deliberation (fast pre-check). Checks order book imbalance and wall detection. A hostile order wall can veto before any expensive model computation.

1CVaRVeto

95th-percentile Conditional Value-at-Risk. Vetoes if the proposed position would breach portfolio risk budget or per-asset limits (5% max).

2Portfolio OptimizerVeto

Kelly Criterion sizing with half-Kelly in production. Four constraints: correlation cap, sector limits, volatility targeting, ATR stops. Each can independently reject.

3ChaosEngineVeto

Monte Carlo simulation with jump-diffusion model. Not just historical stress — generates thousands of synthetic scenarios including fat-tailed jumps and crisis correlation spikes.

4StressTesterVeto

Applies four calibrated historical shocks: 2008 Financial Crisis, 2020 COVID Crash, 1987 Black Monday, 2010 Flash Crash. Position must survive all four.

5TailHedge

Recommends protective instruments using Black-Scholes pricing. Advisory only — does not veto. Outputs are attached to the deal memo for human review.

6RedTeamVeto

A real adversarial LLM call, not a rules lookup. GPT-3.5-turbo is prompted to find every reason the trade should NOT be taken. Can veto with kill_reason.

7SanityGuardVeto

Detects LLM hallucination by comparing cited prices to live data. A > 5% deviation is an unconditional veto. Also checks liquidity and structural consistency.

Risk Chain — 8-Stage Sequential Veto Pipeline

Risk Chain Diagram

All veto decisions are stored in TimescaleDB for audit. The veto_stage and veto_reason fields provide complete traceability of why any trade was blocked.

Data Pipeline

Where the data comes from and how it gets clean.

Ingestion Tiers

Tier 1Crypto Core

Binance WebSocket streaming with 5-minute candle assembly. CCXT handles connection management, rate limiting, and auto-reconnection. Highest priority — crypto markets are 24/7.

Tier 2Equity / Macro

FRED API and yfinance are combined for macro indicators (DGS10, VIX, DXY) and equity OHLCV. Hourly refresh aligned with market hours.

Tier 3Gap Assets

On-demand backfill triggered by DataContinuityModule when gaps are detected. Can backfill up to 5 years of historical data for new tickers.

Quality Gate — 5 Checks

1
Completeness: All expected OHLCV fields present, no nulls in critical columns
2
Temporal Ordering: Timestamps are ascending, no duplicates
3
Price Logic: High >= Low >= 0, Close between High and Low, Volume >= 0
4
Staleness: Age vs expected interval. Crypto: stale > 10min. Equity: stale > 2hr
5
Continuity: Expected candle count vs actual. Logs gap percentage, triggers Tier 3 if needed

TimescaleDB

Hypertable with 7-day chunk intervals. Compression after 7 days. 3-year retention. Continuous aggregates for hourly/daily/weekly rollups. 35,000+ chunks under management.

Redis

1GB LRU cache with allkeys-lru eviction. Key patterns: market:{ticker}:latest (1hr TTL), sentiment:{ticker} (1hr TTL), whale:{ticker} (2hr TTL), regime:current (30min TTL). Pub/sub for cross-module events.

Data Pipeline — Sources → Quality Gate → TimescaleDB → Redis

Data Pipeline Diagram

Execution & Broker Routing

How a trade order is placed, tracked, and confirmed.

Asset Class Routing

Asset ClassBrokerProtocol
EQUITYIBKRib-insync TWS
OPTIONSIBKRib-insync TWS
FUTURESIBKRib-insync TWS
FXIC Markets MT4REST bridge :8005
CRYPTOBinanceCCXT REST
FALLBACKPaperSimulated fills

Order Lifecycle

1
Placement: Signal approved → BrokerRouter determines broker by asset class → order constructed in broker-specific format
2
Submission: Async call to broker adapter. Order ID returned. Status: PENDING recorded to TimescaleDB.
3
Monitoring: IBKR: event-driven callbacks. MT4: polling /order/{id} every 2s. Binance: polling fetch_order() every 3s.
4
Fill: Fill confirmed with price, quantity, timestamp. Orders table updated: FILLED. Position created/updated.
5
Observer: Outcome recorded for ML scoring. Position memory updated. If model underperformance detected, triggers retraining.

NAV Arbitrage Execution

For cross-broker arbitrage (e.g., SPY ETF vs ES futures, or BTC spot vs BTCUSDT perp):

  • Entry: asyncio.gather(leg1, leg2) for simultaneous execution
  • Entry trigger: |Z-score| > 2.0
  • Exit trigger: |Z-score| < 0.3 (mean reversion)

Exchange Mapper

Internal tickers are translated to broker-specific symbols. BTC-USD becomes BTC/USDT on Binance. AAPL becomes AAPL STK SMART on IBKR. EURUSD=X becomes EURUSD on MT4.

Execution Routing — BrokerRouter → Adapters → Fill Confirmation

Execution Routing Diagram