Trading in fast-moving crypto markets demands precision, speed, and realistic cost modeling. The GoQuant Real-Time Trade Simulator is a powerful Python-based tool designed to simulate actual trade execution using live Level 2 order book data from OKX. By integrating advanced quantitative models with real-time WebSocket streams, this project delivers accurate predictions for slippage, fees, market impact, and execution behavior—making it ideal for traders, quants, and algorithmic developers seeking deeper insights into trade efficiency.
Built as part of an internship selection challenge, the simulator combines statistical learning, financial engineering, and interactive visualization into a seamless workflow. Whether you're evaluating execution strategies or benchmarking trading algorithms, this tool offers a robust framework for real-world trading simulation.
👉 Discover how real-time data can transform your trading strategy today.
📊 Real-Time Order Book Processing with WebSocket
At the core of the GoQuant simulator is its ability to consume live Level 2 (L2) order book data directly from OKX through a dedicated WebSocket feed:
wss://ws.gomarket-cpp.goquant.io/ws/l2-orderbook/okx/BTC-USDT-SWAPThis connection ensures that every bid and ask update—down to microsecond-level changes—is captured in real time. The system processes each market tick efficiently, enabling low-latency decision-making and accurate modeling of market conditions.
The L2 data includes full depth information across multiple price levels, which is essential for estimating execution quality. By maintaining a constantly updated order book snapshot, the simulator can dynamically assess liquidity, spread fluctuations, and potential fill prices for both market and limit orders.
This real-time capability sets the foundation for all downstream predictions, including slippage estimation and market impact analysis.
🔍 Advanced Execution Cost Modeling
To reflect real-world trading challenges, the simulator employs several sophisticated models to estimate key execution parameters. These components work together to provide a comprehensive view of expected trading costs.
Slippage Prediction via Quantile Regression
Slippage—the difference between expected and actual execution price—is modeled using Quantile Regression (statsmodels.QuantReg) at the 50th percentile (median). This approach is particularly effective in volatile markets where traditional mean-based models fail.
Key input features include:
- Bid-ask spread
- Trade size in USD
- Order book depth
Model performance metrics:
- Mean Squared Error (MSE): 5.39e-05
- R² Score: 0.798
By focusing on median outcomes, the model provides a realistic estimate of typical slippage in basis points (bps), helping traders anticipate worst-case scenarios without overestimating average costs.
Rule-Based Fee Calculation
Transaction fees are computed based on the user’s fee tier and order type (maker or taker). For example:
- Tier 1 taker fee: 0.06%
- Tier 1 maker fee: 0.02%
These values are applied dynamically depending on whether the order adds liquidity (maker) or removes it (taker), ensuring accurate cost attribution in net execution calculations.
Market Impact Estimation with Almgren-Chriss Model
Market impact—the price movement caused by large trades—is estimated using the Almgren-Chriss Optimal Execution Framework, enhanced with dynamic programming techniques.
The model breaks down impact into two components:
- Temporary Impact: \( \eta \cdot v^\alpha \) — short-term price displacement during execution
- Permanent Impact: \( \gamma \cdot v^\beta \) — lasting effect due to information leakage
Additionally, execution risk is evaluated based on:
- Volatility
- Inventory position
- Time horizon
This allows traders to optimize order slicing strategies and minimize adverse price movements.
Net Execution Cost Aggregation
All cost components are combined into a single metric:
[
\text{Net Cost} = \text{Slippage} + \text{Fees} + \text{Market Impact}
]
This holistic view enables side-by-side comparison of different trading strategies under live market conditions.
👉 See how advanced modeling improves trade execution accuracy.
🤖 Machine Learning for Execution Behavior Analysis
Beyond cost modeling, the simulator uses machine learning to predict whether a given trade will execute as a maker or taker—a crucial distinction for fee optimization and strategy design.
Logistic Regression for Maker/Taker Classification
A Logistic Regression model (scikit-learn) is trained on labeled WebSocket snapshots to classify incoming orders. Input features include:
- Order price relative to mid-spread
- Order type and side (buy/sell)
- Current spread and depth
- Number of bid/ask levels
The model achieves 100% accuracy on real-time test data, thanks to clean feature engineering and high-quality labeling. It outputs the probability of an order being a taker, allowing users to adjust placement logic accordingly.
One-hot encoding is used for categorical variables like order_type and side, enhancing interpretability without sacrificing performance.
This classification capability adds another layer of realism to the simulation, especially when backtesting automated trading systems.
⏱ Internal Latency Monitoring
Execution speed matters. To measure system responsiveness, the simulator tracks internal latency using Python’s high-resolution timer (time.perf_counter()).
Each WebSocket message is timestamped upon arrival and processed in memory with minimal overhead. The time difference between reception and processing gives insight into computational delays within the pipeline.
Monitoring this metric helps identify bottlenecks and ensures that predictions remain synchronized with live market data—a critical factor in high-frequency trading environments.
🖥 Interactive Dashboard with Streamlit
The simulator features an intuitive Streamlit-based UI that presents both inputs and outputs in a clean two-panel layout:
Left Panel – User Inputs
- Exchange selection (currently OKX)
- Asset pair (BTC-USDT-SWAP)
- Order type (market/limit)
- Trade quantity (in USD)
- Volatility assumption
- Fee tier level
Right Panel – Real-Time Outputs
- Predicted slippage (bps)
- Estimated fees (%)
- Market impact (bps)
- Net execution cost
- Maker/taker probability
- Internal latency (ms)
This interactivity allows users to tweak parameters and instantly observe how changes affect overall execution quality—ideal for scenario testing and educational purposes.
⚙️ Performance Optimization Techniques
To maintain responsiveness under high-frequency data flow, several optimizations have been implemented:
- NumPy-accelerated dynamic programming for efficient Almgren-Chriss calculations
- In-memory JSON parsing to reduce I/O overhead
- Fallback logic in quantile regression to handle missing or incomplete data
- Lazy evaluation of model inference—models only run when new relevant ticks arrive
These enhancements ensure stable performance even during periods of extreme market volatility or data bursts.
🧩 How to Run the Project
Setting up the simulator is straightforward:
pip install -r requirements.txt
streamlit run ui_app.pyEnsure you have access to the WebSocket endpoint and that your environment supports real-time data streaming. All dependencies are listed in requirements.txt, including key packages like statsmodels, scikit-learn, numpy, and streamlit.
Frequently Asked Questions (FAQ)
Q: Can this simulator be used with exchanges other than OKX?
A: Currently, it's configured for OKX's BTC-USDT-SWAP pair via a specific WebSocket URL. However, the architecture supports modular integration of other exchanges with appropriate API adaptations.
Q: Is historical backtesting supported?
A: While the focus is on real-time simulation, recorded order book snapshots can be replayed to simulate past conditions—ideal for validating model accuracy.
Q: How accurate are the slippage predictions?
A: With an R² score of 0.798 and low MSE, the quantile regression model provides reliable median estimates under live market conditions.
Q: Does the tool account for network latency?
A: No—only internal processing latency is measured. Network transmission delays would require integration with external monitoring tools.
Q: Can I deploy this model in production trading systems?
A: It serves as a strong prototype or research tool. For production use, additional safeguards, stress testing, and compliance checks are recommended.
Q: Is there support for other asset pairs?
A: Yes—though currently focused on BTC-USDT-SWAP, the codebase can be extended to support additional perpetuals or spot pairs with minimal changes.
👉 Explore live trading insights powered by real-time analytics.