Skip to main content

Simplified Investment & Trading Toolkit with Python & C++

Project description

Simplified Investment & Trading Toolkit with Python & C++

Build Documentation Status PyPi status Linux macOS Windows PYPI Version Supported Python Versions vcpkg version C++20 CMake PyPI Downloads CodeFactor LinkedIn

Welcome to bbstrader – The Ultimate C++ & Python Trading Powerhouse!

Table of Contents

Overview

Imagine having the raw, blistering speed of C++ for your high-frequency trades, combined with Python's ecosystem for lightning-fast prototyping, advanced AI models, and seamless data analysis. That's bbstrader – not just a library, but a game-changing toolkit designed for quants, algo traders, and institutional pros who demand an edge in volatile markets. Whether you're scalping forex pairs, backtesting complex strategies, or copying trades across accounts in real-time, bbstrader empowers you to build, test, and deploy with unmatched efficiency.

Forget the frustrations of slow Python bottlenecks or MQL5's rigid sandbox. bbstrader bridges worlds: C++ for mission-critical performance and Python for intelligent orchestration. It's open-source, battle-tested across platforms, and ready to supercharge your trading arsenal.

Why bbstrader Stands Out

In a crowded field of trading libraries, bbstrader is architected to solve the most challenging problems in algorithmic trading: performance, flexibility, and platform limitations.

  • Blazing Speed with C++ Core: Compile your strategy logic in native C++ for deterministic, low-latency execution. Perfect for HFT, arbitrage, or compute-heavy models that Python alone can't handle.
  • Python's Powerhouse Ecosystem: Leverage NumPy, pandas, scikit-learn, TensorFlow, and more for research, ML-driven signals, and backtesting – all seamlessly integrated with your C++ core.
  • Institutional-Grade Architecture: From its event-driven backtester to its modular design, bbstrader is built with the principles of professional trading systems in mind, providing a robust foundation for serious strategy development. In today's hyper-fast financial landscape, every microsecond counts. bbstrader isn't another lightweight wrapper – it's an institutional-grade powerhouse engineered to tackle real-world trading challenges head-on.
  • Break Free from MQL5 Limits: Ditch interpreted code and ecosystem constraints. Build multi-threaded, AI-infused strategies that execute orders in microseconds via MetaTrader 5 (MT5) integration. Flexible Interface: CLI & GUI bbstrader adapts to your workflow.
    • Automation Fanatics: Use the CLI for headless scripts, cron jobs, and server deployments.
    • Visual Traders: Launch the Desktop GUI (currently for Copy Trading) to monitor your master and slave accounts, check replication status, and manage connections visually.
    • Cross-Platform & Future-Proof: Works on Windows, macOS, Linux. (IBKR integration in development).

Trusted by Traders Worldwide

With thousands of downloads, bbstrader is trusted by traders worldwide. It's not just code – it's your ticket to profitable, scalable strategies.

The bbstrader Edge: Uniting C++ Speed with Python Flexibility

bbstrader's hybrid design is its secret weapon. At the heart is a bidirectional C++/Python bridge via client module:

  1. C++ for Speed: Core classes like MetaTraderClient handle high-performance tasks. Inject Python handlers for MT5 interactions, enabling native-speed signal generation and risk checks.
  2. Python for Smarts: Orchestrate everything with modules like trading and btengine.
  3. The Data Flow: The result is a clean, efficient, and powerful execution loop: Python (Orchestration & Analysis) -> C++ (High-Speed Signal Generation) -> Python (MT5 Communication) -> C++ (Receives Market Data)

This setup crushes performance ceilings: Run ML models in Python, execute trades in C++, and backtest millions of bars in minutes.

Overcoming the MQL5 Bottleneck

