AI-powered, risk-aware trade execution.
Built for the Nebius x NVIDIA Global AI Hackathon.
SmartFlow is a research prototype that combines market microstructure signals, adverse-selection prediction, directional forecasting, and AlmgrenβChriss scheduling. Its execution engine adapts between passive, aggressive, and wait actions, while a React + Plotly dashboard makes the decisions and simulated results visible.
Watch the demo Β· Quick start Β· Dashboard gallery Β· Forecasting Β· Data contracts
- Configure simulated market scenarios, order direction, quantity, and execution horizon.
- Inspect the order book, market features, remaining inventory, and decision timeline.
- View adverse-selection risk separately from directional forecasts, with explicit model status and fallback handling.
- Compare the AC plan with execution output and benchmark six strategies on a shared market replay.
Demo environment: simulated market data with local GRU inference. The codebase includes a configurable Nebius inference client/server path; the linked recording demonstrates the local workflow. The saved GRU did not outperform the zero-return baseline on MAE/MSE in the recorded evaluation. See forecasting methodology and limitations for details.
You need Python and pip, plus Node.js and npm for the React dashboard. The project documents Python 3.10+ and was tested on Python 3.13. Install the pinned Python dependencies to match the bundled model artifacts.
git clone https://github.com/alwaysalearner1234/SmartFlow.git
cd SmartFlow
python -m pip install -r requirements.txtStart the API from the repository root:
python -m uvicorn api.main:app --host 127.0.0.1 --port 8000In a second terminal, start React:
cd frontend
npm ci
npm run devOpen http://localhost:5173/, select a scenario, and click Run simulation + backtest. API documentation is available at http://127.0.0.1:8000/docs. See the frontend README for the response contract and the usage section for training, experiments, and the Streamlit reference dashboard.
These are actual screenshots of the React dashboard using a simulated replay. Click an image to inspect it at full resolution.
The React dashboard is in frontend/, served by api/. A separate Streamlit reference dashboard lives in dashboard/.
Executing large institutional orders in electronic limit order books (LOBs) entails a fundamental trade-off:
- Aggressive Execution (Taker): Immediately crosses the bid-ask spread to guarantee completion, but incurs substantial spread cost and adverse temporary/permanent market impact.
- Passive Execution (Maker): Posts resting limit orders at or inside the quote to earn the spread and avoid impact, but suffers from adverse selection (the "winner's curse")βresting orders are filled disproportionately when informed traders sweep the book right before an adverse price plunge.
Smart Order Routing (SOR) and risk-aware execution must dynamically sense toxic flow, estimate instantaneous execution costs, and adapt slicing and order placement in real time.
In fragmented and fast-moving modern markets:
- Static algorithms (e.g., fixed TWAP) blindly execute on arbitrary clocks regardless of whether a volatility spike or toxic flow is occurring.
- Naive liquidity-seeking strategies get picked off by predatory algorithms.
- SmartFlow bridges microstructure predictive signals (Order Flow Imbalance, micro-price divergence, spread expansion) with mathematical liquidation models (Almgren-Chriss) to minimize Implementation Shortfall.
Market Data (L2/L3 Order Book & Trades)
β
βΌ
Data Cleaning & Validation (data/validator.py)
β
βΌ
Order Book Representation (data/contracts.py)
β
βΌ
Feature Engineering Pipeline (features/)
βββ Order Book Depth & Micro-Price (features/order_book.py)
βββ Order Flow Imbalance / OFI (features/imbalance.py)
βββ Bid-Ask Spread Dynamics (features/spread.py)
βββ Price Momentum & Velocity (features/momentum.py)
βββ Realized Volatility Regimes (features/volatility.py)
βββ Trade Flow & CVD (features/trade_flow.py)
β
βΌ
ML Adverse Selection Risk Model (models/)
βββ Preprocessing & Zero-Leakage Splits (models/preprocessing.py)
βββ Training (Logistic Regression Baseline vs. XGBoost) (models/train.py)
βββ Predictor Interface with Heuristic Fallback (models/predictor.py)
β
βΌ
Dynamic Strategy Engine (execution/strategy_engine.py)
βββ Risk Probability (ML Predictor)
βββ AlmgrenβChriss Cost/Variance Model (execution/almgren_chriss.py)
βββ Current Market State (Spread, OFI, Depth, Volatility)
βββ Execution Urgency & Time Progress
βββ Remaining Order Quantity
β
βΌ
Strategy Selection & Execution (strategies/ & execution/)
βββ Market (strategies/market.py)
βββ TWAP (strategies/twap.py)
βββ VWAP (strategies/vwap.py)
βββ Passive Maker with Adverse Backoff (execution/passive.py)
βββ Aggressive Spread Crossing (execution/aggressive.py)
βββ Almgren-Chriss Trajectory (strategies/almgren_chriss_strat.py)
βββ Proposed Risk-Aware SOR (strategies/proposed.py)
β
βΌ
Market & Fill Simulator (simulator/)
βββ Chronological Market Replay (simulator/market_simulator.py)
βββ Order Management & Lifecycle State Machine (execution/order_manager.py)
βββ Fill Physics: Queue Decay & Adverse Bias (simulator/fill_model.py)
βββ Order Book Depletion & Price Impact (simulator/order_book_simulator.py)
β
βΌ
Backtesting & Performance Analytics (backtest/)
βββ Implementation Shortfall & Cost Metrics (backtest/metrics.py)
βββ Multi-Strategy Fair Replay (backtest/backtester.py)
βββ 10-Scenario Stress Testing (backtest/comparison.py)
β
βΌ
Dashboard API (api/)
βββ React + Plotly dashboard (frontend/)
βββ Streamlit reference dashboard (dashboard/app.py)
All features are deterministic and calculated without lookahead bias:
-
Order Book Depth & Micro-Price: Level 1 to 5 depth, size-weighted Stoikov micro-price:
$$P_{micro} = \frac{P_{bid} Q_{ask} + P_{ask} Q_{bid}}{Q_{bid} + Q_{ask}}$$ -
Order Flow Imbalance (OFI): Cont-Kukanov-Stoikov formula tracking net changes in bid/ask price and depth:
$$OFI = \Delta W_{bid} - \Delta W_{ask}$$ -
Spread Metrics: Absolute spread (
$P_{ask} - P_{bid}$ ), relative spread, spread in basis points (bps), and rolling spread expansion ratio. - Price Momentum: Log-returns over 5, 10, 20, 50 ticks, price velocity, and acceleration.
- Realized Volatility: Rolling return standard deviation over 10, 30, 60 ticks and volatility regime ratios.
- Trade Flow & CVD: Buyer- vs. seller-initiated volume, volume imbalance, and Cumulative Volume Delta (CVD).
Feature definitions, units, rolling-window behavior, missing-value conventions, and the canonical forecasting feature order are documented in docs/FEATURE_REFERENCE.md. Shared schemas and cross-module invariants are documented in docs/DATA_CONTRACTS.md.
-
Prediction Horizon (
$H$ ): Configurable (default: 10 ticks). -
Target Label (
$Y=1$ ):-
For BUY Orders: Adverse event occurs if future mid-price drops significantly below current mid-price:
$$P_{t+H} \le P_t - \theta \cdot \text{Spread}_t$$ -
For SELL Orders: Adverse event occurs if future mid-price rises significantly above current mid-price:
$$P_{t+H} \ge P_t + \theta \cdot \text{Spread}_t$$
-
For BUY Orders: Adverse event occurs if future mid-price drops significantly below current mid-price:
- Leakage Prevention: Strictly chronological time-series splits (Train: 70%, Validation: 15%, Test: 15%). Scalers are fit strictly on training data.
-
Models Evaluated:
- Regularized Logistic Regression Baseline
- XGBoost Classifier with probability calibration
-
Standard Interface:
predict(features) -> PredictionResultreturning probability, timestamp, horizon, model name, and status (TRAINEDorFALLBACK_HEURISTIC).
Implements the classical Almgren-Chriss (2000) optimal execution framework:
-
Parameters: Total quantity
$X$ , execution horizon$T$ , slices$N$ , risk aversion$\lambda$ , temporary impact$\eta$ , permanent impact$\gamma$ , volatility$\sigma$ . -
Trajectory:
$$x_j = \frac{\sinh(\kappa (T - t_j))}{\sinh(\kappa T)} X_0, \quad \text{where } \kappa \approx \sqrt{\frac{\lambda \sigma^2}{\eta}}$$ - Computes:
- Trajectory
$x_j$ and slice quantities$v_j$ - Expected execution cost
$E[x] = \frac{1}{2} \gamma X^2 + \eta \sum \frac{v_j^2}{\tau}$ - Cost variance
$V[x] = \sigma^2 \tau \sum x_j^2$ - Utility cost
$U[x] = E[x] + \lambda V[x]$ - Dynamic trajectory re-slicing as remaining time and inventory progress.
- Trajectory
At every decision interval, the engine synthesizes:
- Market State: Spread, OFI, liquidity, and volatility
-
ML Risk Score: Probability of adverse selection (
$p$ ) - AlmgrenβChriss Guidance: Optimal slice size and theoretical cost
- Execution Urgency: Progress of time elapsed vs. remaining inventory
- Remaining Quantity: Order inventory left to liquidate
SmartFlow separates three signals: adverse-selection toxicity, directional forecast, and AlmgrenβChriss urgency.
-
Near Deadline (
$Urgency \ge 0.75$ ): Aggressive AC-guided slice. Completion always dominates. -
High Adverse Risk (
$p \ge 0.65$ ): Withdraw resting maker exposure. A valid forecast may justify taking liquidity only when waiting is directionally costly; high toxicity never makes a resting order safe. -
Low Adverse Risk (
$p \le 0.35$ ): Post a same-side maker order unless a valid strong forecast says waiting is expensive. - Moderate Risk: Follow the Almgren-Chriss inventory trajectory; a valid forecast may delay or slightly accelerate that slice.
High adverse-selection risk does not automatically mean βcross the spread.β See docs/FORECASTING.md.
Every decision returns an auditable reason string explaining WHY the strategy was chosen.
- Deterministic Market Replay: Ensures all strategies run across the exact same tick sequence.
- Market Orders: Depth-walking model that consumes multi-level order-book liquidity with realistic slippage and price impact.
- Limit Orders: Simulates queue position, priority decay, and adverse selection fill bias (higher probability of fills during toxic runs).
- Endogenous Market Impact: Order book simulator adjusts visible depth and shifts mid-prices post-execution.
- Latency Delay: Enforces realistic network and exchange matching latency (default: 15ms).
Metrics calculated from actual executions (no fabricated values):
- Implementation Shortfall (IS): Dollar and basis points vs. arrival price: $$IS_{bps} = \frac{(\bar{P}{exec} - P{arrival}) \cdot Q_{exec}}{P_{arrival} \cdot Q_{exec}} \times 10^4$$
- Realized Execution Cost: Total slippage and half-spread paid
- Average Execution Price vs. Arrival Price
- Completion Rate & Fill Rate
- Adverse Selection Cost
- Almgren-Chriss Expected vs. Realized Cost
- Normal Market
- High Volatility
- Poor Liquidity / Thin Book
- High Adverse-Selection Risk
- Low Adverse-Selection Risk
- Small Order
- Medium Order
- Large Order
- Short Execution Horizon
- Long Execution Horizon
- Python 3.10+ (tested on 3.13)
pip- Node.js and npm for the React frontend
git clone https://github.com/alwaysalearner1234/SmartFlow.git
cd SmartFlow
python -m pip install -r requirements.txtrequirements.txt pins numpy/pandas/scipy/scikit-learn/xgboost/joblib/torch to the versions used to serialize the saved models and includes PyArrow for the bundled Parquet datasets and Parquet output. The torch pin is the CPU wheel. For NVIDIA GPU training or Nebius serving, install a CUDA build from https://pytorch.org/get-started/locally/ after the CPU requirements.
python main.py --generate-dataGenerates 10 market regime datasets under data/raw/ and data/processed/.
python main.py --trainExtracts features, trains Logistic Regression and XGBoost models chronologically, outputs genuine classification metrics, and saves the best model to models/saved/best_adverse_selection_model.joblib.
python -m models.train_forecasterTrains the GRU on chronological 20Γ14 sequences, keeps the best validation checkpoint, writes honest test metrics, and saves models/saved/directional_forecaster.pt. See docs/FORECASTING.md.
python main.py --runRuns an end-to-end simulated replay showing order-book processing, feature extraction, ML risk scoring, AC scheduling, dynamic strategy shifts, order fills, and execution metrics.
python main.py --backtestRuns Market, TWAP, VWAP, Almgren-Chriss, and Proposed strategies across all 10 experimental scenarios under identical market conditions and prints the comparative summary table.
python -m backtest.experiment_runnerCompares Market, TWAP, VWAP, AlmgrenβChriss, Proposed (ML + AC), and SmartFlow (ML + NVIDIA + AC) across existing market scenarios and writes results/strategy_multiseed_results.csv and results/strategy_summary.csv.
From the repository root:
python -m uvicorn api.main:app --host 127.0.0.1 --port 8000In another terminal:
cd frontend
npm ci
npm run devOpen http://localhost:5173/. The dashboard exposes scenario controls, market features, risk/forecast views, execution history, an AC plan, and a six-strategy comparison.
streamlit run dashboard/app.pyOr via CLI:
python main.py --dashboardBefore a release, validate the checked-in sample datasets and reproducibility with:
python -m pytest -q tests/test_person1_data_readiness.py
python scripts/verify_pipeline.pyExecute the comprehensive pytest suite (SmartFlow tests only; vendored python_packages/ is excluded via pytest.ini):
pytest -qTests cover:
- Microstructure features (micro-price, imbalance, OFI, spread bps, momentum, volatility, trade flow)
- ML model training, preprocessing, zero-leakage splits, predictor interface, and fallback handling
- Almgren-Chriss schedules, order manager lifecycle, passive/aggressive strategies, and dynamic engine
- Market simulator replay, queue position, fill physics, and endogenous price impact
- Multi-strategy backtester and identical-market-condition guarantees.
-
Real-Market Calibration: In production,
$\eta$ (temporary impact) and$\gamma$ (permanent impact) should be calibrated against institutional trade execution data (FIX / ITCH feeds). - Multi-Venue SOR: The current system models single-venue multi-level books; future extensions can route across multi-exchange fragmented liquidity pools.
- Deep Reinforcement Learning: Coupling the dynamic strategy engine with Proximal Policy Optimization (PPO) or Deep Q-Networks (DQN) for continuous control.
Distributed under the MIT License. See LICENSE for details.
The React + Plotly frontend and its data contract live in frontend/. The FastAPI service supplies market features, execution history, risk estimates, directional forecasts, the AC plan, and backtest results. Model status and unavailable metrics are displayed explicitly. See the frontend README for startup commands and request/response details.
| Contributor | Primary area |
|---|---|
| Anay | Market data and feature engineering |
| Ariv | Machine learning and quantitative modeling |
| Lidiya | Execution, simulation, backtesting, and backend integration |
| Tuan | React dashboard, visualization, and frontend integration |



