MCPcopy Index your code
hub / github.com/Ashutosh0x/rust-finance

github.com/Ashutosh0x/rust-finance @v0.4.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v0.4.0 ↗ · + Follow
2,990 symbols 6,773 edges 287 files 708 documented · 24%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

RustFinance Terminal (rust-finance)

Rust Tokio Ratatui Anthropic WebSocket

GitHub stars GitHub forks Buy Me a Coffee

Alpaca Binance Finnhub Polymarket

NASDAQ NYSE CME LSE NSE BSE CRYPTO

Windows macOS Linux

OpenSSF Scorecard Security & Supply Chain CI Tests dependency status License: MIT


At a Glance

RustFinance Terminal, also called RustForge, is an open-source Rust trading terminal for market-data ingestion, execution research, quantitative risk controls, compliance checks, and terminal dashboards.

Safety: this project is research and open-source infrastructure. It is not financial advice, not a broker, and not a guarantee of live-trading readiness. Use paper trading and independent review before connecting real capital.


Overview

https://github.com/user-attachments/assets/c769b2c2-cfa0-44bd-a261-99786ea653e1

RustForge is an institutional-grade AI trading terminal built in pure Rust. It combines real-time multi-exchange market data, Claude-powered AI analysis, quantitative risk management, prediction market trading, and a full TUI dashboard — all in a single binary with nanosecond-precision timestamps and sub-millisecond latency.

v0.4 — 2026 Quant Alpha Library: Multi-level Microprice (MLOFI), Adverse Selection Detection, Regime-Conditioned Quoting, Kelly+Bayesian Sizing, Alpha Health Monitor, IC-Weighted Composite Signals, Enhanced Avellaneda-Stoikov Quoting Engine, Almgren-Chriss Optimal Execution, Live Binance WebSocket Candlestick Feed, and WebSocket Gap Detection Engine. 82+ unit tests passing on Rust 1.95.0.

Feature Detail
Language Pure Rust
Interface Full TUI Dashboard (Ratatui, 6 screens)
AI Integration Claude-powered Dexter Analyst
Execution Algorithms TWAP, VWAP, Iceberg, POV, Almgren-Chriss Optimal Execution
Market Making Enhanced Avellaneda-Stoikov with regime gating, VPIN toxicity, OFI skew
Microstructure Multi-level MLOFI, OFI, Microprice, Kyle's Lambda, VPIN, Amihud, Lee-Ready
Smart Order Router Multi-venue scoring (fill rate, latency, fees, impact)
Alpha Signals Toxicity detection, regime classifier, IC-weighted composite, alpha health
Position Sizing Quarter-Kelly with Bayesian shrinkage, conviction scaling
Live Data Binance WebSocket candlestick feed with gap detection engine
Prediction Markets Polymarket CLOB + cross-platform arbitrage engine
Agent Simulation 100K-agent Rayon-parallel swarm
Knowledge Graph petgraph-backed RAG engine
Risk Models GARCH(1,1) + VaR + Kill Switch + SMP + Regime Detection + Toxicity Gating
Timestamp Precision Nanosecond (UnixNanos)
Deterministic Replay DeterministicClock + SequenceId ordering
Regulatory Compliance SEBI 2026 Algo-ID + OPS threshold + pre-trade checks
Fill Simulation Almgren-Chriss √-impact model + fixed slippage
Alpha Monitoring Rolling IC, Sharpe, hit rate with auto-decay detection
FIX Protocol Production FIX 4.4 parser with checksum validation
Market Sources Alpaca, Binance, Finnhub, Polymarket, Mock
Execution Alpaca REST, Polymarket CLOB, Paper Trading
License MIT

Rust Trading Terminal


Table of Contents


Architecture

34 modular crates, 250+ source files, strict dependency boundaries.

