{"id":40560787,"url":"https://github.com/bbalouki/bbstrader","last_synced_at":"2026-01-25T13:00:42.193Z","repository":{"id":226736916,"uuid":"769509535","full_name":"bbalouki/bbstrader","owner":"bbalouki","description":"Simplified Investment \u0026 Trading Toolkit with Python \u0026 C++","archived":false,"fork":false,"pushed_at":"2026-01-20T23:15:48.000Z","size":16507,"stargazers_count":9,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"main","last_synced_at":"2026-01-21T09:21:26.195Z","etag":null,"topics":["backtest","backtesting","backtesting-engine","backtesting-trading-strategies","fianance","investment","machine-learning","metatrader5","strategy","time-series","trading"],"latest_commit_sha":null,"homepage":"https://github.com/bbalouki/bbstrader","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bbalouki.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-03-09T09:28:51.000Z","updated_at":"2026-01-20T22:39:32.000Z","dependencies_parsed_at":"2024-08-06T03:27:50.526Z","dependency_job_id":"3a3c85a0-4146-4f08-9dff-3cab882bebe7","html_url":"https://github.com/bbalouki/bbstrader","commit_stats":null,"previous_names":["bbalouki/bbstrade"],"tags_count":24,"template":false,"template_full_name":null,"purl":"pkg:github/bbalouki/bbstrader","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbalouki%2Fbbstrader","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbalouki%2Fbbstrader/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbalouki%2Fbbstrader/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbalouki%2Fbbstrader/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bbalouki","download_url":"https://codeload.github.com/bbalouki/bbstrader/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bbalouki%2Fbbstrader/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28753411,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-25T10:25:12.305Z","status":"ssl_error","status_checked_at":"2026-01-25T10:25:11.933Z","response_time":113,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backtest","backtesting","backtesting-engine","backtesting-trading-strategies","fianance","investment","machine-learning","metatrader5","strategy","time-series","trading"],"created_at":"2026-01-21T01:00:22.892Z","updated_at":"2026-01-25T13:00:42.105Z","avatar_url":"https://github.com/bbalouki.png","language":"Python","funding_links":["https://paypal.me/bertinbalouki?country.x=SN\u0026locale.x=en_US"],"categories":[],"sub_categories":[],"readme":"# Simplified Investment \u0026 Trading Toolkit with Python \u0026 C++\n\n[![Documentation Status](https://readthedocs.org/projects/bbstrader/badge/?version=latest)](https://bbstrader.readthedocs.io/en/latest/?badge=latest)\n[![PYPI Version](https://img.shields.io/pypi/v/bbstrader)](https://pypi.org/project/bbstrader/)\n[![PyPi status](https://img.shields.io/pypi/status/bbstrader.svg?maxAge=60)](https://pypi.python.org/pypi/bbstrader)\n[![Supported Python Versions](https://img.shields.io/pypi/pyversions/bbstrader)](https://pypi.org/project/bbstrader/)\n[![Linux](https://github.com/bbalouki/bbstrader/actions/workflows/cpp_linux.yml/badge.svg)](https://github.com/bbalouki/bbstrader/actions/workflows/cpp_linux.yml)\n[![macOS](https://github.com/bbalouki/bbstrader/actions/workflows/cpp_macos.yml/badge.svg)](https://github.com/bbalouki/bbstrader/actions/workflows/cpp_macos.yml)\n[![Windows](https://github.com/bbalouki/bbstrader/actions/workflows/cpp_win.yml/badge.svg)](https://github.com/bbalouki/bbstrader/actions/workflows/cpp_win.yml)\n[![C++20](https://img.shields.io/badge/C++-20-blue.svg)](https://isocpp.org/std/the-standard)\n[![CMake](https://img.shields.io/badge/CMake-3.20+-blue.svg)](https://cmake.org/)\n[![PyPI Downloads](https://static.pepy.tech/badge/bbstrader)](https://pepy.tech/projects/bbstrader)\n[![CodeFactor](https://www.codefactor.io/repository/github/bbalouki/bbstrader/badge)](https://www.codefactor.io/repository/github/bbalouki/bbstrader)\n[![LinkedIn](https://img.shields.io/badge/LinkedIn-grey?logo=Linkedin\u0026logoColor=white)](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)\n\n## Welcome to `bbstrader` – The Ultimate C++ \u0026 Python Trading Powerhouse!\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Why `bbstrader` Stands Out](#why-bbstrader-stands-out)\n- [Trusted by Traders Worldwide](#trusted-by-traders-worldwide)\n- [The `bbstrader` Edge: Uniting C++ Speed with Python Flexibility](#the-bbstrader-edge-uniting-c-speed-with-python-flexibility)\n  - [Overcoming the MQL5 Bottleneck](#overcoming-the-mql5-bottleneck)\n- [Key Modules](#key-modules)\n  - [1. `btengine`: Event-Driven Backtesting Beast](#1-btengine-event-driven-backtesting-beast)\n  - [2. `metatrader`: The C++/Python Bridge to MT5](#2-metatrader-the-cpython-bridge-to-mt5)\n    - [Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)](#pattern-1-c-core-python-orchestrator-maximum-performance)\n    - [Pattern 2: Python-Driven with C++ Acceleration](#pattern-2-python-driven-with-c-acceleration)\n  - [3. `trading`: Live Execution \u0026 Strategy Orchestrator](#3-trading-live-execution--strategy-orchestrator)\n  - [4. `models`: Quant Toolkit for Signals \u0026 Risk](#4-models-quant-toolkit-for-signals--risk)\n- [Getting Started](#getting-started)\n  - [Prerequisites](#prerequisites)\n- [Installation](#installation)\n  - [For the Python Quant](#for-the-python-quant)\n  - [For the C++ Developer](#for-the-c-developer)\n- [CLI workflow](#cli-workflow)\n- [Community \u0026 Support](#-community--support)\n- [Professional Services](#professional-services)\n\n### Overview\n\nImagine 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.\n\nForget 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.\n\n## **Why `bbstrader` Stands Out**\n\nIn a crowded field of trading libraries, `bbstrader` is architected to solve the most challenging problems in algorithmic trading: performance, flexibility, and platform limitations.\n\n- **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.\n- **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.\n- **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.\n  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.\n- **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.\n  **Flexible Interface**: CLI \u0026 GUI\n  `bbstrader` adapts to your workflow.\n  - **Automation Fanatics**: Use the CLI for headless scripts, cron jobs, and server deployments.\n  - **Visual Traders**: Launch the Desktop GUI (currently for Copy Trading) to monitor your master and slave accounts, check replication status, and manage connections visually.\n  - **Cross-Platform \u0026 Future-Proof**: Works on Windows, macOS, Linux. (IBKR integration in development).\n\n## **Trusted by Traders Worldwide**\n\nWith thousands of downloads, `bbstrader` is trusted by traders worldwide. It's not just code – it's your ticket to profitable, scalable strategies.\n\n## **The `bbstrader` Edge: Uniting C++ Speed with Python Flexibility**\n\nbbstrader's hybrid design is its secret weapon. At the heart is a bidirectional C++/Python bridge via `metatrader_client` module:\n\n1. **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.\n2. **Python for Smarts**: Orchestrate everything with modules like `trading` and `btengine`.\n3. **The Data Flow:** The result is a clean, efficient, and powerful execution loop:\n   `Python (Orchestration \u0026 Analysis) -\u003e C++ (High-Speed Signal Generation) -\u003e Python (MT5 Communication) -\u003e C++ (Receives Market Data)`\n\nThis setup crushes performance ceilings: Run ML models in Python, execute trades in C++, and backtest millions of bars in minutes.\n\n### **Overcoming the MQL5 Bottleneck**\n\nMetaTrader 5 is a world-class trading platform, but its native MQL5 language presents significant limitations for complex, high-frequency strategies:\n\n- **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.\n- **Ecosystem Constraints:** MQL5 lacks access to the vast, mature ecosystems of libraries for numerical computation, data science, and AI that C++ and Python offer.\n- **Architectural Rigidity:** Implementing sophisticated, multi-threaded, or event-driven architectures in MQL5 is often a complex and error-prone endeavor.\n\n`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.\n\n## **Key Modules**\n\nbbstrader is modular, with each component laser-focused.\n\n### 1. **btengine**: Event-Driven Backtesting Beast\n\n- **Purpose**: Simulate strategies with historical data, including slippage, commissions, and multi-asset portfolios. Optimizes parameters and computes metrics like Sharpe Ratio, Drawdown, and CAGR.\n- **Features**: Event queue for ticks/orders, vectorized operations for speed, integration with models for signal generation.\n- **Example**: Backtest a StockIndexSTBOTrading from the example strategies.\n\n```Python\n# Inside the examples/\nfrom strategies import test_strategy\nif __name__ == '__main__':\n    # Run backtesting for Stock Index Short Term Buy Only Strategy\n    test_strategy(strategy='sistbo')\n```\n\n### Backtesting Results\n\n![Backtesting Results1](https://github.com/bbalouki/bbstrader/blob/main/bbstrader/assets/bbs_.png?raw=true)\n![Backtesting Results2](https://github.com/bbalouki/bbstrader/blob/main/bbstrader/assets/qs_metrics_1.png?raw=true)\n\n### 2. **metatrader**: The C++/Python Bridge to MT5\n\n- **Purpose**: High-speed MT5 integration. C++ MetaTraderClient mirrors MT5 API for orders, rates, and account management.\n- **Features**: Bidirectional callbacks, error handling, real-time tick processing.\n- **Strategy Patterns**: Two main patterns to build strategies:\n\n#### Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)\n\nThis 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.\n\n**Use this pattern when:**\n\n- Your strategy involves complex mathematical calculations that are slow in Python.\n- You need to react to market data in the shortest possible time.\n- Your production environment demands deterministic, low-latency performance.\n\n**C++ Side (`MovingAverageStrategy.cpp`):**\n\n```cpp\n#include \"bbstrader/metatrader.hpp\"\n#include \u003cnumeric\u003e\n#include \u003ciostream\u003e\n\nclass MovingAverageStrategy : public MT5::MetaTraderClient {\npublic:\n    using MetaTraderClient::MetaTraderClient;\n\n    void on_tick(const std::string\u0026 symbol) {\n        auto rates_opt = copy_rates_from_pos(symbol, 1, 0, 20);\n\n        if (!rates_opt || rates_opt-\u003esize() \u003c 20) return;\n\n        const auto\u0026 rates = *rates_opt;\n\n        double sum = std::accumulate(rates.begin(), rates.end(), 0.0,\n                                     [](double a, const MT5::RateInfo\u0026 b) { return a + b.close; });\n        double sma = sum / rates.size();\n        double current_price = rates.back().close;\n\n        if (current_price \u003e sma) {\n            std::cout \u003c\u003c \"Price is above SMA. Sending Buy Order for \" \u003c\u003c symbol \u003c\u003c '\\n';\n            MT5::TradeRequest request;\n            request.action = MT5::TradeAction::DEAL;\n            request.symbol = symbol;\n            request.volume = 0.1;\n            request.type = MT5::OrderType::BUY;\n            request.type_filling = MT5::OrderFilling::FOK;\n            request.type_time = MT5::OrderTime::GTC;\n            send_order(request);\n        }\n    }\n};\n```\n\n_This C++ class would then be exposed to Python using `pybind11`._\n\n```cpp\n// Inside bindings.cpp\n#include \u003cpybind11/pybind11.h\u003e\n#include \"MovingAverageStrategy.hpp\"\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(my_strategies, m){\npy::class_\u003cMovingAverageStrategy, MT5::MetaTraderClient\u003e(m, \"MovingAverageStrategy\")\n    .def(py::init\u003cMT5::MetaTraderClient::Handlers\u003e())\n    .def(\"on_tick\", \u0026MovingAverageStrategy::on_tick);\n}\n```\n\n**Python Side (`main.py`):**\n\n```python\nfrom bbstrader.api import Mt5Handlers\nimport MetaTrader5 as mt5\nimport time\nfrom my_strategies import MovingAverageStrategy\n\n# 1. Instantiate the C++ strategy, injecting the Python MT5 handlers\nstrategy = MovingAverageStrategy(Mt5Handlers)\n\n# 2. Main execution loop\nif strategy.initialize():\n    while True:\n        strategy.on_tick(\"EURUSD\")\n        time.sleep(1)\n```\n\n#### Pattern 2: Python-Driven with C++ Acceleration\n\nThis 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.\n\n**Use this pattern when:**\n\n- Your strategy relies heavily on Python libraries like `pandas`, `scikit-learn`, or `tensorflow`.\n- Rapid prototyping and iteration are more important than absolute minimum latency.\n- Your core logic is more about decision-making based on pre-processed data than it is about raw computation speed.\n\n```python\nimport MetaTrader5 as mt5\nfrom bbstrader.api import Mt5Handlers\nfrom bbstrader.api.metatrader_client import MetaTraderClient\n\n# 1. Inherit from the C++ MetaTraderClient in Python\nclass MyStrategyClient(MetaTraderClient):\n    def __init__(self, handlers):\n        super().__init__(handlers)\n\n# 2. Instantiate your client\nstrategy = MyStrategyClient(Mt5Handlers)\n\n# 3. Interact with the MT5 terminal via the C++ bridge\nif strategy.initialize():\n    rates = strategy.copy_rates_from_pos(\"EURUSD\", mt5.TIMEFRAME_M1, 0, 100)\n    print(f\"Retrieved {len(rates)} rates via the C++ bridge.\")\n```\n\n### 3. **`trading`: Live Execution \u0026 Strategy Orchestrator**\n\n- **Purpose**: Manages live sessions, coordinates signals from strategies, risk from models, and execution via metatrader.\n- **Features**: Multi-account support, position hedging, trailing stops.\n\n### 4. `models`: Quant Toolkit for Signals \u0026 Risk\n\n- **Purpose**: Build/test models like NLP sentiment, VaR/CVaR risk, optimization.\n- **Features**: Currently Sentiment analysis, and Topic Modeling.\n- **Example**: Sentiment-Based Entry:\n\n```python\nfrom bbstrader.models import SentimenSentimentAnalyzer\n\nmodel = SentimenSentimentAnalyzer()  # Loads pre-trained NLP\nscore = model.analyze_sentiment(\"Fed hikes rates – markets soar!\")\nif score \u003e 0.7:  # Bullish? Buy!\n    print(\"Go long!\")\n```\n\n### **Other Modules:**\n\n`core`: Utilities (data structs, logging).\n`config`: Manages JSON configs in ~/.bbstrader/.\n`api`: Handler injections for bridges.\n\n## Getting Started\n\n### Prerequisites\n\n- **Python**: Python 3.12+ is required.\n- **MetaTrader 5 (MT5)**: Required for live execution (Windows).\n- **MT5 Broker**: [Admirals](https://one.justmarkets.link/a/tufvj0xugm/registration/trader), [JustMarkets](https://one.justmarkets.link/a/tufvj0xugm/registration/trader), [FTMO](https://trader.ftmo.com/?affiliates=JGmeuQqepAZLMcdOEQRp).\n\n## Installation\n\n`bbstrader` is designed for both Python and C++ developers. Follow the instructions that best suit your needs.\n\n### For the Python Quant\n\nGet started in minutes using `pip`. We strongly recommend using a virtual environment.\n\n```bash\n# Create and activate a virtual environment\npython -m venv venv\nsource venv/bin/activate  # on Linux/macOS\nvenv\\Scripts\\activate     # on Windows\n\n# Install bbstrader\npip install bbstrader[MT5] # Windows\npip install bbstrader  # Linux/macOS\n```\n\n### For the C++ Developer\n\nTo develop your own C++ strategies, you can use `vcpkg` to install the `bbstrader` library and its dependencies.\n\n```bash\n# If you don't have vcpkg, clone and bootstrap it\ngit clone https://github.com/microsoft/vcpkg\n./vcpkg/bootstrap-vcpkg.sh or ./vcpkg/bootstrap-vcpkg.bat\n\n# Install bbstrader\n./vcpkg/vcpkg install bbstrader\n```\n\n## CLI workflow\n\n`bbstrader` shines via CLI – launch everything from one command!\n\n| Action             | Command                                                                                                               |\n| :----------------- | :-------------------------------------------------------------------------------------------------------------------- |\n| **Run Backtest**   | `python -m bbstrader --run backtest --strategy SMAStrategy --account MY_ACCOUNT --config backtest.json`               |\n| **Live Execution** | `python -m bbstrader --run execution --strategy KalmanFilter --account MY_ACCOUNT --config execution.json --parallel` |\n| **Copy Trades**    | `python -m bbstrader --run copier --source 123456 --targets 789012 --risk_multiplier 2.0`                             |\n| **Get Help**       | `python -m bbstrader --help`                                                                                          |\n\n**Config Example** (`~/.bbstrader/execution/execution.json`):\n\n```json\n{\n  \"SMAStrategy\": {\n    \"MY_MT5_ACCOUNT_1\": {\n      \"symbol_list\": [\"EURUSD\", \"GBPUSD\"],\n      \"trades_kwargs\": { \"magic\": 12345, \"comment\": \"SMA_Live\" },\n      \"short_window\": 20,\n      \"long_window\": 50\n    }\n  }\n}\n```\n\n## 🌍 Community \u0026 Support\n\n- **[Read the Docs](https://bbstrader.readthedocs.io/en/latest/)**: Full API reference and tutorials.\n- **[GitHub Issues](https://github.com/bbalouki/bbstrader/issues)**: Report bugs or request features.\n- **[LinkedIn](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)**: Connect with the creator.\n\n---\n\n### Professional Services\n\nIf you need a custom trading strategy, a proprietary risk model, advanced data pipelines, or a dedicated copy trading server setup, professional services are available.\n\n**Contact the Developer:**  \n📧 [bertin@bbs-trading.com](mailto:bertin@bbs-trading.com)\n\n---\n\n### Support the Project\n\nIf you find this project useful and would like to support its continued development, you can contribute here:\n\n☕ [Support the Developer](https://paypal.me/bertinbalouki?country.x=SN\u0026locale.x=en_US)\n\n---\n\n_Disclaimer: Trading involves significant risk. `bbstrader` provides the tools, but you provide the strategy. Test thoroughly on demo accounts before deploying real capital._\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbbalouki%2Fbbstrader","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbbalouki%2Fbbstrader","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbbalouki%2Fbbstrader/lists"}