MetaTrader 5 is a world-class trading platform, but its native MQL5 language presents significant limitations for complex, high-frequency strategies:

  • Performance Ceilings: As an interpreted language, MQL5 struggles with the computationally intensive logic required for advanced statistical models, machine learning, and rapid-fire order execution.
  • Ecosystem Constraints: MQL5 lacks access to the vast, mature ecosystems of libraries for numerical computation, data science, and AI that C++ and Python offer.
  • Architectural Rigidity: Implementing sophisticated, multi-threaded, or event-driven architectures in MQL5 is often a complex and error-prone endeavor.

bbstrader eradicates these barriers. By moving your core strategy logic to C++, you can unlock the full potential of your trading ideas, executing them with the microsecond-level precision demanded by institutional trading.

Key Modules

bbstrader is modular, with each component laser-focused.

1. btengine: Event-Driven Backtesting Beast

  • Purpose: Simulate strategies with historical data, including slippage, commissions, and multi-asset portfolios. Optimizes parameters and computes metrics like Sharpe Ratio, Drawdown, and CAGR.
  • Features: Event queue for ticks/orders, vectorized operations for speed, integration with models for signal generation.
  • Example: Backtest a StockIndexSTBOTrading from the example strategies.
# Inside the examples/
from strategies import test_strategy
if __name__ == '__main__':
    # Run backtesting for Stock Index Short Term Buy Only Strategy
    test_strategy(strategy='sistbo')

Backtesting Results

Backtesting Results1 Backtesting Results2

2. metatrader: The C++/Python Bridge to MT5

  • Purpose: High-speed MT5 integration. C++ MetaTraderClient mirrors MT5 API for orders, rates, and account management.
  • Features: Bidirectional callbacks, error handling, real-time tick processing.
  • Strategy Patterns: Two main patterns to build strategies:

Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)

This is the recommended pattern for latency-sensitive strategies, such as statistical arbitrage, market making, or any strategy where execution speed is a critical component of your edge. By compiling your core logic, you minimize interpretation overhead and gain direct control over memory and execution.

Use this pattern when:

  • Your strategy involves complex mathematical calculations that are slow in Python.
  • You need to react to market data in the shortest possible time.
  • Your production environment demands deterministic, low-latency performance.

C++ Side (MovingAverageStrategy.cpp):

#include "bbstrader/metatrader.hpp"
#include <numeric>
#include <iostream>

class MovingAverageStrategy : public MT5::MetaTraderClient {
public:
    using MetaTraderClient::MetaTraderClient;

    void on_tick(const std::string& symbol) {
        auto rates_opt = copy_rates_from_pos(symbol, 1, 0, 20);

        if (!rates_opt || rates_opt->size() < 20) return;

        const auto& rates = *rates_opt;

        double sum = std::accumulate(rates.begin(), rates.end(), 0.0,
                                     [](double a, const MT5::RateInfo& b) { return a + b.close; });
        double sma = sum / rates.size();
        double current_price = rates.back().close;

        if (current_price > sma) {
            std::cout << "Price is above SMA. Sending Buy Order for " << symbol << '\n';
            MT5::TradeRequest request;
            request.action = MT5::TradeAction::DEAL;
            request.symbol = symbol;
            request.volume = 0.1;
            request.type = MT5::OrderType::BUY;
            request.type_filling = MT5::OrderFilling::FOK;
            request.type_time = MT5::OrderTime::GTC;
            send_order(request);
        }
    }
};

This C++ class would then be exposed to Python using pybind11.

// Inside bindings.cpp
#include <pybind11/pybind11.h>
#include "MovingAverageStrategy.hpp"

namespace py = pybind11;

PYBIND11_MODULE(my_strategies, m){
py::class_<MovingAverageStrategy, MT5::MetaTraderClient>(m, "MovingAverageStrategy")
    .def(py::init<MT5::MetaTraderClient::Handlers>())
    .def("on_tick", &MovingAverageStrategy::on_tick);
}

Python Side (main.py):

from bbstrader.api import Mt5Handlers
import MetaTrader5 as mt5
import time
from my_strategies import MovingAverageStrategy