graph TD;
    subgraph "External Feeds"
        ALP(Alpaca WS) --> Ingest
        BIN(Binance WS) --> Ingest
        FH(Finnhub WS) --> Ingest
        PM(Polymarket WS) --> Ingest
        LLM(Anthropic Claude) <--> AI
    end

    subgraph "RustForge Engine"
        Ingest(Ingestion / Source Multiplexer) --> Bus(TCP Event Bus)
        Bus --> AI(AI Engine — Dexter / Mirofish)
        Bus --> Quant(Quant Features)
        Quant --> Swarm(Swarm Simulator — 100K Agents)
        Swarm --> KG(Knowledge Graph — petgraph RAG)
        KG --> AI

        AI --> Strategy(Strategy Dispatcher)
        Strategy --> Risk(Risk Gate — GARCH / VaR / Kill Switch)
        Risk --> Exec(Execution Gateway)

        Exec -.-> |Paper Mode| Mock(MockExecutor)
        Exec --> |Live Mode| AlpacaAPI(Alpaca REST)
        Exec --> |Prediction| PolyCLOB(Polymarket CLOB)
    end

    subgraph "Quantitative Models"
        Pricing(Pricing Engine) --> BSM(Black-Scholes-Merton)
        Pricing --> HESTON(Heston Stochastic Vol)
        Risk --> GARCH(GARCH 1,1 Volatility)
        Backtest(Backtest Engine) --> WF(Walk-Forward)
        Backtest --> MC(Monte Carlo)
    end

    subgraph "Persistence"
        Bus --> PG[(PostgreSQL)]
        Bus --> Redis[(Redis Hot-State)]
    end

    subgraph "Frontends"
        Bus --> TUI(Ratatui TUI Dashboard)
        Bus --> Web(REST API / Web Dashboard)
    end

Crate Map

common           Nanosecond timestamps, events, config, models
ingestion        Multi-source market data (Alpaca, Binance, Finnhub, Polymarket) + gap detector
execution        ExecutionGateway + TWAP/VWAP/Iceberg/POV + Almgren-Chriss optimal execution
strategy         Momentum, MeanReversion, Avellaneda-Stoikov (Welford O(1) variance)
risk             Kill switch, GARCH vol, VaR, risk interceptor chain, self-match prevention
pricing          Black-Scholes-Merton, Heston, GARCH(1,1) models
backtest         Walk-forward, Monte Carlo, backtesting engine, √-impact fill model
ai               Dexter AI analyst, Claude integration, signal routing
swarm_sim        100,000-agent market microstructure simulator
knowledge_graph  petgraph-backed RAG knowledge engine
polymarket       CLOB + EIP-712 signing + sum-to-one/cross-platform arb engine
daemon           Hybrid intelligence pipeline, engine orchestration
event_bus        Postcard-serialized TCP event bus (daemon <-> TUI)
tui              Ratatui TUI + live Binance candlestick feed + 500 msg/frame cap
oms              Order Management System (netting + hedging + SEBI 2026 Algo-ID)
alerts           Rule-based alert engine
signals          2026 Quant Alpha Library (see below) + indicators + microstructure
compliance       Pre-trade compliance, audit trail
persistence      PostgreSQL + SQLite persistence layer
metrics          Prometheus-compatible telemetry
ml               Machine learning model inference, alpha decay monitoring
model            Model registry and versioning
feature          Feature engineering pipeline
fix              FIX 4.4 protocol engine — production parser + session layer
cli              Command-line interface
web              REST API server
web-dashboard    Web-based dashboard
dashboard        Dashboard data models
tests            Integration test suite
benchmarks       Criterion performance benchmarks

Signals Crate — 2026 Quant Alpha Library

Based on 18 research papers (2025–2026). 55 unit tests.

Indicators       SMA, EMA, RSI, MACD, Bollinger Bands, VWAP
Microstructure   OFI (Cont 2014), Microprice, Kyle's Lambda, VPIN (Easley 2012),
                 Amihud Illiquidity, Lee-Ready Trade Classifier
Microprice ML    Multi-level microprice MLOFI (Oxford 2019, arXiv 2602.00776)
Adverse Select.  Toxicity detection + halt/widen (Barzykin 2025, Crypto 2026)
Regime           Fast/slow EMA vol ratio → LowVol/Normal/HighVol/Crisis (RegimeFolio 2025)
Kelly            Quarter-Kelly + Bayesian shrinkage sizing (PolySwarm Apr 2026)
Alpha Health     IC decay + hit rate monitor → Healthy/Degraded/Decayed (AlphaForgeBench 2026)
Composite        IC-weighted signal combiner with regime + toxicity gating (Chain-of-Alpha 2025)
Quoting Engine   Enhanced Avellaneda-Stoikov: regime γ, VPIN widening, OFI skew, Kelly sizing

