Skip to main content

Quant trading engine toolkit

Project description

XQTrader

Python 3.12+ License: MIT

中文文档

A quantitative trading engine toolkit for strategy development, backtesting, paper trading, and live trading.


Features

  • Strategy Framework: Modular strategy system with hot-reload support
  • Multi-Exchange Support: 100+ exchanges via CCXT
  • Technical Indicators: 60+ indicators powered by talipp
  • Futures Trading: Perpetual futures with hedge mode
  • Event Contracts: Binary options style trading
  • Risk Management: Multi-level risk control (WARNING/CRITICAL)
  • Smart Caching: LRU + TTL caching with circuit breaker

Installation

Requirements

  • Python >= 3.12
  • uv (recommended) or pip

Use as a dependency

Add XQTrader to your project with uv:

uv add "xqtrader @ git+https://github.com/Aixtrade/QuantTrader.git@main"

Or pin to a specific version tag:

uv add "xqtrader @ git+https://github.com/Aixtrade/QuantTrader.git@v0.1.0"

Or with pip:

pip install "xqtrader @ git+https://github.com/Aixtrade/QuantTrader.git@main"

Development install

git clone https://github.com/Aixtrade/QuantTrader.git
cd XQTrader

# Install dependencies with uv
uv sync --dev

# Or with pip
pip install -e ".[dev]"

Quick Start

1. Create a Strategy

from xqtrader.strategies.base import (
    BaseStrategy,
    StrategyContext,
    StrategyResult,
)

class MyStrategy(BaseStrategy):
    def __init__(self):
        super().__init__(name="my_strategy", version="1.0.0")

    def execute(self, context: StrategyContext) -> StrategyResult:
        close_prices = context.market_data.get("close", [])
        if not close_prices:
            return StrategyResult(
                signals=[self.create_signal("HOLD", context.symbol)],
                indicators={},
                metadata={},
                execution_time=0.0,
                success=True,
            )

        # Your trading logic here
        signal = self.create_signal("LONG", context.symbol, confidence=0.8)
        return StrategyResult(
            signals=[signal],
            indicators={},
            metadata={},
            execution_time=0.0,
            success=True,
        )

2. Run Backtest

import asyncio
from datetime import datetime, timedelta, timezone
from xqtrader.engine.backtest import BacktestConfig, BacktestEngine

async def main():
    strategy = MyStrategy()
    engine = BacktestEngine()

    now = datetime.now(timezone.utc)
    config = BacktestConfig(
        symbol="BTC/USDT",
        interval="1h",
        initial_capital=10000.0,
        start_time=int((now - timedelta(days=7)).timestamp() * 1000),
        end_time=int(now.timestamp() * 1000),
    )

    async for event in engine.run(strategy, config):
        if event.event_type == "trade":
            print(f"Trade: {event.data}")
        elif event.event_type == "complete":
            print(f"Final balance: {event.data.get('final_balance')}")

asyncio.run(main())

Signal Conventions

Contract Type Signals
Perpetual/Futures LONG, SHORT, CLOSE_LONG, CLOSE_SHORT, CLOSE
Event Contracts UP, DOWN, HOLD

Event trader also accepts LONG/SHORT/BUY/SELL and auto-maps to UP/DOWN.


Architecture

xqtrader/
├── strategies/     # Strategy system - BaseStrategy and dynamic loader
├── engine/         # Execution engines - BacktestEngine / RealtimeEngine
├── accounts/       # Account management - SimulatedAccount / FuturesSimulatedAccount
├── traders/        # Trade executors - EventsTrader / FuturesTrader
├── data/           # Data services - DataCenterService + CCXT adapters
│   └── adapters/   # Exchange adapters - CCXTAdapter / BinanceAdapter
├── indicators/     # Technical indicators - 60+ indicators via talipp
├── risk/           # Risk management - RiskManager (WARNING/CRITICAL levels)
├── reports/        # Report generation - BacktestReport / TradeRecord
└── config/         # Configuration management

Data Flow

Market Data (OHLCV) → Indicator Engine → Strategy Context → Strategy Execution
     ↓                                                            ↓
DataCenterService                                          StrategyResult
                                                                  ↓
Account Update ← Trade Execution ← Risk Check ← Trading Signals
     ↓
BacktestReport

Examples

See the examples/ directory for complete examples:

  • MACD Strategy: examples/macd_strategy/
    • macd_strategy.py - Strategy implementation
    • run_backtest_futures.py - Futures backtest
    • run_backtest_events.py - Event contracts backtest

Development

# Run all tests
uv run pytest

# Run specific test file
uv run pytest tests/test_data_center.py -v

# Run specific test class
uv run pytest tests/test_data_center.py::TestLRUCache -v

# Run examples
uv run python examples/macd_strategy/run_backtest_futures.py

Risk Rules

Rule Warning Critical
Daily Loss 3.5% 5%
Max Drawdown 10% 15%

Roadmap

  • MVP v0: Single-asset backtesting
  • MVP v1: Real-time paper trading
  • MVP v2: Funding rate optimization
  • MVP v3: Multi-asset portfolio
  • MVP v4: Live trading interface

See docs/trading_system_roadmap.md for details.


Dependencies

Package Purpose
ccxt Exchange connectivity
talipp Technical indicators
numpy Numerical computing
pydantic Data validation
httpx Async HTTP client

License

MIT License - see LICENSE for details.


Contributing

Contributions are welcome! Please read the AGENTS.md for coding conventions.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xqtrader-0.1.0.tar.gz (173.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

xqtrader-0.1.0-py3-none-any.whl (54.7 kB view details)

Uploaded Python 3

File details

Details for the file xqtrader-0.1.0.tar.gz.

File metadata

  • Download URL: xqtrader-0.1.0.tar.gz
  • Upload date:
  • Size: 173.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.2

File hashes

Hashes for xqtrader-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6d1143846641a0d4b3d3e7d705ba6a399bd0c3cad81d6b1dde9b8e1383f08db1
MD5 c9355b3098c388665fd3206ed72e5718
BLAKE2b-256 0d14681a99fe31c8e4059f93e1018697547606355d6bbea59891b7a6cf2a402e

See more details on using hashes here.

File details

Details for the file xqtrader-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: xqtrader-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 54.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.2

File hashes

Hashes for xqtrader-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ead94b6466eff8afa46f5688ae7b0e244753f92879e965b34bbe2fef6b7b7744
MD5 dd8204183ec7836fb529cd734285abc2
BLAKE2b-256 30f2ac35ff8a227d6076eede9f13c02b291d0fbe53be3a984a59e939355f95b6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page