Skip to content

marcosuma/trading-bot

Repository files navigation

Trading Bot

A comprehensive Python framework for quantitative research, backtesting, and live trading. Supports multiple brokers (IBKR, OANDA), real-time data collection, technical analysis, machine learning predictions, and automated strategy execution.

Table of Contents

Features

Core Capabilities

  • Data Management: Download and cache historical OHLCV data from IBKR
  • Technical Indicators: RSI, MACD, EMA/SMA, ATR, ADX, Bollinger Bands, Local Extrema
  • Pattern Detection: Chart patterns (Head & Shoulders, Triangles, etc.) and candlestick patterns
  • Strategy Backtesting: Comprehensive backtesting framework with multiple strategies
  • Machine Learning: ML predictors for price direction, volatility, trend, and extrema
  • Live Trading: Real-time trading system with multi-timeframe support
  • Visualization: Interactive charts with Matplotlib and Plotly

Trading Strategies

  • Momentum Strategies: Trend following with MACD, EMA crossovers
  • Mean Reversion: RSI, Bollinger Bands mean reversion
  • Breakout Strategies: Support/Resistance and ATR-based breakouts
  • Multi-Timeframe: Higher timeframe trend confirmation
  • Pattern-Based: Chart pattern and triangle detection strategies
  • Adaptive: Multi-indicator adaptive strategies

See Strategy Documentation for details.

Brokers

  • IBKR: Market data and order execution (paper and live)
  • OANDA: Order execution (paper and live)

See Broker Configuration for setup instructions.

Quick Start

Prerequisites

  • Python 3.10+
  • IBKR TWS/Gateway (for IBKR data/trading)
  • MongoDB (for live trading system)
  • Node.js 18+ (for frontend, optional)

Installation

  1. Clone the repository:
git clone <repository-url>
cd trading-bot
  1. Create virtual environment:
python3 -m venv .venv-cli
source .venv-cli/bin/activate  # On Windows: .venv\Scripts\activate
  1. Install system dependencies (macOS):
brew install ta-lib libomp
  1. Install Python dependencies:
pip install --upgrade pip setuptools
pip install -r requirements.txt
pip install -e ./IBJts/source/pythonclient  # IBKR API
  1. Configure environment: Create a .env file in the project root:
# Optional: For OANDA trading
OANDA_ACCESS_TOKEN=your_token
OANDA_ACCOUNT_ID=your_account_id

# Optional: For live trading system
MONGODB_URL=mongodb://localhost:27017
MONGODB_DB_NAME=trading_bot
  1. Start IBKR TWS/Gateway:
  • Enable API: Configure → Global Configuration → API → Settings
  • Socket port: 7497 (paper) or 7496 (live)
  • Add 127.0.0.1 to Trusted IPs

Basic Usage

Interactive Mode (recommended):

python cli.py

Then in the shell:

trading-bot> help
trading-bot> download-and-process
trading-bot> test-forex-strategies --asset USD-CAD
trading-bot> exit

Single Command Mode:

# Download and process data
python cli.py download-and-process

# Test strategies
python cli.py test-forex-strategies --asset USD-CAD --bar-size "1 hour"

# Train ML models
python cli.py train-extrema-predictor --asset USD-CAD

Architecture

The system consists of two main components:

1. Backtesting & Research System

  • CLI Interface: Interactive shell for data management, strategy testing, and ML training
  • Data Pipeline: IBKR → CSV cache → Technical Indicators → Strategies → Backtesting
  • Strategy Framework: Extensible strategy base classes with backtesting integration
  • ML Pipeline: Feature engineering, model training, and prediction

See Architecture Documentation for details.

2. Live Trading System

  • Trading Engine: Orchestrates real-time trading operations
  • Data Manager: Real-time data collection and bar aggregation
  • Order Manager: Order placement, position tracking, risk management
  • REST API: FastAPI-based API for operation management
  • React Frontend: Web interface for monitoring and control

See Live Trading Documentation for details.

Documentation

Comprehensive documentation is available in the docs/ directory:

Getting Started

Core Concepts

Live Trading

Advanced Topics

Reference

Installation

See Installation Guide for detailed instructions.

System Dependencies

macOS:

brew install ta-lib libomp

Linux:

sudo apt-get install ta-lib libomp-dev  # Ubuntu/Debian

Windows: Download TA-Lib from https://ta-lib.org/install/

Usage

Data Management

Download and process historical data:

python cli.py download-and-process
python cli.py download-and-process --include-1min --force-refresh

Strategy Testing

Test all strategies on all assets:

python cli.py test-forex-strategies

Test specific strategies on specific assets:

python cli.py test-forex-strategies --asset USD-CAD --bar-size "1 hour" --strategies "MomentumStrategy,RSIStrategy"

Machine Learning

Train extrema predictor:

python cli.py train-extrema-predictor --asset USD-CAD --lookback-bars 20

Train other predictors:

python cli.py train-price-direction-predictor --asset USD-CAD
python cli.py train-volatility-predictor --asset USD-CAD
python cli.py train-trend-predictor --asset USD-CAD

Live Trading

Start in interactive mode (foreground):

python -m live_trading.main

Start as a background daemon (recommended for production):

python -m live_trading.cli start    # Start daemon
python -m live_trading.cli status   # Check status
python -m live_trading.cli logs -f  # Follow logs (like tail -f)
python -m live_trading.cli stop     # Stop daemon

Access the system:

  • API: http://localhost:8000
  • Frontend: http://localhost:3000 (if running separately)
  • Logs Viewer: http://localhost:3000/logs (frontend)

See Live Trading Documentation for details.

Project Structure

trading-bot/
├── cli.py                      # Main CLI entry point
├── config.py                   # Global configuration
├── contracts.json              # Instrument definitions
├── requirements.txt            # Python dependencies
├── docs/                       # Documentation
├── data/                       # Cached historical data (CSV)
├── forex_strategies/          # Trading strategies
├── technical_indicators/      # Technical indicator implementations
├── machine_learning/         # ML models and predictors
├── patterns/                  # Chart pattern detection
├── triangles/                 # Triangle pattern detection
├── live_trading/              # Live trading system
│   ├── api/                   # FastAPI REST API
│   ├── brokers/              # Broker adapters (IBKR, OANDA, cTrader)
│   ├── daemon/               # Background process management
│   ├── data/                 # Data collection and aggregation
│   ├── engine/               # Trading engine
│   ├── logging/              # Modular logging system
│   ├── models/                # MongoDB models
│   ├── orders/               # Order management
│   ├── strategies/           # Strategy adapters
│   ├── cli.py                # Daemon control CLI
│   └── frontend/             # React frontend
├── ib_api_client/            # IBKR API client wrapper
├── request_historical_data/  # Historical data requests
└── data_manager/             # Data download and processing

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

See LICENSE file for details.

Disclaimer

This project is for educational and research purposes. Trading involves significant risk. Use at your own risk and verify behavior on paper trading/sandbox environments before any live deployment.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published