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.
๐ค Automated Financial Market Trading System
A comprehensive, production-ready algorithmic trading system with real-time market data, multiple trading strategies, risk management, and advanced backtesting capabilities.
๐ Table of Contents
- ๐ Features
- ๐ฏ What You Can Do
- ๐๏ธ Architecture
- ๐ฆ Installation
- โก Quick Start
- ๐ง Usage Modes
- ๐งญ Interactive CLI (No-Flags Guided Mode)
- ๐ Trading Strategies
- ๐ก๏ธ Risk Management
- ๐ Backtesting
- ๐ API Integration
- ๐ Configuration
- ๐ Performance Analytics
- ๐ฅ๏ธ Live Order Control (Split Terminal)
- ๐ค Contributing
- ๐ License
๐ Features
Core Trading Engine
- ๐ง High-Performance Matching Engine: Real-time order matching with price-time priority
- ๐ Order Book Management: Full limit order book with bid/ask depth tracking
- โก Low-Latency Execution: Sub-millisecond order processing with configurable latency simulation
- ๐ FIX Protocol Support: Industry-standard FIX 4.2 protocol integration via simplefix
- ๐ Real-time Market Data: Live price feeds via yfinance with automatic fallback mechanisms
Algorithmic Trading Strategies
- ๐ Momentum Trading: Price momentum-based strategy with configurable lookback periods
- ๐ EMA Crossover: Exponential Moving Average crossover strategy with customizable windows
- ๐ Swing Trading: Support/resistance level-based trading with dynamic level adjustment
- ๐ง Sentiment Analysis: AI-powered news sentiment trading using TensorFlow/Keras models
- ๐ฏ Custom Strategies: Framework for implementing custom trading algorithms
Market Making & Liquidity
- ๐ช Avellaneda-Stoikov Market Maker: Advanced market making with inventory management
- ๐ฐ Multi-Level Quoting: Configurable quote laddering with size decay
- ๐ Dynamic Spread Adjustment: Volatility-based spread widening and momentum skewing
- ๐ก๏ธ Drawdown Protection: Automatic quote withdrawal on excessive losses
- ๐ Synthetic Liquidity: Automated liquidity injection for testing scenarios
Risk Management System
- ๐ Position Limits: Per-symbol and portfolio-level position constraints
- ๐ฐ Notional Limits: Maximum order and portfolio notional value controls
- โก Rate Limiting: Configurable order submission rate limits per strategy
- ๐ Drawdown Protection: Automatic trading halt on portfolio drawdown thresholds
- ๐ Volatility Halts: Market volatility-based trading suspension
- ๐ฏ Leverage Controls: Maximum leverage and gross exposure limits
Advanced Backtesting
- ๐ Historical Data: Yahoo Finance integration with intelligent caching
- โก High-Speed Simulation: Optimized backtesting engine with configurable slippage
- ๐ Performance Analytics: Comprehensive performance metrics and reporting
- ๐ Multi-Asset Testing: Simultaneous testing across multiple symbols
- ๐ Parameter Optimization: Optuna integration for strategy parameter tuning
- ๐ MLflow Integration: Experiment tracking and model versioning
Data & Analytics
- ๐ Real-time Portfolio Tracking: Live P&L, positions, and equity curve monitoring
- ๐ Trade Cost Analysis (TCA): Slippage analysis and adverse selection tracking
- ๐ Execution Analytics: Detailed execution quality and market impact analysis
- ๐ Performance Metrics: Sharpe ratio, Sortino ratio, max drawdown, CAGR
- ๐ HTML Reports: Automated performance report generation with interactive charts
- ๐ CSV Logging: Comprehensive trade and equity data export
Infrastructure & Integration
- ๐๏ธ Database Support: PostgreSQL integration for persistent data storage
- ๐ก Event Streaming: Redis and Kafka integration for real-time event distribution
- ๐ง Configuration Management: Flexible configuration system with environment variables
- ๐ Monitoring: Comprehensive logging and audit trails
- ๐ Snapshot Management: Order book state persistence and recovery
- ๐ฏ Auction Support: Opening/closing auction mechanisms
๐ฏ What You Can Do
For Traders & Investors
- ๐ Test Trading Strategies: Backtest your strategies on historical data with realistic market conditions
- ๐ Paper Trading: Practice trading with virtual money in real-time market conditions
- ๐ Portfolio Analysis: Analyze your trading performance with professional-grade metrics
- ๐ฏ Strategy Development: Develop and optimize custom trading algorithms
- ๐ Market Research: Study market microstructure and order book dynamics
For Developers & Researchers
- ๐ฌ Market Microstructure Research: Study order book dynamics and market impact
- ๐ Algorithm Development: Build and test new trading algorithms
- ๐ง System Integration: Integrate with existing trading infrastructure via FIX protocol
- ๐ Performance Testing: Benchmark trading strategies and execution algorithms
- ๐ฏ Machine Learning: Develop ML-based trading strategies with sentiment analysis
For Institutions
- ๐ข Risk Management: Implement comprehensive risk controls and monitoring
- ๐ Compliance: Maintain detailed audit trails and trade records
- ๐ง Infrastructure: Build scalable trading infrastructure with real-time capabilities
- ๐ Analytics: Generate institutional-grade performance and risk analytics
- ๐ Integration: Connect with existing trading systems and data feeds
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Trading System Architecture โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ
โ โ Market Data โ โ FIX API โ โ Web UI โ โ
โ โ Feed โ โ Client โ โ (Future) โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ
โ โ โ โ โ
โ โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Trading Engine Core โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โ โ Order โ โ Matching โ โ Risk โ โ โ
โ โ โ Book โ โ Engine โ โ Management โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Algorithmic Traders โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โ โ Momentum โ โ EMA โ โ Swing โ โ โ
โ โ โ Trader โ โ Trader โ โ Trader โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โ โ Sentiment โ โ Market โ โ Custom โ โ โ
โ โ โ Trader โ โ Maker โ โ Trader โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Data & Analytics โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โ โ Portfolio โ โ Trade โ โ Performance โ โ โ
โ โ โ Tracker โ โ Logger โ โ Analytics โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Storage & Integration โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โ โ PostgreSQL โ โ Redis โ โ Kafka โ โ โ
โ โ โ Database โ โ Cache โ โ Events โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฆ Installation
Prerequisites
- Python 3.11+ (Required for modern type hints and performance features)
- Git (For cloning the repository)
- pip (Python package manager)
Basic Installation
# Clone the repository
git clone https://github.com/yourusername/Automated-Financial-Market-Trading-System.git
cd Automated-Financial-Market-Trading-System
Create a virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
Install core dependencies
pip install -r requirements.txt
Full Installation (all features)
# Install all features (core + optional integrations)
pip install -r requirements.txt
Environment Setup
# Copy environment template
cp .env.example .env
Edit environment variables
nano .env
Key Environment Variables (placeholders):
# API Keys (Optional) NEWSAPIKEY=yournewsapikeyhere YAHOOFINANCEAPIKEY=youryahookeyhere
Database Configuration
DATABASEURL=postgresql://user:pass@localhost/tradingdb
REDIS_URL=redis://localhost:6379
KAFKABOOTSTRAPSERVERS=localhost:9092
Trading Configuration
DEFAULTINITIALCASH=1000000
DEFAULTFEEBPS=1.0
DEFAULTMAKERREBATE_BPS=0.5
Risk Management
MAXORDERQTY=1000
MAXSYMBOLPOSITION=10000
MAXGROSSNOTIONAL=5000000
โก Quick Start
1. Simple Backtest
# Run a basic backtest on AAPL
python tradingsimulatorwithalgorithmictraders.py \
--mode backtest \
--symbol AAPL \
--start-date 2023-01-01 \
--end-date 2023-12-31 \
--enable-traders \
--export-report
2. Live Trading Simulation
# Start live trading simulation with market maker
python tradingsimulatorwithalgorithmictraders.py \
--mode live \
--symbol AAPL \
--md-interval 30 \
--enable-traders
3. Interactive Demo
# Run interactive demo mode
python tradingsimulatorwithalgorithmictraders.py --mode demo
๐ง Usage Modes
Backtest Mode
Run historical simulations with configurable parameters:python tradingsimulatorwithalgorithmictraders.py \
--mode backtest \
--symbol AAPL \
--start-date 2023-01-01 \
--end-date 2023-12-31 \
--enable-traders \
--initial-cash 1000000 \
--fee-bps 1.0 \
--slippage-bps-per-100 0.5 \
--latency-ms 10 \
--export-report \
--report-out performance_report.html
Multi-Asset Backtest:
python tradingsimulatorwithalgorithmictraders.py \ --mode backtest \ --symbols "AAPL,MSFT,GOOGL,TSLA" \ --start-date 2023-01-01 \ --end-date 2023-12-31 \ --enable-traders
Live Mode
Real-time trading simulation with live market data:python tradingsimulatorwithalgorithmictraders.py \
--mode live \
--symbol AAPL \
--md-interval 30 \
--enable-traders \
--fix-host localhost \
--fix-port 5005 \
--inject-liquidity 60
Replay Mode
Historical data replay at configurable speed:python tradingsimulatorwithalgorithmictraders.py \
--mode replay \
--symbol AAPL \
--start-date 2023-01-01 \
--end-date 2023-12-31 \
--replay-speed 5.0 \
--enable-traders
Demo Mode
Interactive order book demonstration:python tradingsimulatorwithalgorithmictraders.py --mode demo
๐งญ Interactive CLI (No-Flags Guided Mode)
Prefer prompts over flags? Just run without arguments:
python tradingsimulatorwithalgorithmictraders.py
What you can configure interactively
- Mode: Backtest, Live, Replay, Demo (and an Advanced mode for manual flag entry)
- Symbols and date ranges (Backtest/Replay)
- Market data interval (Live) and replay pacing (Replay)
- Built-in trader parameters (Momentum/EMA/Swing)
- Market microstructure: slippage, latency
- Matching protections: price band (bps), reference (mid/last), taker fee, maker rebate
- Engine: submission queue on/off + queue size, order-book snapshots (interval + dir)
- Risk manager: min/round lots, max qty/position/notional, order rate limit, drawdown limit, volatility halt, leverage, per-symbol gross exposure
- Custom traders: add any number of
module:ClassNamewith JSON params - Reporting & experiments: export HTML report, Optuna trials, MLflow tracking
Custom traders via prompts
- When asked โAdd custom traders?โ choose Yes and enter:
yourpkg.strats:MyTrader
- JSON params: {"lookback": 20, "interval": 0.0, "owner_id": "mytrader"}
- Repeat to add multiple strategies. The system dynamically imports, instantiates, and wires them into the live/backtest pipeline.
Optuna, MLflow, and TCA
- Optuna: enable and set trials; optionally configure MLflow URI and experiment name for tracking
- TCA: enabled automatically; slippage/adverse selection written to
tca.csvandtca_adv.csv
๐ Trading Strategies
1. Momentum Trader
Trades based on short-term price momentum:from trading_simulator import MomentumTrader
trader = MomentumTrader( symbol="AAPL", matching_engine=engine, lookback=5, # Lookback period for momentum calculation interval=0.1 # Trading interval in seconds )
Strategy Logic:
- Calculates price change over lookback period
- Buys on positive momentum (price increase)
- Sells on negative momentum (price decrease)
- Aggressively crosses the book at best bid/ask
2. EMA-Based Trader
Uses Exponential Moving Average crossover signals:from trading_simulator import EMABasedTrader
trader = EMABasedTrader( symbol="AAPL", matching_engine=engine, short_window=5, # Short EMA period long_window=20, # Long EMA period interval=0.1 )
Strategy Logic:
- Calculates short and long EMAs
- Generates buy signal when short EMA > long EMA
- Generates sell signal when short EMA < long EMA
- Implements trend-following approach
3. Swing Trader
Trades based on support and resistance levels:from trading_simulator import SwingTrader
trader = SwingTrader( symbol="AAPL", matching_engine=engine, support_level=100.0, # Support price level resistance_level=200.0, # Resistance price level interval=0.1 )
Strategy Logic:
- Buys when price approaches support level
- Sells when price approaches resistance level
- Implements mean-reversion approach
- Configurable support/resistance levels
4. Sentiment Analysis Trader
AI-powered trading based on news sentiment:from trading_simulator import SentimentAnalysisTrader
trader = SentimentAnalysisTrader( symbol="AAPL", matching_engine=engine, modelfile="sentimentclassifier_model.keras", newsapikey="yourapikey", interval=60.0 # Check news every 60 seconds )
Strategy Logic:
- Fetches latest news via NewsAPI
- Analyzes sentiment using TensorFlow model
- Buys on positive sentiment
- Sells on negative sentiment
- Holds on neutral sentiment
5. Market Maker
Advanced market making with inventory management:from trading_simulator import MarketMaker
maker = MarketMaker( symbol="AAPL", matching_engine=engine, gamma=0.1, # Risk aversion parameter k=1.5, # Order book intensity horizon_seconds=60.0, # Quote horizon max_inventory=1000, # Maximum inventory baseordersize=100, # Base quote size min_spread=0.01, # Minimum spread num_levels=2, # Quote levels levelspacingbps=2.0, # Level spacing in basis points size_decay=0.7, # Size decay factor momentum_window=10, # Momentum calculation window alpha_skew=0.5, # Momentum skew weight volwidenz=2.0, # Volatility widening threshold drawdown_limit=0.2 # Drawdown protection limit )
Strategy Logic:
- Implements Avellaneda-Stoikov market making model
- Adjusts quotes based on inventory position
- Widens spreads during high volatility
- Skews quotes based on price momentum
- Automatically withdraws quotes on drawdown
6. Custom Trader
Framework for implementing custom strategies:from trading_simulator import AlgorithmicTrader
class MyCustomTrader(AlgorithmicTrader): def init(self, symbol, matching_engine, threshold=0.0): super().init(symbol, matching_engine, interval=0.1) self.threshold = threshold def trade(self): if self.current_price is None: return # Your custom trading logic here if self.current_price < self.threshold: order = Order( id=uuid.uuid4().hex, price=self.current_price, quantity=10, side='buy', type='market', symbol=self.symbol, owner_id='custom' ) self.matchingengine.matchorder(order)
๐ก๏ธ Risk Management
Configure All Risk Controls Interactively
Run the script with no flags and choose to customize risk when prompted. You can set:- Position/Notional Limits: max order qty, max net position per symbol, max gross notional per order
- Lot Rules: min order qty, lot size, round-lot required
- Rate Limiting: per-owner order rate limit (orders/sec)
- Drawdown Protection: per-owner drawdown limit (fraction)
- Volatility Halts: window length and |z| threshold
- Leverage & Exposure: max leverage and per-symbol gross exposure
Position Limits
risk_manager = RiskManager(
portfolio=portfolio,
maxorderqty=1000, # Maximum order quantity
maxsymbolposition=10000, # Maximum position per symbol
maxgrossnotional=5000000, # Maximum order notional
minorderqty=1, # Minimum order quantity
lot_size=1, # Lot size requirement
roundlotrequired=False # Round lot requirement
)
Example Custom Traders (Ready to Use)
Create a module like examples/strats.py with:
from collections import deque
import uuid
from tradingsimulatorwithalgorithmictraders import AlgorithmicTrader, Order
class BreakoutTrader(AlgorithmicTrader): def init(self, symbol, matchingengine, lookback=20, bandbps=5, interval=0.0, owner_id='breakout'): super().init(symbol, matching_engine, interval) self.lookback = int(lookback) self.bandbps = float(bandbps) self.ownerid = str(ownerid) self.buf = deque(maxlen=max(3, self.lookback))
def onmarketdata(self, data): super().onmarketdata(data) self.buf.append(float(data['price']))
def trade(self): if self.current_price is None or len(self.buf) < self.lookback: return hi = max(self.buf) lo = min(self.buf) band = self.currentprice * (self.bandbps / 10000.0) ob = self.matchingengine.orderbook bestask = ob.getbest_ask() bestbid = ob.getbest_bid() if bestask is None or bestbid is None: return if self.current_price > hi + band: o = Order(id=uuid.uuid4().hex, price=float(bestask), quantity=100, side='buy', type='limit', symbol=self.symbol, ownerid=self.owner_id) self.matchingengine.matchorder(o) elif self.current_price < lo - band: o = Order(id=uuid.uuid4().hex, price=float(bestbid), quantity=100, side='sell', type='limit', symbol=self.symbol, ownerid=self.owner_id) self.matchingengine.matchorder(o)
class MeanRevTrader(AlgorithmicTrader): def init(self, symbol, matchingengine, lookback=20, zentry=1.0, interval=0.0, owner_id='meanrev'): super().init(symbol, matching_engine, interval) self.lookback = int(lookback) self.zentry = float(zentry) self.ownerid = str(ownerid) self.buf = deque(maxlen=max(3, self.lookback))
def onmarketdata(self, data): super().onmarketdata(data) self.buf.append(float(data['price']))
def trade(self): import numpy as np if self.current_price is None or len(self.buf) < self.lookback: return arr = np.array(self.buf, dtype=float) sma = float(arr.mean()) std = float(arr.std(ddof=0)) if std <= 0: return z = (self.current_price - sma) / std ob = self.matchingengine.orderbook bestask = ob.getbest_ask() bestbid = ob.getbest_bid() if bestask is None or bestbid is None: return if z <= -self.z_entry: o = Order(id=uuid.uuid4().hex, price=float(bestask), quantity=100, side='buy', type='limit', symbol=self.symbol, ownerid=self.owner_id) self.matchingengine.matchorder(o) elif z >= self.z_entry: o = Order(id=uuid.uuid4().hex, price=float(bestbid), quantity=100, side='sell', type='limit', symbol=self.symbol, ownerid=self.owner_id) self.matchingengine.matchorder(o)
Add them interactively when prompted by specifying examples.strats:BreakoutTrader or examples.strats:MeanRevTrader and providing JSON parameters.
Building Custom Traders (Detailed)
Custom traders must subclass AlgorithmicTrader and implement trade() (optional onmarketdata). Constructor signature should be:
def init(self, symbol: str, matching_engine: MatchingEngine, **params):
super().init(symbol, matching_engine, interval=params.get('interval', 0.0))
They submit orders through matchingengine.matchorder(Order(...)). Use owner_id to segment PnL and risk by strategy.
Integration Pipeline
- Market data tick โ your traderโs
onmarketdataโ yourtrade()โ createOrderโ risk checks โ matching โexecutions.csv/TCA โ owner-aware Portfolio โequity_curve.csv - The system tracks adverse selection and slippage automatically.
Adding Custom Traders Interactively
- Run
python tradingsimulatorwithalgorithmictraders.pywith no flags - Choose a mode (Backtest/Replay/Live)
- When prompted โAdd custom traders?โ
module.path:ClassName
- Provide JSON params, e.g. { "lookback": 20, "interval": 0.0, "owner_id": "mytrader" }
- Repeat to add more; leave blank to continue.
- Add
mypkg.strats:BreakoutTraderwith{ "lookback": 15, "bandbps": 8, "ownerid": "bo15" } - Add
mypkg.strats:MeanRevTraderwith{ "lookback": 30, "zentry": 1.25, "ownerid": "mr30" }
Best Practices
- Cross at best bid/ask for immediate fills when you want action; use resting orders deliberately
- Use small
intervalor0.0in backtests for per-bar evaluation - Set a unique
owner_idper strategy for clean PnL/risk isolation - Keep code non-blocking; do not sleep inside
trade()
Rate Limiting
risk_manager = RiskManager(
# ... other parameters ...
orderratelimitpersec=10, # Max orders per second per owner
ownerdrawdownlimit=0.2, # 20% drawdown limit
max_leverage=3.0, # Maximum leverage
maxsymbolgross_exposure=1000000 # Max gross exposure per symbol
)
Volatility Protection
risk_manager = RiskManager(
# ... other parameters ...
volatility_window=20, # Volatility calculation window
volatilityhaltz=3.0 # Z-score threshold for volatility halt
)
Kill Switches
# Disable specific traders
riskmanager.disableowner("momentum_trader")
Disable specific symbols
riskmanager.disablesymbol("TSLA")
Re-enable when conditions improve
riskmanager.enableowner("momentum_trader")
riskmanager.enablesymbol("TSLA")
๐ Backtesting
Basic Backtest
from tradingsimulator import runbacktest, loadhistoricaldata
Load historical data
data = loadhistoricaldata("AAPL", "2023-01-01", "2023-12-31")
Create components
order_book = OrderBook()
engine = MatchingEngine(order_book)
portfolio = Portfolio(initial_cash=1000000)
marketmaker = MarketMaker(symbol="AAPL", matchingengine=engine)
Create traders
traders = [
MomentumTrader(symbol="AAPL", matching_engine=engine, lookback=5),
EMABasedTrader(symbol="AAPL", matchingengine=engine, shortwindow=5, long_window=20),
SwingTrader(symbol="AAPL", matchingengine=engine, supportlevel=100, resistance_level=200)
]
Run backtest
runbacktest(data, marketmaker, engine, traders=traders, portfolio=portfolio)
Multi-Asset Backtest
from tradingsimulator import runmultibacktest, loadmultihistoricaldata
Load data for multiple symbols
datamap = loadmultihistoricaldata(
["AAPL", "MSFT", "GOOGL"],
"2023-01-01",
"2023-12-31"
)
Create engines and market makers for each symbol
engines = {}
makers = {}
for symbol in ["AAPL", "MSFT", "GOOGL"]:
ob = OrderBook()
eng = MatchingEngine(ob)
engines[symbol] = eng
makers[symbol] = MarketMaker(symbol=symbol, matching_engine=eng)
Run multi-asset backtest
runmultibacktest(data_map, engines, makers, portfolio=portfolio)
Parameter Optimization
import optuna
from tradingsimulator import objectiveoptuna
Define optimization objective
def objective(trial):
return objective_optuna(
trial,
symbol="AAPL",
start="2023-01-01",
end="2023-12-31",
base_params={
'initial_cash': 1000000,
'fee_bps': 1.0,
'riskmaxorder_qty': 1000,
'riskmaxsymbol_position': 10000,
'riskmaxgross_notional': 5000000
},
log_dir=".logs"
)
Create study and optimize
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100)
print(f"Best parameters: {study.best_params}") print(f"Best value: {study.best_value}")
๐ API Integration
FIX Protocol Integration
from trading_simulator import FixApplication
Create FIX application
fixapp = FixApplication(matchingengine)
Start FIX server
fix_app.start(host='localhost', port=5005)
Send FIX order
ordermsg = fixapp.createordermessage({
'id': 'ORDER001',
'side': 'buy',
'symbol': 'AAPL',
'price': 150.0,
'quantity': 100
})
fixapp.sendmessage(order_msg, host='localhost', port=5005)
Market Data Integration
from trading_simulator import MarketDataFeed
Create market data feed
feed = MarketDataFeed(symbol="AAPL")
Subscribe to market data
class MySubscriber:
def receive(self, data):
print(f"Price: {data['price']}, Volume: {data['volume']}")
subscriber = MySubscriber() feed.subscribe(subscriber)
Start feed
feed.start(interval_seconds=60)
Database Integration
from trading_simulator import DbLogger
Create database logger
dblogger = DbLogger("postgresql://user:pass@localhost/tradingdb")
Log execution
dblogger.logexecution(execution)
Log equity
dblogger.logequity(timestamp, net_liq, realized, cash)
Save configuration
dblogger.saveconfig("strategy_config", {
'momentum_lookback': 5,
'emashortwindow': 5,
'emalongwindow': 20
})
Event Streaming
from tradingsimulator import EventBus, makeredispublisher, makekafka_publisher
Create event bus
event_bus = EventBus()
Add Redis publisher
redispub = makeredispublisher("redis://localhost:6379", "tradingevents")
eventbus.addpublisher(redis_pub)
Add Kafka publisher
kafkapub = makekafkapublisher("localhost:9092", "tradingevents")
eventbus.addpublisher(kafka_pub)
Publish events
eventbus.publish("orderexecuted", {
'order_id': 'ORDER001',
'price': 150.0,
'quantity': 100,
'timestamp': '2023-01-01T10:00:00Z'
})
๐ Configuration
Command Line Arguments
# Mode selection
--mode {backtest,live,demo,replay}
Symbol and data
--symbol SYMBOL # Trading symbol (default: AAPL)
--symbols SYMBOLS # Comma-separated symbols for multi-asset
--start-date START_DATE # Backtest start date (YYYY-MM-DD)
--end-date END_DATE # Backtest end date (YYYY-MM-DD)
Trading parameters
--initial-cash INITIAL_CASH # Initial portfolio cash (default: 1000000)
--fee-bps FEE_BPS # Execution fee in basis points (default: 0.0)
--slippage-bps-per-100 SLIPPAGE # Slippage in bps per 100 shares (default: 0.0)
--latency-ms LATENCY # Order latency in milliseconds (default: 0)
Risk management
--risk-max-order-qty QTY # Maximum order quantity (default: 1000)
--risk-max-symbol-position POS # Maximum position per symbol (default: 10000)
--risk-max-gross-notional NOT # Maximum gross notional (default: 5000000)
Market maker parameters
--mm-gamma GAMMA # Risk aversion parameter (default: 0.1)
--mm-k K # Order book intensity (default: 1.5)
--mm-horizon-seconds HORIZON # Quote horizon (default: 60.0)
--mm-max-inventory INVENTORY # Maximum inventory (default: 1000)
--mm-base-order-size SIZE # Base order size (default: 100)
--mm-min-spread SPREAD # Minimum spread (default: 0.01)
--mm-num-levels LEVELS # Number of quote levels (default: 2)
--mm-level-spacing-bps SPACING # Level spacing in bps (default: 2.0)
--mm-size-decay DECAY # Size decay factor (default: 0.7)
--mm-momentum-window WINDOW # Momentum window (default: 10)
--mm-alpha-skew SKEW # Momentum skew weight (default: 0.5)
--mm-vol-widen-z Z # Volatility widening threshold (default: 2.0)
--mm-drawdown-limit LIMIT # Drawdown limit (default: 0.2)
Trader parameters
--momentum-lookback LOOKBACK # Momentum lookback (default: 5)
--ema-short-window SHORT # EMA short window (default: 5)
--ema-long-window LONG # EMA long window (default: 20)
--swing-support SUPPORT # Swing support level (default: 100.0)
--swing-resistance RESISTANCE # Swing resistance level (default: 200.0)
Output and logging
--log-dir LOG_DIR # Log directory (default: .logs)
--export-report # Export HTML performance report
--report-out REPORT_OUT # Report output path (default: report.html)
Advanced features
--enable-traders # Enable algorithmic traders
--inject-liquidity SECONDS # Inject synthetic liquidity every N seconds
--seed SEED # Random seed for reproducibility
--optuna-trials TRIALS # Number of Optuna optimization trials
--mlflow-uri URI # MLflow tracking URI
--mlflow-experiment EXPERIMENT # MLflow experiment name
Configuration Files
# config.yaml
trading:
default_symbol: "AAPL"
initial_cash: 1000000
fee_bps: 1.0
makerrebatebps: 0.5
risk_management: maxorderqty: 1000 maxsymbolposition: 10000 maxgrossnotional: 5000000 orderratelimitpersec: 10 ownerdrawdownlimit: 0.2 max_leverage: 3.0 volatilityhaltz: 3.0
market_maker: gamma: 0.1 k: 1.5 horizon_seconds: 60.0 max_inventory: 1000 baseordersize: 100 min_spread: 0.01 num_levels: 2 levelspacingbps: 2.0 size_decay: 0.7 momentum_window: 10 alpha_skew: 0.5 volwidenz: 2.0 drawdown_limit: 0.2
traders: momentum: lookback: 5 interval: 0.1 ema: short_window: 5 long_window: 20 interval: 0.1 swing: support_level: 100.0 resistance_level: 200.0 interval: 0.1
backtesting: slippagebpsper_100: 0.5 latency_ms: 10 export_report: true reportout: "performancereport.html"
data: cache_dir: ".cache" yahoofinancetimeout: 30 max_retries: 5 base_backoff: 1.5
logging: level: "INFO" format: "%(asctime)s - %(levelname)s - %(message)s" log_dir: ".logs"
๐ Performance Analytics
Periodic Metrics During Runs
The system prints rolling metrics during Replay and at the end of Backtest/Live runs:- Net Liq, Cash, Realized PnL
- Sharpe (ann), Sortino (ann), Volatility (ann)
- Current and Maximum Drawdown, CAGR
- Trades, Buys, Sells, Total Notional, Avg Trade Qty
- Average Slippage vs Mid (bps), Adverse Selection Rate
equitycurve.csv, executions.csv, tca.csv, and tcaadv.csv in your chosen log directory.
๐ฅ๏ธ Live Order Control (Split Terminal)
Place, cancel, or modify orders while a Live run is executingโwithout FIX. This lightweight order shell uses JSON-over-TCP and integrates with the same risk/matching/TCA pipeline.
Enable
- Interactive CLI: answer โEnable local order-control server for live mode?โ โ Yes
- Flags: add
--order-cli-enable --order-cli-host 127.0.0.1 --order-cli-port 8765 --order-cli-owner cli
Order CLI enabled: send JSON to 127.0.0.1:8765 (actions: new/cancel/modify)
Protocol
- One JSON per connection; server responds with JSON
{ "ok": true/false, ... } - Actions:
{
"action": "new",
"symbol": "AAPL",
"side": "buy",
"type": "limit",
"price": 150.25,
"quantity": 100,
"tif": "GTC",
"owner_id": "cli"
}
- Cancel:
{ "action": "cancel", "order_id": "<returned id>" }
- Modify (in-book):
{ "action": "modify", "order_id": "<id>", "price": 150.4, "quantity": 50 }
Notes:
owner_idroutes PnL/risk to that portfolio owner (default from--order-cli-owner).- Orders pass the same risk checks; executions hit TCA and CSV logs.
- Works offline: the live feed auto-simulates if data fetching fails.
Usage Examples
Windows PowerShell
$host = "127.0.0.1"; $port = 8765 python -c "import socket,json,sys; h=sys.argv[1]; p=int(sys.argv[2]); o={'action':'new','symbol':'AAPL','side':'buy','type':'limit','price':150.25,'quantity':100,'tif':'GTC','owner_id':'cli'}; s=socket.socket(); s.connect((h,p)); s.sendall(json.dumps(o).encode()); print(s.recv(4096).decode()); s.close()" $host $port
Cancel (replace with returned order_id):
$host = "127.0.0.1"; $port = 8765 python -c "import socket,json,sys; h=sys.argv[1]; p=int(sys.argv[2]); o={'action':'cancel','orderid':'REPLACEWITHORDERID'}; s=socket.socket(); s.connect((h,p)); s.sendall(json.dumps(o).encode()); print(s.recv(4096).decode()); s.close()" $host $port
Modify:
$host = "127.0.0.1"; $port = 8765 python -c "import socket,json,sys; h=sys.argv[1]; p=int(sys.argv[2]); o={'action':'modify','orderid':'REPLACEWITHORDERID','price':150.4,'quantity':50}; s=socket.socket(); s.connect((h,p)); s.sendall(json.dumps(o).encode()); print(s.recv(4096).decode()); s.close()" $host $port
bash/zsh
host=127.0.0.1; port=8765 python - << 'PY' import socket, json, os host = os.environ.get('HOST','127.0.0.1'); port = int(os.environ.get('PORT','8765')) o = {"action":"new","symbol":"AAPL","side":"buy","type":"limit","price":150.25,"quantity":100,"tif":"GTC","owner_id":"cli"} s = socket.socket(); s.connect((host,port)); s.sendall(json.dumps(o).encode()); print(s.recv(4096).decode()); s.close() PY
Performance Metrics
from tradingsimulator import computeperformancemetrics, exporthtml_report
Load equity curve
equitydf = pd.readcsv(".logs/equity_curve.csv")
Compute metrics
metrics = computeperformancemetrics(equity_df)
print(f"Initial Value: ${metrics['initial']:,.2f}") print(f"Final Value: ${metrics['final']:,.2f}") print(f"CAGR: {metrics['cagr']:.2%}") print(f"Sharpe Ratio: {metrics['sharpe']:.2f}") print(f"Sortino Ratio: {metrics['sortino']:.2f}") print(f"Max Drawdown: {metrics['max_drawdown']:.2%}")
Export HTML report
exporthtmlreport(equitydf, metrics, "performancereport.html")
Trade Cost Analysis
from trading_simulator import CsvLogger
Analyze TCA data
tcadf = pd.readcsv(".logs/tca.csv")
Calculate average slippage
avgslippagemid = tcadf['slippagemid_bps'].mean()
avgslippagelast = tcadf['slippagelast_bps'].mean()
print(f"Average Mid Slippage: {avgslippagemid:.2f} bps") print(f"Average Last Trade Slippage: {avgslippagelast:.2f} bps")
Analyze adverse selection
advdf = pd.readcsv(".logs/tca_adv.csv")
adverserate = advdf['adverse'].mean()
print(f"Adverse Selection Rate: {adverse_rate:.2%}")
Portfolio Analysis
from tradingsimulator import Portfolio, markto_market
Get portfolio snapshot
snapshot = portfolio.snapshot()
print(f"Cash: ${snapshot['cash']:,.2f}") print(f"Realized PnL: ${snapshot['realized_pnl']:,.2f}") print(f"Positions: {snapshot['positions']}")
Mark to market
last_prices = {'AAPL': 150.0, 'MSFT': 300.0}
netliq = marktomarket(portfolio, lastprices) + portfolio.realized_pnl
print(f"Net Liquidation Value: ${net_liq:,.2f}")
๐ค Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Development Setup
# Clone repository
git clone https://github.com/yourusername/Automated-Financial-Market-Trading-System.git
cd Automated-Financial-Market-Trading-System
Create development environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
Install development dependencies
pip install -r requirements-dev.txt
Install pre-commit hooks
pre-commit install
Run tests
pytest tests/
Run linting
flake8 trading_simulator/
black trading_simulator/
isort trading_simulator/
Code Style
- Python: Follow PEP 8 with 88-character line length
- Type Hints: Use type hints for all function parameters and return values
- Docstrings: Use Google-style docstrings for all public functions
- Tests: Maintain 90%+ test coverage
- Documentation: Update documentation for all new features
Pull Request Process
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Update documentation
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
This project is licensed under the MIT License ยฉ 2025 Devansh Garg - see the LICENSE file for details.
๐ Acknowledgments
- Yahoo Finance for market data
- NewsAPI for sentiment analysis data
- TensorFlow for machine learning capabilities
- Optuna for hyperparameter optimization
- MLflow for experiment tracking
- PostgreSQL for data persistence
- Redis for caching and event streaming
- Apache Kafka for real-time event processing
๐ Support
- Issues: GitHub Issues