Execution Crate — Almgren-Chriss Optimal Execution

Almgren-Chriss   Optimal trajectory: xⱼ = X × sinh(κ(N-j)) / sinh(κN)
                 Urgency parameter κ = √(λσ²/η), square-root impact model
                 Presets: liquid_default, aggressive, passive
                 7 unit tests (TWAP convergence, front-loading, quantity conservation)

Quick Start

# 1. Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 2. Clone
git clone https://github.com/Ashutosh0x/rust-finance.git
cd rust-finance

# 3. Configure
cp .env.example .env
# Edit .env — add your API keys (see Configuration below)

# 4. Build
cargo build --release

# 5. Run (mock mode — no API keys required)
USE_MOCK=1 cargo run -p daemon --release

# 6. Run TUI (separate terminal)
cargo run -p tui --release

Features

Core Engine

  • Hybrid Intelligence Pipeline — Quant, Swarm, Knowledge Graph, Dexter AI, Risk Gate, Execution
  • Nanosecond-precision timestamps (UnixNanos) with monotonic SequenceId ordering
  • Swappable clock — RealtimeClock for live trading, DeterministicClock for backtesting
  • Event-driven architecture with typed Envelope<T> wrapping every system event
  • Deterministic Safety Gate — zero-AI verification layer preventing agent confirmation bias
  • 34-crate workspace compiling in ~17s

Market Data

  • Alpaca — Real-time US equities via WebSocket (5 feeds: IEX, SIP, BOATS, Delayed, Overnight)
  • Binance

Extension points exported contracts — how you extend this code

Identity (Interface)
Trait for getting the identity element of a point type. [13 implementers]
crates/curve25519-dalek-patch/src/traits.rs
RiskInterceptor (Interface)
(no doc) [8 implementers]
crates/risk/src/interceptor.rs
MarketDataSource (Interface)
(no doc) [5 implementers]
crates/ingestion/src/source.rs
PluggableStrategy (Interface)
v2 strategy trait — processes typed MarketEvent envelopes [2 implementers]
crates/strategy/src/lib.rs
FillModel (Interface)
Trait for pluggable fill models. Implementations determine how orders are filled in backtesting — the fill price account [2 …
crates/backtest/src/fill_model.rs
Clock (Interface)
Swappable clock: real-time for live trading, manual for backtesting. This is the key pattern from NautilusTrader that en [2 …
crates/common/src/time.rs
FusedContextLike (Interface)
Using a generic bound for context to avoid circular dependency with daemon [1 implementers]
crates/ai/src/dexter.rs
ExecutionGateway (Interface)
(no doc) [3 implementers]
crates/execution/src/gateway.rs

Core symbols most depended-on inside this repo

m
called by 466
crates/curve25519-dalek-patch/src/backend/serial/u32/scalar.rs
iter
called by 432
crates/common/src/exchange.rs
len
called by 296
crates/risk/src/wal.rs
send
called by 158
crates/ai/src/compaction.rs
get
called by 150
crates/execution/src/bracket.rs
get
called by 112
crates/ingestion/src/finnhub_rest.rs
m
called by 96
crates/curve25519-dalek-patch/src/backend/serial/u64/scalar.rs
is_empty
called by 87
crates/risk/src/wal.rs

Shape

Method 1,359
Function 934
Class 556
Enum 120
Interface 21

Languages

Rust100%

Modules by API surface

crates/curve25519-dalek-patch/src/edwards.rs87 symbols
crates/curve25519-dalek-patch/src/scalar.rs76 symbols
crates/curve25519-dalek-patch/src/ristretto.rs61 symbols
crates/tui/src/app.rs50 symbols
crates/ingestion/src/alpaca/rest.rs50 symbols
crates/common/src/events.rs46 symbols
crates/polymarket/src/gamma.rs44 symbols
crates/ingestion/src/finnhub_rest.rs40 symbols
crates/risk/src/auto_flatten.rs39 symbols
crates/common/src/time.rs38 symbols
crates/risk/src/garch.rs35 symbols
crates/polymarket/src/clob.rs35 symbols

For agents

$ claude mcp add rust-finance \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page