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.1.tar.gz (173.5 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.1-py3-none-any.whl (54.8 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for xqtrader-0.1.1.tar.gz
Algorithm Hash digest
SHA256 e0af520b9a341f804a44e8e3cb8c583d9577e4e71075760b5e0df938a053675b
MD5 a278103a84732a1d31cb3ad060bee5a1
BLAKE2b-256 a7bcaee06d0913b92f2e79d89bb55338ac587fda0219375ebcab8cf6f713958c

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for xqtrader-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 292106d2dcfc9f2b2f831ee210f61b55c940d406539e94b6c8f17312be51de7f
MD5 23ed3194d4c26a8cb2d195bab53ffb0f
BLAKE2b-256 6e7de49f71f729322b464498f0234a662a3c5b3bc5862fb3ab40ca8b49e01d37

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