# 1. Instantiate the C++ strategy, injecting the Python MT5 handlers
strategy = MovingAverageStrategy(Mt5Handlers)

# 2. Main execution loop
if strategy.initialize():
    while True:
        strategy.on_tick("EURUSD")
        time.sleep(1)

Pattern 2: Python-Driven with C++ Acceleration

This pattern is ideal for strategies that benefit from Python's rich ecosystem for data analysis, machine learning, or complex event orchestration, but still require high-performance access to market data and the trading API.

Use this pattern when:

  • Your strategy relies heavily on Python libraries like pandas, scikit-learn, or tensorflow.
  • Rapid prototyping and iteration are more important than absolute minimum latency.
  • Your core logic is more about decision-making based on pre-processed data than it is about raw computation speed.
import MetaTrader5 as mt5
from bbstrader.api import Mt5Handlers
from bbstrader.api.client import MetaTraderClient

# 1. Inherit from the C++ MetaTraderClient in Python
class MyStrategyClient(MetaTraderClient):
    def __init__(self, handlers):
        super().__init__(handlers)

# 2. Instantiate your client
strategy = MyStrategyClient(Mt5Handlers)

# 3. Interact with the MT5 terminal via the C++ bridge
if strategy.initialize():
    rates = strategy.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_M1, 0, 100)
    print(f"Retrieved {len(rates)} rates via the C++ bridge.")

3. trading: Live Execution & Strategy Orchestrator

  • Purpose: Manages live sessions, coordinates signals from strategies, risk from models, and execution via metatrader.
  • Features: Multi-account support, position hedging, trailing stops.

4. models: Quant Toolkit for Signals & Risk

  • Purpose: Build/test models like NLP sentiment, VaR/CVaR risk, optimization.
  • Features: Currently Sentiment analysis, and Topic Modeling.
  • Example: Sentiment-Based Entry:
from bbstrader.models import SentimenSentimentAnalyzer

model = SentimenSentimentAnalyzer()  # Loads pre-trained NLP
score = model.analyze_sentiment("Fed hikes rates – markets soar!")
if score > 0.7:  # Bullish? Buy!
    print("Go long!")

Other Modules:

core: Utilities (data structs, logging). config: Manages JSON configs in ~/.bbstrader/. api: Handler injections for bridges.

Getting Started

Prerequisites

  • Python: Python 3.12+ is required.
  • MetaTrader 5 (MT5): Required for live execution (Windows).
  • MT5 Broker: Admirals, JustMarkets, FTMO.

Installation

bbstrader is designed for both Python and C++ developers. Follow the instructions that best suit your needs.

For the Python Quant

Get started in minutes using pip. We strongly recommend using a virtual environment.

# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate  # on Linux/macOS
venv\Scripts\activate     # on Windows

# Install bbstrader
pip install bbstrader[MT5] # Windows
pip install bbstrader  # Linux/macOS

For the C++ Developer

To develop your own C++ strategies, you can use vcpkg to install the bbstrader library and its dependencies.

# If you don't have vcpkg, clone and bootstrap it
git clone https://github.com/microsoft/vcpkg
./vcpkg/bootstrap-vcpkg.sh or ./vcpkg/bootstrap-vcpkg.bat

# Install bbstrader
./vcpkg/vcpkg install bbstrader

CLI workflow

bbstrader shines via CLI – launch everything from one command!

Action Command
Run Backtest python -m bbstrader --run backtest --strategy SMAStrategy --account MY_ACCOUNT --config backtest.json
Live Execution python -m bbstrader --run execution --strategy KalmanFilter --account MY_ACCOUNT --config execution.json --parallel
Copy Trades python -m bbstrader --run copier --source "S1" --destination "D1"
Get Help python -m bbstrader --help

Config Example (~/.bbstrader/execution/execution.json):

