SkillAgentSearch skills...

Automated Financial Market Trading System

This project is a Python-based trading simulator that allows users to simulate trading strategies, manage an order book, and interact with a mock trading environment using various algorithmic traders. The simulator includes a FIX (Financial Information eXchange) protocol handler, a market-making algorithm, and synthetic liquidity generation.

Install / Use

npx skills add ThePredictiveDev/Automated-Financial-Market-Trading-System

Installs into whichever agent you are using.

README

📈 Automated Financial Trading System

<div align="center">

Python License Tests Version Contributions

<img src="https://capsule-render.vercel.app/api?type=waving&color=gradient&customColorList=12,20,25&height=140&section=header&text=Trade.%20Simulate.%20Understand.&fontSize=38&fontColor=ffffff&animation=fadeIn&fontAlignY=38&desc=A%20full%20stock%20exchange%2C%20built%20from%20scratch%2C%20that%20runs%20on%20your%20laptop&descAlignY=58&descAlign=50" width="100%"/> </div>

What is this, really?

Imagine you could build your own tiny stock exchange — one with real buyers and sellers, a real order book, and real price competition — except nobody's money is actually at risk and you can rewind time as many times as you want. That's what this is.

You feed it a stock symbol, tell it how you want to trade (or let one of the built-in robot traders do it for you), and watch as orders get matched, prices move, and a portfolio grows or shrinks in real time — powered by the same mechanics real exchanges use under the hood.

In one line: a from-scratch limit order book, matching engine, market maker, algorithmic traders, multi-venue router, FIX protocol engine, and backtester — a complete miniature electronic market you run entirely on your own machine.

For anyone who wants the deeper version: this is a research and education platform for market microstructure. It implements price-time priority matching, self-trade prevention, time-in-force handling (GTC/IOC/FOK), Avellaneda-Stoikov market making, pre-trade risk controls, multi-venue NBBO routing, opening/closing auctions, a real FIX 4.2 session layer, and institutional-grade backtesting with Sharpe/Sortino/drawdown analytics — all as an installable Python package with both a guided, no-flags CLI and a full scriptable one.

🎯 What You Can Do With It

If you trade or invest — backtest a strategy against real historical data, paper-trade it live against a simulated market, and see exactly how it would have performed with professional-grade metrics, before ever risking real money.

If you build or research — study market microstructure hands-on: watch how price-time priority actually resolves a crossed book, how a market maker's quotes skew with inventory, how an order gets swept across venues for the best effective price. Wire in your own strategy in a dozen lines of code.

If you teach or learn — every mechanism is small enough to read end-to-end and readable enough to actually learn from: the whole matching engine is a few hundred lines, not a black box.

📋 Table of Contents

🚀 What's Included

