Skip to content

πŸš€ Real-time trading dashboard for OKX spot order book. Monitor liquidity, simulate executions, track latency, and visualize spreads & slippage. Interactive web app for traders & analysts. Built with Streamlit.

License

Notifications You must be signed in to change notification settings

UjjwalSaini07/RealTime-Trade-Simulator

Repository files navigation

πŸ“ˆ RealTime Trade Simulator & Orderbook Analysis

A Streamlit-based real-time trading dashboard for analyzing the OKX spot orderbook, simulating execution strategies, tracking latency, visualizing price spreads, and modeling slippage and market impact, it connects to the OKX WebSocket API to stream live order book data for selected spot assets. It provides real-time visualization of market depth metrics such as best bid/ask, spread, mid-price, volumes, latency monitoring, health status, and simulates basic order execution scenarios. The goal is to enable traders and analysts to monitor market liquidity and simulate order executions interactively in a clean, easy-to-use web interface.

Github License Info Generic badge GitHub stars Github Release

Features πŸš€

  • πŸ“‘ Real-time WebSocket order book data from OKX WebSocket API (books5 channel)
  • πŸ“Š Mid-price & spread time series visualization
  • ⚑ Latency & system health monitoring
  • 🎯 Market/Limit execution simulation with volatility
  • 🧠 Model-based slippage prediction & market impact estimation
  • πŸ—Ž Interactive parameter inputs- symbol, order type, quantity, volatility estimate, fee tiers, and refresh rate
  • πŸ’Ύ CSV export of historical order book data
  • πŸ“Ž Modular architecture: models/, utils/, ws_client.py
  • πŸ’» Display of key metrics:
    • Best Bid and Best Ask prices
    • Bid/Ask volumes
    • Spread and Mid Price over time
    • Latency measurement and health monitoring (Healthy / Warning / Unhealthy)

Project Structure πŸ—‚οΈ

RealTime-Trade-Simulator/
β”‚
β”œβ”€β”€ main.py                   # Streamlit app (UI + logic)
β”œβ”€β”€ ws_client.py              # WebSocket client for orderbook
β”‚
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ slippage_model.py     # Linear regression for slippage
β”‚   β”œβ”€β”€ market_impact.py      # Almgren–Chriss model
β”‚   └── maker_taker_model.py  # Logistic regression: maker vs taker
β”‚
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ latency_tracker.py    # Tracks system/network latency
β”‚   β”œβ”€β”€ fee_model.py          # Tiered fee computation
β”‚   └── data_utils.py         # Preprocess orderbook data
β”‚
β”œβ”€β”€ .env                      # Environment Variables
β”œβ”€β”€ test_ws.py                # TestModule File
β”œβ”€β”€ requirements.txt          # Python dependencies
└── README.md                 # Documentation (this file)

Architecture

  • main.py : Main Streamlit application responsible for the user interface, real-time order book visualization, trading simulation, model interaction, and export functionalities.
  • ws_client.py : WebSocket client managing the connection to OKX's public WebSocket API. Handles subscription, reconnection logic, and parsing of live order book data.
  • models/slippage_model.py : Implements a linear regression model to estimate slippage based on order size and market depth.
  • models/market_impact.py : Applies the Almgren–Chriss model to evaluate the market impact of large trades over time.
  • models/maker_taker_model.py : Uses logistic regression to predict whether a trade will be a maker or taker based on live order book features.
  • utils/latency_tracker.py : Measures and logs system and network latency to monitor real-time performance.
  • utils/fee_model.py : Calculates trading fees based on tiered fee structure, accounting for maker and taker differences.
  • utils/data_utils.py : Provides utility functions for preprocessing and structuring order book data.
  • .env : Environment configuration file storing sensitive data such as WebSocket URLs or API credentials.
  • requirements.txt : Lists all Python dependencies required to install and run the application.
  • test_ws.py : Standalone test script to validate WebSocket connectivity and data integrity.
  • README.md : Documentation file providing an overview, setup instructions, and project structure.

Installation πŸ› οΈ

  • First Read this License & their terms then proceed.
  • Star ⭐ the Repository
  • Fork the repository (Optional)
  • Project Setup:
  1. Clone the Project