{
  "SMAStrategy": {
    "MY_MT5_ACCOUNT_1": {
      "symbol_list": ["EURUSD", "GBPUSD"],
      "trades_kwargs": { "magic": 12345, "comment": "SMA_Live" },
      "short_window": 20,
      "long_window": 50
    }
  }
}

🌍 Community & Support


Professional Services

If you need a custom trading strategy, a proprietary risk model, advanced data pipelines, or a dedicated copy trading server setup, professional services are available.

Contact the Developer:
📧 bertin@bbs-trading.com


Support the Project

If you find this project useful and would like to support its continued development, you can contribute here:

Support the Developer


Disclaimer: Trading involves significant risk. bbstrader provides the tools, but you provide the strategy. Test thoroughly on demo accounts before deploying real capital.

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

bbstrader-2.0.8.tar.gz (1.1 MB view details)

Uploaded Source

Built Distributions

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

bbstrader-2.0.8-cp312-cp312-win_amd64.whl (1.1 MB view details)

Uploaded CPython 3.12Windows x86-64

bbstrader-2.0.8-cp312-cp312-musllinux_1_2_x86_64.whl (2.1 MB view details)

Uploaded CPython 3.12musllinux: musl 1.2+ x86-64

bbstrader-2.0.8-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (1.2 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

bbstrader-2.0.8-cp312-cp312-macosx_11_0_arm64.whl (1.1 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

File details

Details for the file bbstrader-2.0.8.tar.gz.

File metadata

  • Download URL: bbstrader-2.0.8.tar.gz
  • Upload date:
  • Size: 1.1 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for bbstrader-2.0.8.tar.gz
Algorithm Hash digest
SHA256 aa3b411acab8879152020521cf371bf6db161e8116593608bd5ce1c78c333f3c
MD5 1a464a5fa7ca5a0baa5290a689dcee79
BLAKE2b-256 89ebb811f29bff24c7192fdb7c46088dfecd4232ce3c21868ffe603b80a413d0

See more details on using hashes here.

File details

Details for the file bbstrader-2.0.8-cp312-cp312-win_amd64.whl.

File metadata

  • Download URL: bbstrader-2.0.8-cp312-cp312-win_amd64.whl
  • Upload date:
  • Size: 1.1 MB
  • Tags: CPython 3.12, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for bbstrader-2.0.8-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 04b504c9480c6cb56a8bd1129184959796eb5252b291b084b0e421c415172e58
MD5 9b74dd966ff4e9d108915af30fd68ebe
BLAKE2b-256 d51cec3383d1de9719113f40d6b25eeab2186b142748295921417185acf07df3

See more details on using hashes here.

File details

Details for the file bbstrader-2.0.8-cp312-cp312-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for bbstrader-2.0.8-cp312-cp312-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 77f0e8330641386c2f96ffc534c47185fa4cc87eb9ce37a089d121aff7579927
MD5 9f8dae9b6ed4cafd4f9770a4ce8e75ec
BLAKE2b-256 882cc6e00c7a702d6222dea8c1389639b1952130957e7d1215350f79a72cb23f

See more details on using hashes here.

File details

Details for the file bbstrader-2.0.8-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for bbstrader-2.0.8-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 003d4ca861222a2d2db3453a138893a1ec9b8d2f8932c6bc7a5ded890cf28d3f
MD5 f71629bc1396354b68f985eee3d4a9be
BLAKE2b-256 b3d0c00733ba13204b853989acc5eaeff2e355d98d75a9a7131683b4104909e6

See more details on using hashes here.

File details

Details for the file bbstrader-2.0.8-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for bbstrader-2.0.8-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 11661ac297214ec24c18b1012f52c23b71e7f61535322da7cc057c2c3f905900
MD5 e7eff7e786cfe3a11c7acdcbe3f01eae
BLAKE2b-256 a1ebdab7097db3effa6addb615809fc504350fe54bd03ceb647e908ec8dabb15

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