Core engine

  • Limit order book with strict price-time priority and tick/lot normalization
  • Matching engine supporting limit/market orders, GTC/IOC/FOK time-in-force, post-only, self-trade prevention (that preserves other participants' queue priority instead of corrupting it), price bands, halts, and configurable slippage/latency simulation
  • Per-instrument configuration (tick size, lot size, trading hours) via InstrumentRegistry, instantiated per engine so parallel backtests and Optuna trials never leak state into each other
  • Order book snapshotting (interval-based or on demand) and deterministic event-log replay (EventLogger + ReplayRunner)
  • Opening/closing auction uncrossing (single clearing price maximizing matched volume)

Trading & market making

  • Built-in algorithmic traders: Momentum, EMA crossover, Swing (support/ resistance), and a news-sentiment trader (TensorFlow-based, with memory of already-traded headlines so it doesn't re-trade stale news)
  • Avellaneda-Stoikov-inspired market maker: multi-level laddering, inventory skew, volatility-based spread widening, momentum skew, and a drawdown kill-switch measured against a configurable capital base
  • Framework for custom traders: subclass AlgorithmicTrader, load by module:ClassName from the CLI or guided prompts
  • TWAP/VWAP parent-order slicing for reduced market impact on large orders

Risk & connectivity

  • Pre-trade risk manager: position/notional limits, round-lot enforcement, per-owner order rate limiting, per-owner drawdown kill-switch, volatility halts, leverage caps, per-symbol gross exposure caps, and manual owner/symbol enable/disable switches
  • Multi-venue router: NBBO aggregation across independent MatchingEngine instances and inter-market-sweep order splitting by depth and effective (fee-adjusted) price
  • A real FIX 4.2 engine, not just a message-format demo: full session layer (Logon, Heartbeat, TestRequest, ResendRequest with true message replay, SequenceReset, Logout), MsgSeqNum tracking in both directions, and real ExecutionReport/Reject generation — with both a server (FixApplication) and a client (FixClient) so it talks to itself out of the box. See FIX Protocol Engine.
  • A lightweight JSON-over-TCP order control channel for live mode (place/ cancel/modify orders from a second terminal without FIX)
  • Event streaming: a generic pub-sub EventBus plus optional Redis and Kafka publishers

Backtesting & analytics

  • Single-asset and multi-asset backtesting against historical data (yahooquery/yfinance, with local caching and retry/backoff)
  • Performance metrics (Sharpe, Sortino, CAGR, max drawdown), HTML report export, and rolling metrics printed during live/replay runs
  • Trade cost analysis (TCA): slippage vs. mid/last and adverse-selection tracking, written to CSV
  • Optional Optuna hyperparameter search and MLflow experiment tracking
  • Optional PostgreSQL persistence (DbLogger) for executions, equity, and strategy configs

Usability

  • Two CLIs in one: a guided, prompt-driven mode for anyone who doesn't want to memorize flags, and a full argparse flag interface for scripting/CI
  • Clean, actionable error messages for expected failures (missing market data provider, bad custom-trader spec, etc.) instead of raw tracebacks -- pass --debug to get the full traceback back when you actually want it
  • Every optional third-party dependency (simplefix, tensorflow, sqlalchemy, optuna, mlflow, redis, confluent-kafka) degrades gracefully: if it's not installed, the feature that needs it raises one clear RuntimeError telling you what to pip install, instead of crashing somewhere deep in the call stack
  • 109 automated tests covering the matching engine, order book, portfolio, risk manager, strategies, market maker, router, the FIX session layer, DB/streaming graceful-degradation paths, socket-level order-CLI behavior, snapshot/replay round-trips, auctions, and the CLI itself end to end

🏗️ Project Layout

trading_simulator/
├── __init__.py            # top-level re-exports: `from trading_simulator import X`
├── __main__.py             # `python -m trading_simulator` entry point
├── config.py                # environment-variable-driven defaults
├── core/
│   ├── order.py              # Order dataclass + validation
│   ├── order_book.py          # price-time-priority book, its own lock
│   ├── matching_engine.py       # matching, TIF, auctions, snapshots, risk hook
│   ├── instruments.py            # per-symbol tick/lot/hours registry
│   └── execution.py               # Execution/fill record
├── portfolio/                # Portfolio + multi-owner PortfolioDispatcher
├── risk/                      # RiskManager (pre-trade checks, kill-switches)
├── strategies/                  # Momentum/EMA/Swing/Sentiment/Custom traders
├── marketmaker/                   # Avellaneda-Stoikov MarketMaker
├── marketdata/                      # historical + live feed, synthetic liquidity
├── connectivity/                      # FIX engine, order-CLI socket server, router
│   ├── fix_session.py                    # FIX session-layer state machine
│   ├── fix_app.py                         # FixApplication (server) + FixClient
│   ├── order_cli.py                        # JSON-over-TCP order control
│   └── router.py                            # NBBO aggregation + sweep routing
├── execution_algos/                     # TWAP/VWAP slicing
├── persistence/                           # CSV/audit/event logging, optional DB
├── streaming/                              # EventBus + Redis/Kafka publishers
├── backtest/                                # runner, metrics, replay, Optuna glue
└── cli/
    ├── args.py                                 # argparse flag definitions
    ├── guided.py                       

Related Skills

View on GitHub
GitHub Stars36
CategoryDevelopment
Updated1d ago
Forks11

Languages

Python

Security Score

95/100

Audited on Aug 7, 2026

No findings