git clone https://github.com/UjjwalSaini07/RealTime-Trade-Simulator.git
  1. Navigate to the project Root directory:
cd RealTime-Trade-Simulator
  1. Install dependencies
pip install -r requirements.txt
  1. Create a .env file in the root directory and Setup Contact

Usage πŸ–₯️

  • Run the Streamlit app:
python -m streamlit run main.py

Project Setup Using Docker Containerization:

  1. Start the Docker Engine Locally or Use Any Service
  2. Navigate to the project Root directory:
    cd RealTime-Trade-Simulator
  1. Run DockerFile:
    docker-compose up --build
  1. Wait for Generating the Image

How Docker Image Builds Looks

image

Docker Image Starts the Server Locally

image

Project Docker Container WebSockets Data Fetching

image

  1. Now Simply use the Project using Docker Container

Dashboard Panels

  • Metrics: Shows current best bid/ask, spread, mid price, bid/ask volumes, latency, and health status.
  • Charts: Real-time line charts for mid price, spread, and latency over time.
  • Latency & Health Monitoring: Shows latency trends and health status based on latency thresholds.
  • Execution Simulation: Displays simulated execution results based on order type and market conditions.
  • Export Data: Button to download historical order book snapshots and metrics as CSV.

Model Documentation 🧠

1. Slippage Model

Path: models/slippage_model.py

  • Model: Linear Regression
  • Purpose: Estimate price deviation from order size, volatility, and spread.
  • Features: order_size_usd, market_volatility, spread_percent
  • Target: slippage_bps

2. Market Impact Model

Path: models/market_impact.py

  • Framework: Almgren–Chriss
  • Assumptions:
    • Linear coefficients for temporary and permanent impact
    • Liquidity proxy via market volume
  • Equation:
    impact = Ξ· * (Q / V) + Ξ» * (Q / V)^2
    • Q: order size
    • V: market volume
    • Ξ·, Ξ»: impact coefficients

3. Maker vs Taker Model

Path: models/maker_taker_model.py

  • Model: Logistic Regression
  • Purpose: Predict limit order execution likelihood.
  • Features: spread, volatility, order_type, relative_price_distance

Utility Modules 🧰

1. utils/latency_tracker.py : Measures roundtrip latency for WebSocket events and internal app cycles.

2. utils/fee_model.py : Supports tiered maker-taker fee structures (OKX Tier 1, 2, 3).

3. utils/data_utils.py : Converts OKX order book ticks into normalized pandas DataFrames.

Performance Optimization βš™οΈ

  • @st.cache_resource to avoid re-instantiating WebSocket clients
  • deque with maxlen for lightweight time series
  • DataFrames rebuilt only from live updates
  • Streamlit container reuse to reduce render load

Future Enhancements 🧭

Feature Description
πŸ”Œ FastAPI Backend Refactor core logic into a FastAPI backend to support RESTful and WebSocket endpoints for scalable API-based integration.
πŸ“± Mobile Dashboard Build a responsive frontend using React Native or Flutter to access real-time analytics from mobile devices.
πŸ“¦ Redis Caching Layer Introduce Redis for efficient storage and retrieval of real-time market data and reduce load on WebSocket listeners.
πŸ“ˆ Historical Backtesting Engine Implement a module for backtesting execution strategies using historical tick data.
πŸ” User Authentication Add secure login with role-based access (e.g., admin vs. analyst) using OAuth2 or Firebase.
πŸ§ͺ CI/CD & Dockerization Containerize the entire system and set up CI/CD pipelines with GitHub Actions and Docker Compose.

Contact πŸ“ž

Feel free to reach out if you have any questions or suggestions!

Screenshots πŸ“·

Trading Dashboard

image

Terminal Data Retrieval

image

Video Demonstration πŸ“·

Project_Demonstration.mp4

About

πŸš€ Real-time trading dashboard for OKX spot order book. Monitor liquidity, simulate executions, track latency, and visualize spreads & slippage. Interactive web app for traders & analysts. Built with Streamlit.

Topics

Resources

License

Security policy

Stars

Watchers

Forks