Skip to content
alwaysalearner1234Public

About

Smart order routing & risk-aware trade execution

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

42 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SmartFlow

AI-powered, risk-aware trade execution.

Python React TypeScript FastAPI PyTorch License: MIT

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

SmartFlow market microstructure dashboard showing spread, imbalance, volatility, momentum, and book depth

What you can explore

  • 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.

Quick start

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.txt

Start the API from the repository root:

python -m uvicorn api.main:app --host 127.0.0.1 --port 8000

In a second terminal, start React:

cd frontend
npm ci
npm run dev

Open 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.

Dashboard gallery

These are actual screenshots of the React dashboard using a simulated replay. Click an image to inspect it at full resolution.

Risk and directional forecasting

Adverse-selection history alongside a local GRU directional forecast, model status, and decision explanation

Almgren–Chriss execution plan

Planned remaining inventory, per-slice quantities, and expected execution cost

Six-strategy comparison

Simulated slippage, market impact, implementation shortfall, and fill rates for six strategies

The React dashboard is in frontend/, served by api/. A separate Streamlit reference dashboard lives in dashboard/.


1. Problem Statement

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.


2. Why Smart Order Routing Matters

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.

3. System Architecture

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)

4. Market Microstructure Features

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.


5. Machine Learning Adverse-Selection Model

Horizon & Labeling Logic

  • 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$$
  • Leakage Prevention: Strictly chronological time-series splits (Train: 70%, Validation: 15%, Test: 15%). Scalers are fit strictly on training data.
  • Models Evaluated:
    1. Regularized Logistic Regression Baseline
    2. XGBoost Classifier with probability calibration
  • Standard Interface: predict(features) -> PredictionResult returning probability, timestamp, horizon, model name, and status (TRAINED or FALLBACK_HEURISTIC).

6. Almgren–Chriss Optimal Execution Model

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.

7. Dynamic Strategy Engine

At every decision interval, the engine synthesizes:

  1. Market State: Spread, OFI, liquidity, and volatility
  2. ML Risk Score: Probability of adverse selection ($p$)
  3. Almgren–Chriss Guidance: Optimal slice size and theoretical cost
  4. Execution Urgency: Progress of time elapsed vs. remaining inventory
  5. Remaining Quantity: Order inventory left to liquidate

Conceptual Decision Tree:

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.


8. Simulator & Fill Model

  • 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).

9. Backtesting & Performance Metrics

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

10 Experimental Regimes:

  1. Normal Market
  2. High Volatility
  3. Poor Liquidity / Thin Book
  4. High Adverse-Selection Risk
  5. Low Adverse-Selection Risk
  6. Small Order
  7. Medium Order
  8. Large Order
  9. Short Execution Horizon
  10. Long Execution Horizon

10. Installation & Setup

Prerequisites

  • 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.txt

requirements.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.


11. Usage

1. Generate Synthetic Market Datasets

python main.py --generate-data

Generates 10 market regime datasets under data/raw/ and data/processed/.

2. Train ML Adverse-Selection Models

python main.py --train

Extracts 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.

2b. Train the directional forecast model

python -m models.train_forecaster

Trains 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.

3. Run an Execution Replay Demo

python main.py --run

Runs 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.

4. Run Multi-Strategy Backtesting

python main.py --backtest

Runs 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_runner

Compares 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.

5. Launch the React Dashboard

From the repository root:

python -m uvicorn api.main:app --host 127.0.0.1 --port 8000

In another terminal:

cd frontend
npm ci
npm run dev

Open http://localhost:5173/. The dashboard exposes scenario controls, market features, risk/forecast views, execution history, an AC plan, and a six-strategy comparison.

6. Launch the Streamlit Reference Dashboard

streamlit run dashboard/app.py

Or via CLI:

python main.py --dashboard

12. Testing

Before 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.py

Execute the comprehensive pytest suite (SmartFlow tests only; vendored python_packages/ is excluded via pytest.ini):

pytest -q

Tests 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.

13. Limitations & Future Improvements

  • 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.

14. License

Distributed under the MIT License. See LICENSE for details.


15. React Frontend

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.

Team

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

About

Smart order routing & risk-aware trade execution

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Contributors

Languages