Inspiration Retail traders lose money chasing momentum. When a stock crashes 3% or Bitcoin dumps 5%, panic selling pushes prices past fair value. We wanted to build a system that does the opposite — systematically fades extreme moves across two completely different markets, with AI acting as the final gatekeeper on every trade.
The core idea is simple: if an asset's intraday move exceeds a statistical threshold, the probability of mean-reversion within the session is elevated. We formalize this as:
$$P(\text{reversion} \mid |\Delta p| > \theta) > P(\text{continuation} \mid |\Delta p| > \theta)$$
where $\theta = 2%$ for Indian stocks and $\theta = 4%$ for crypto perpetuals.
What it does AI Hedge Fund is a dual-market algorithmic trading platform that simultaneously trades:
Indian F&O (NSE stock options via Dhan API) Crypto perpetual futures (Bybit API) Both modules use the EOS (Exhaustion of Strength) contrarian strategy:
Stock moves UP > 2% → Buy PUT options (expect drop) Crypto moves DOWN > 4% → Open LONG perpetual (expect bounce) Every trade signal passes through 2-tier AI validation:
Tier 1 — Rule-based (<10ms): Hard filters on risk limits, position caps, duplicate checks Tier 2 — Claude Sonnet 4.5 (~2-4s): Full market context analysis → APPROVE or REJECT with reasoning The system includes backtesting with real historical data, paper trading with live exchange connections, risk management (stop-losses, trailing stops, SMA crossover exits), and a unified Flask dashboard to monitor both markets in real time.
How we built it The entire system is built in Python, with a modular architecture:
Data Layer → Strategy Engine → AI Validator → Risk Manager → Execution → Portfolio DB → Dashboard Key technical decisions:
Bybit API v5 (REST + WebSocket) for crypto market data and order execution Dhan API v2 for Indian F&O data, option chains, and order execution Claude Sonnet 4.5 via OpenRouter for Tier-2 AI validation — the model receives full market context (price action, volume, funding rates, volatility) and returns a structured APPROVE/REJECT decision SQLite with WAL mode for portfolio tracking — shared database with separate table namespaces for each module (eos_* and crypto_*) Black-Scholes pricing for synthetic option backtesting when historical option data isn't available: $$C = S \cdot N(d_1) - K e^{-rT} \cdot N(d_2)$$
where $d_1 = \frac{\ln(S/K) + (r + \sigma^2/2)T}{\sigma\sqrt{T}}$
Exponential backoff retry on all API calls to handle rate limits and transient failures Crash recovery — on startup, the system reconciles local state with actual exchange positions to handle ungraceful shutdowns Thread-safe WebSocket feeds with daemon threads and asyncio event loops for real-time price streaming Challenges we ran into Cross-market strategy design — EOS is a mean-reversion strategy originally designed for stock options. Adapting it to crypto (which is more momentum-driven) required different thresholds ($4%$ vs $2%$), additional confirmation signals (funding rate extremes, volume spikes), and crypto-specific exits (funding flip). SQLite threading — The paper trading runner creates database connections in the main thread but executes trades from a daemon thread. We had to enable check_same_thread=False and ensure WAL mode for safe concurrent access. AI validation latency — Claude Sonnet 4.5 calls take 2-4 seconds, which is an eternity in trading. We solved this with a 2-tier system: Tier 1 rejects obviously bad trades instantly (<10ms), so the expensive AI call only runs on promising signals. Backtesting without historical option data — Indian stock option historical data is expensive and hard to get. We built a synthetic backtester that uses real stock prices from Yahoo Finance and generates option prices using Black-Scholes, giving us realistic P&L estimates without paying for premium data. Fill confirmation — In live trading, a submitted order isn't necessarily filled. We implemented polling-based fill confirmation that checks order status until filled or timeout, then uses the actual average fill price instead of the expected price. What we learned AI as a risk layer, not a signal generator — Using Claude as a trade validator rather than a trade picker is far more practical. It catches edge cases (earnings days, macro events, low liquidity) that rule-based systems miss. Mean-reversion works differently across asset classes — The same core idea (fade extreme moves) needs very different parameterization for stocks vs crypto. Crypto's 24/7 nature and higher volatility demand wider thresholds and additional confirmation signals. Paper trading is not optional — Building a realistic paper sim that mirrors the live system (same sizing, same AI validation, same exits) caught multiple bugs before any real money was at risk. What's next Live deployment with real capital on Bybit (crypto) and Dhan (Indian F&O) Multi-timeframe analysis — adding daily and weekly trend context to improve entry timing Reinforcement learning — training an RL agent to dynamically adjust $\theta$ based on current volatility regime Options Greeks integration — using Delta and Theta decay modeling for smarter option strike selection
Built With
- ai/ml
- amazon-web-services
- calude
- dhan
- python
- supabase
Log in or sign up for Devpost to join the conversation.