bbstrader 2.0.1__tar.gz → 2.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. {bbstrader-2.0.1 → bbstrader-2.0.2}/PKG-INFO +73 -50
  2. {bbstrader-2.0.1 → bbstrader-2.0.2}/README.md +70 -47
  3. bbstrader-2.0.2/VERSION.txt +1 -0
  4. bbstrader-2.0.2/bbstrader/assets/bbstrader.ico +0 -0
  5. bbstrader-2.0.2/bbstrader/assets/bbstrader.png +0 -0
  6. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/backtest.py +5 -5
  7. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/execution.py +2 -9
  8. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/strategy.py +5 -1
  9. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/core/strategy.py +6 -7
  10. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/trading/execution.py +6 -6
  11. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/trading/strategy.py +4 -0
  12. {bbstrader-2.0.1 → bbstrader-2.0.2}/cmake/Helpers.cmake +1 -1
  13. {bbstrader-2.0.1 → bbstrader-2.0.2}/pyproject.toml +2 -2
  14. {bbstrader-2.0.1 → bbstrader-2.0.2}/src/metatrader.cpp +4 -2
  15. bbstrader-2.0.2/tcopier.spec +59 -0
  16. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/api/test_metatrader_client.py +1 -1
  17. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/btengine/test_execution.py +4 -0
  18. bbstrader-2.0.1/VERSION.txt +0 -1
  19. {bbstrader-2.0.1 → bbstrader-2.0.2}/.clang-format +0 -0
  20. {bbstrader-2.0.1 → bbstrader-2.0.2}/.clang-tidy +0 -0
  21. {bbstrader-2.0.1 → bbstrader-2.0.2}/.github/workflows/cpp_linux.yml +0 -0
  22. {bbstrader-2.0.1 → bbstrader-2.0.2}/.github/workflows/cpp_macos.yml +0 -0
  23. {bbstrader-2.0.1 → bbstrader-2.0.2}/.github/workflows/cpp_win.yml +0 -0
  24. {bbstrader-2.0.1 → bbstrader-2.0.2}/.github/workflows/python.yml +0 -0
  25. {bbstrader-2.0.1 → bbstrader-2.0.2}/.gitignore +0 -0
  26. {bbstrader-2.0.1 → bbstrader-2.0.2}/.readthedocs.yaml +0 -0
  27. {bbstrader-2.0.1 → bbstrader-2.0.2}/CMakeLists.txt +0 -0
  28. {bbstrader-2.0.1 → bbstrader-2.0.2}/LICENSE +0 -0
  29. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/__init__.py +0 -0
  30. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/__main__.py +0 -0
  31. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/api/__init__.py +0 -0
  32. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/api/handlers.py +0 -0
  33. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/api/metatrader_client.pyi +0 -0
  34. {bbstrader-2.0.1 → bbstrader-2.0.2/bbstrader}/assets/bbs_.png +0 -0
  35. {bbstrader-2.0.1 → bbstrader-2.0.2/bbstrader}/assets/qs_metrics_1.png +0 -0
  36. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/__init__.py +0 -0
  37. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/data.py +0 -0
  38. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/event.py +0 -0
  39. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/performance.py +0 -0
  40. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/btengine/portfolio.py +0 -0
  41. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/compat.py +0 -0
  42. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/config.py +0 -0
  43. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/core/__init__.py +0 -0
  44. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/core/data.py +0 -0
  45. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/__init__.py +0 -0
  46. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/_copier.py +0 -0
  47. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/account.py +0 -0
  48. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/broker.py +0 -0
  49. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/copier.py +0 -0
  50. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/rates.py +0 -0
  51. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/risk.py +0 -0
  52. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/trade.py +0 -0
  53. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/metatrader/utils.py +0 -0
  54. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/models/__init__.py +0 -0
  55. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/models/nlp.py +0 -0
  56. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/models/optimization.py +0 -0
  57. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/scripts.py +0 -0
  58. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/trading/__init__.py +0 -0
  59. {bbstrader-2.0.1 → bbstrader-2.0.2}/bbstrader/trading/utils.py +0 -0
  60. {bbstrader-2.0.1 → bbstrader-2.0.2}/cmake/Versions.cmake +0 -0
  61. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/Doxyfile.in +0 -0
  62. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/Makefile +0 -0
  63. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.api.rst +0 -0
  64. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.btengine.rst +0 -0
  65. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.core.rst +0 -0
  66. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.metatrader.rst +0 -0
  67. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.models.rst +0 -0
  68. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.rst +0 -0
  69. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/bbstrader.trading.rst +0 -0
  70. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/conf.py +0 -0
  71. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/index.rst +0 -0
  72. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/make.bat +0 -0
  73. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/modules.rst +0 -0
  74. {bbstrader-2.0.1 → bbstrader-2.0.2}/docs/requirements.txt +0 -0
  75. {bbstrader-2.0.1 → bbstrader-2.0.2}/examples/strategies.py +0 -0
  76. {bbstrader-2.0.1 → bbstrader-2.0.2}/include/bbstrader/metatrader.hpp +0 -0
  77. {bbstrader-2.0.1 → bbstrader-2.0.2}/include/bbstrader/objects.hpp +0 -0
  78. {bbstrader-2.0.1 → bbstrader-2.0.2}/src/CMakeLists.txt +0 -0
  79. {bbstrader-2.0.1 → bbstrader-2.0.2}/src/bbstrader.cpp +0 -0
  80. {bbstrader-2.0.1 → bbstrader-2.0.2}/src/cmake/BbstraderConfig.cmake.in +0 -0
  81. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/CMakeLists.txt +0 -0
  82. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/__init__.py +0 -0
  83. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/api/__init__.py +0 -0
  84. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/btengine/__init__.py +0 -0
  85. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/btengine/test_backtest.py +0 -0
  86. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/btengine/test_data.py +0 -0
  87. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/btengine/test_events.py +0 -0
  88. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/btengine/test_portfolio.py +0 -0
  89. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/cpp/test_metatrader_client.cpp +0 -0
  90. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/metatrader/__init__.py +0 -0
  91. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/metatrader/test_account.py +0 -0
  92. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/metatrader/test_rates.py +0 -0
  93. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/metatrader/test_risk_management.py +0 -0
  94. {bbstrader-2.0.1 → bbstrader-2.0.2}/tests/metatrader/test_trade.py +0 -0
  95. {bbstrader-2.0.1 → bbstrader-2.0.2}/vcpkg.json +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bbstrader
3
- Version: 2.0.1
4
- Summary: Simplified Investment & Trading Toolkit
3
+ Version: 2.0.2
4
+ Summary: Simplified Investment & Trading Toolkit with Python & C++
5
5
  Keywords: Finance,Toolkit,Financial,Analysis,Fundamental,Quantitative,Database,Equities,Currencies,Economics,ETFs,Funds,Indices,Moneymarkets,Commodities,Futures,CFDs,Derivatives,Trading,Investing,Portfolio,Optimization,Performance
6
6
  Author-Email: Bertin Balouki SIMYELI <bertin@bbs-trading.com>
7
7
  Maintainer-Email: Bertin Balouki SIMYELI <bertin@bbs-trading.com>
@@ -37,7 +37,7 @@ Requires-Dist: python-telegram-bot>=22.3
37
37
  Requires-Dist: PyYAML>=6.0.2
38
38
  Requires-Dist: QuantStats>=0.0.77
39
39
  Requires-Dist: seaborn>=0.13.2
40
- Requires-Dist: spacy>=3.8.7
40
+ Requires-Dist: spacy>=3.8.11
41
41
  Requires-Dist: sumy>=0.11.0
42
42
  Requires-Dist: tabulate>=0.9.0
43
43
  Requires-Dist: textblob>=0.19.0
@@ -64,7 +64,9 @@ Description-Content-Type: text/markdown
64
64
  [![LinkedIn](https://img.shields.io/badge/LinkedIn-grey?logo=Linkedin&logoColor=white)](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)
65
65
 
66
66
  ## Welcome to `bbstrader` – The Ultimate C++ & Python Trading Powerhouse!
67
+
67
68
  ## Table of Contents
69
+
68
70
  - [Overview](#overview)
69
71
  - [Why `bbstrader` Stands Out](#why-bbstrader-stands-out)
70
72
  - [Trusted by Traders Worldwide](#trusted-by-traders-worldwide)
@@ -74,7 +76,7 @@ Description-Content-Type: text/markdown
74
76
  - [1. `btengine`: Event-Driven Backtesting Beast](#1-btengine-event-driven-backtesting-beast)
75
77
  - [2. `metatrader`: The C++/Python Bridge to MT5](#2-metatrader-the-cpython-bridge-to-mt5)
76
78
  - [Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)](#pattern-1-c-core-python-orchestrator-maximum-performance)
77
- - [Pattern 2: Python-Driven with C++ Acceleration](#pattern-2-python-driven-with-c-acceleration)
79
+ - [Pattern 2: Python-Driven with C++ Acceleration](#pattern-2-python-driven-with-c-acceleration)
78
80
  - [3. `trading`: Live Execution & Strategy Orchestrator](#3-trading-live-execution--strategy-orchestrator)
79
81
  - [4. `models`: Quant Toolkit for Signals & Risk](#4-models-quant-toolkit-for-signals--risk)
80
82
  - [Getting Started](#getting-started)
@@ -88,54 +90,59 @@ Description-Content-Type: text/markdown
88
90
 
89
91
  ### Overview
90
92
 
91
- 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.
93
+ 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.
92
94
 
93
- 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.
95
+ 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.
94
96
 
95
97
  ## **Why `bbstrader` Stands Out**
96
98
 
97
99
  In a crowded field of trading libraries, `bbstrader` is architected to solve the most challenging problems in algorithmic trading: performance, flexibility, and platform limitations.
98
100
 
99
- * **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.
100
- * **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.
101
- * **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.
102
- 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.
103
- * **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.
104
- **Flexible Interface**: CLI & GUI
105
- ``bbstrader`` adapts to your workflow.
101
+ - **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.
102
+ - **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.
103
+ - **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.
104
+ 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.
105
+ - **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.
106
+ **Flexible Interface**: CLI & GUI
107
+ `bbstrader` adapts to your workflow.
106
108
  - **Automation Fanatics**: Use the CLI for headless scripts, cron jobs, and server deployments.
107
109
  - **Visual Traders**: Launch the Desktop GUI (currently for Copy Trading) to monitor your master and slave accounts, check replication status, and manage connections visually.
108
110
  - **Cross-Platform & Future-Proof**: Works on Windows, macOS, Linux. (IBKR integration in development).
109
111
 
110
112
  ## **Trusted by Traders Worldwide**
111
- With thousands of downloads, ``bbstrader`` is trusted by traders worldwide. It's not just code – it's your ticket to profitable, scalable strategies.
113
+
114
+ With thousands of downloads, `bbstrader` is trusted by traders worldwide. It's not just code – it's your ticket to profitable, scalable strategies.
112
115
 
113
116
  ## **The `bbstrader` Edge: Uniting C++ Speed with Python Flexibility**
114
117
 
115
- bbstrader's hybrid design is its secret weapon. At the heart is a bidirectional C++/Python bridge via ``metatrader_client`` module:
118
+ bbstrader's hybrid design is its secret weapon. At the heart is a bidirectional C++/Python bridge via `metatrader_client` module:
116
119
 
117
- 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.
118
- 2. **Python for Smarts**: Orchestrate everything with modules like ``trading`` and ``btengine``.
119
- 3. **The Data Flow:** The result is a clean, efficient, and powerful execution loop:
120
- `Python (Orchestration & Analysis) -> C++ (High-Speed Signal Generation) -> Python (MT5 Communication) -> C++ (Receives Market Data)`
120
+ 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.
121
+ 2. **Python for Smarts**: Orchestrate everything with modules like `trading` and `btengine`.
122
+ 3. **The Data Flow:** The result is a clean, efficient, and powerful execution loop:
123
+ `Python (Orchestration & Analysis) -> C++ (High-Speed Signal Generation) -> Python (MT5 Communication) -> C++ (Receives Market Data)`
121
124
 
122
125
  This setup crushes performance ceilings: Run ML models in Python, execute trades in C++, and backtest millions of bars in minutes.
123
126
 
124
127
  ### **Overcoming the MQL5 Bottleneck**
128
+
125
129
  MetaTrader 5 is a world-class trading platform, but its native MQL5 language presents significant limitations for complex, high-frequency strategies:
126
- - **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.
127
- - **Ecosystem Constraints:** MQL5 lacks access to the vast, mature ecosystems of libraries for numerical computation, data science, and AI that C++ and Python offer.
128
- - **Architectural Rigidity:** Implementing sophisticated, multi-threaded, or event-driven architectures in MQL5 is often a complex and error-prone endeavor.
130
+
131
+ - **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.
132
+ - **Ecosystem Constraints:** MQL5 lacks access to the vast, mature ecosystems of libraries for numerical computation, data science, and AI that C++ and Python offer.
133
+ - **Architectural Rigidity:** Implementing sophisticated, multi-threaded, or event-driven architectures in MQL5 is often a complex and error-prone endeavor.
129
134
 
130
135
  `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.
131
136
 
132
137
  ## **Key Modules**
138
+
133
139
  bbstrader is modular, with each component laser-focused.
134
140
 
135
141
  ### 1. **btengine**: Event-Driven Backtesting Beast
136
- - **Purpose**: Simulate strategies with historical data, including slippage, commissions, and multi-asset portfolios. Optimizes parameters and computes metrics like Sharpe Ratio, Drawdown, and CAGR.
137
- - **Features**: Event queue for ticks/orders, vectorized operations for speed, integration with models for signal generation.
138
- - **Example**: Backtest a StockIndexSTBOTrading from the example strategies.
142
+
143
+ - **Purpose**: Simulate strategies with historical data, including slippage, commissions, and multi-asset portfolios. Optimizes parameters and computes metrics like Sharpe Ratio, Drawdown, and CAGR.
144
+ - **Features**: Event queue for ticks/orders, vectorized operations for speed, integration with models for signal generation.
145
+ - **Example**: Backtest a StockIndexSTBOTrading from the example strategies.
139
146
 
140
147
  ```Python
141
148
  # Inside the examples/
@@ -146,25 +153,28 @@ if __name__ == '__main__':
146
153
  ```
147
154
 
148
155
  ### Backtesting Results
149
- ![Backtesting Results1]( https://github.com/bbalouki/bbstrader/blob/main/assets/bbs_.png?raw=true)
150
- ![Backtesting Results2](https://github.com/bbalouki/bbstrader/blob/main/assets/qs_metrics_1.png?raw=true)
151
156
 
157
+ ![Backtesting Results1](https://github.com/bbalouki/bbstrader/blob/main/bbstrader/assets/bbs_.png?raw=true)
158
+ ![Backtesting Results2](https://github.com/bbalouki/bbstrader/blob/main/bbstrader/assets/qs_metrics_1.png?raw=true)
152
159
 
153
160
  ### 2. **metatrader**: The C++/Python Bridge to MT5
154
161
 
155
- - **Purpose**: High-speed MT5 integration. C++ MetaTraderClient mirrors MT5 API for orders, rates, and account management.
156
- - **Features**: Bidirectional callbacks, error handling, real-time tick processing.
157
- - **Strategy Patterns**: Two main patterns to build strategies:
162
+ - **Purpose**: High-speed MT5 integration. C++ MetaTraderClient mirrors MT5 API for orders, rates, and account management.
163
+ - **Features**: Bidirectional callbacks, error handling, real-time tick processing.
164
+ - **Strategy Patterns**: Two main patterns to build strategies:
158
165
 
159
166
  #### Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)
167
+
160
168
  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.
161
169
 
162
170
  **Use this pattern when:**
171
+
163
172
  - Your strategy involves complex mathematical calculations that are slow in Python.
164
173
  - You need to react to market data in the shortest possible time.
165
174
  - Your production environment demands deterministic, low-latency performance.
166
175
 
167
176
  **C++ Side (`MovingAverageStrategy.cpp`):**
177
+
168
178
  ```cpp
169
179
  #include "bbstrader/metatrader.hpp"
170
180
  #include <numeric>
@@ -176,12 +186,12 @@ public:
176
186
 
177
187
  void on_tick(const std::string& symbol) {
178
188
  auto rates_opt = copy_rates_from_pos(symbol, 1, 0, 20);
179
-
189
+
180
190
  if (!rates_opt || rates_opt->size() < 20) return;
181
191
 
182
192
  const auto& rates = *rates_opt;
183
-
184
- double sum = std::accumulate(rates.begin(), rates.end(), 0.0,
193
+
194
+ double sum = std::accumulate(rates.begin(), rates.end(), 0.0,
185
195
  [](double a, const MT5::RateInfo& b) { return a + b.close; });
186
196
  double sma = sum / rates.size();
187
197
  double current_price = rates.back().close;
@@ -200,7 +210,9 @@ public:
200
210
  }
201
211
  };
202
212
  ```
203
- *This C++ class would then be exposed to Python using `pybind11`.*
213
+
214
+ _This C++ class would then be exposed to Python using `pybind11`._
215
+
204
216
  ```cpp
205
217
  // Inside bindings.cpp
206
218
  #include <pybind11/pybind11.h>
@@ -216,6 +228,7 @@ py::class_<MovingAverageStrategy, MT5::MetaTraderClient>(m, "MovingAverageStrate
216
228
  ```
217
229
 
218
230
  **Python Side (`main.py`):**
231
+
219
232
  ```python
220
233
  from bbstrader.api import Mt5Handlers
221
234
  import MetaTrader5 as mt5
@@ -233,9 +246,11 @@ if strategy.initialize():
233
246
  ```
234
247
 
235
248
  #### Pattern 2: Python-Driven with C++ Acceleration
249
+
236
250
  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.
237
251
 
238
252
  **Use this pattern when:**
253
+
239
254
  - Your strategy relies heavily on Python libraries like `pandas`, `scikit-learn`, or `tensorflow`.
240
255
  - Rapid prototyping and iteration are more important than absolute minimum latency.
241
256
  - Your core logic is more about decision-making based on pre-processed data than it is about raw computation speed.
@@ -259,16 +274,17 @@ if strategy.initialize():
259
274
  print(f"Retrieved {len(rates)} rates via the C++ bridge.")
260
275
  ```
261
276
 
262
- ### 3. **``trading``: Live Execution & Strategy Orchestrator**
277
+ ### 3. **`trading`: Live Execution & Strategy Orchestrator**
263
278
 
264
279
  - **Purpose**: Manages live sessions, coordinates signals from strategies, risk from models, and execution via metatrader.
265
280
  - **Features**: Multi-account support, position hedging, trailing stops.
266
281
 
267
- ### 4. ``models``: Quant Toolkit for Signals & Risk
282
+ ### 4. `models`: Quant Toolkit for Signals & Risk
268
283
 
269
284
  - **Purpose**: Build/test models like NLP sentiment, VaR/CVaR risk, optimization.
270
285
  - **Features**: Currently Sentiment analysis, and Topic Modeling.
271
286
  - **Example**: Sentiment-Based Entry:
287
+
272
288
  ```python
273
289
  from bbstrader.models import SentimenSentimentAnalyzer
274
290
 
@@ -280,9 +296,9 @@ if score > 0.7: # Bullish? Buy!
280
296
 
281
297
  ### **Other Modules:**
282
298
 
283
- ``core``: Utilities (data structs, logging).
284
- ``config``: Manages JSON configs in ~/.bbstrader/.
285
- ``api``: Handler injections for bridges.
299
+ `core`: Utilities (data structs, logging).
300
+ `config`: Manages JSON configs in ~/.bbstrader/.
301
+ `api`: Handler injections for bridges.
286
302
 
287
303
  ## Getting Started
288
304
 
@@ -293,10 +309,13 @@ if score > 0.7: # Bullish? Buy!
293
309
  - **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).
294
310
 
295
311
  ## Installation
312
+
296
313
  `bbstrader` is designed for both Python and C++ developers. Follow the instructions that best suit your needs.
297
314
 
298
315
  ### For the Python Quant
316
+
299
317
  Get started in minutes using `pip`. We strongly recommend using a virtual environment.
318
+
300
319
  ```bash
301
320
  # Create and activate a virtual environment
302
321
  python -m venv venv
@@ -309,7 +328,9 @@ pip install bbstrader # Linux/macOS
309
328
  ```
310
329
 
311
330
  ### For the C++ Developer
331
+
312
332
  To develop your own C++ strategies, you can use `vcpkg` to install the `bbstrader` library and its dependencies.
333
+
313
334
  ```bash
314
335
  # If you don't have vcpkg, clone and bootstrap it
315
336
  git clone https://github.com/microsoft/vcpkg
@@ -318,17 +339,20 @@ git clone https://github.com/microsoft/vcpkg
318
339
  # Install bbstrader
319
340
  ./vcpkg/vcpkg install bbstrader
320
341
  ```
342
+
321
343
  ## CLI workflow
344
+
322
345
  `bbstrader` shines via CLI – launch everything from one command!
323
346
 
324
- | Action | Command |
325
- | :--- | :--- |
326
- | **Run Backtest** | `python -m bbstrader --run backtest --strategy SMAStrategy --account MY_ACCOUNT --config backtest.json` |
347
+ | Action | Command |
348
+ | :----------------- | :-------------------------------------------------------------------------------------------------------------------- |
349
+ | **Run Backtest** | `python -m bbstrader --run backtest --strategy SMAStrategy --account MY_ACCOUNT --config backtest.json` |
327
350
  | **Live Execution** | `python -m bbstrader --run execution --strategy KalmanFilter --account MY_ACCOUNT --config execution.json --parallel` |
328
- | **Copy Trades** | `python -m bbstrader --run copier --source 123456 --targets 789012 --risk_multiplier 2.0` |
329
- | **Get Help** | `python -m bbstrader --help` |
351
+ | **Copy Trades** | `python -m bbstrader --run copier --source 123456 --targets 789012 --risk_multiplier 2.0` |
352
+ | **Get Help** | `python -m bbstrader --help` |
353
+
354
+ **Config Example** (`~/.bbstrader/execution/execution.json`):
330
355
 
331
- **Config Example** (``~/.bbstrader/execution/execution.json``):
332
356
  ```json
333
357
  {
334
358
  "SMAStrategy": {
@@ -344,9 +368,9 @@ git clone https://github.com/microsoft/vcpkg
344
368
 
345
369
  ## 🌍 Community & Support
346
370
 
347
- * **[Read the Docs](https://bbstrader.readthedocs.io/en/latest/)**: Full API reference and tutorials.
348
- * **[GitHub Issues](https://github.com/bbalouki/bbstrader/issues)**: Report bugs or request features.
349
- * **[LinkedIn](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)**: Connect with the creator.
371
+ - **[Read the Docs](https://bbstrader.readthedocs.io/en/latest/)**: Full API reference and tutorials.
372
+ - **[GitHub Issues](https://github.com/bbalouki/bbstrader/issues)**: Report bugs or request features.
373
+ - **[LinkedIn](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)**: Connect with the creator.
350
374
 
351
375
  ---
352
376
 
@@ -365,7 +389,6 @@ If you find this project useful and would like to support its continued developm
365
389
 
366
390
  ☕ [Support the Developer](https://paypal.me/bertinbalouki?country.x=SN&locale.x=en_US)
367
391
 
368
-
369
392
  ---
370
393
 
371
- *Disclaimer: Trading involves significant risk. `bbstrader` provides the tools, but you provide the strategy. Test thoroughly on demo accounts before deploying real capital.*
394
+ _Disclaimer: Trading involves significant risk. `bbstrader` provides the tools, but you provide the strategy. Test thoroughly on demo accounts before deploying real capital._
@@ -14,7 +14,9 @@
14
14
  [![LinkedIn](https://img.shields.io/badge/LinkedIn-grey?logo=Linkedin&logoColor=white)](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)
15
15
 
16
16
  ## Welcome to `bbstrader` – The Ultimate C++ & Python Trading Powerhouse!
17
+
17
18
  ## Table of Contents
19
+
18
20
  - [Overview](#overview)
19
21
  - [Why `bbstrader` Stands Out](#why-bbstrader-stands-out)
20
22
  - [Trusted by Traders Worldwide](#trusted-by-traders-worldwide)
@@ -24,7 +26,7 @@
24
26
  - [1. `btengine`: Event-Driven Backtesting Beast](#1-btengine-event-driven-backtesting-beast)
25
27
  - [2. `metatrader`: The C++/Python Bridge to MT5](#2-metatrader-the-cpython-bridge-to-mt5)
26
28
  - [Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)](#pattern-1-c-core-python-orchestrator-maximum-performance)
27
- - [Pattern 2: Python-Driven with C++ Acceleration](#pattern-2-python-driven-with-c-acceleration)
29
+ - [Pattern 2: Python-Driven with C++ Acceleration](#pattern-2-python-driven-with-c-acceleration)
28
30
  - [3. `trading`: Live Execution & Strategy Orchestrator](#3-trading-live-execution--strategy-orchestrator)
29
31
  - [4. `models`: Quant Toolkit for Signals & Risk](#4-models-quant-toolkit-for-signals--risk)
30
32
  - [Getting Started](#getting-started)
@@ -38,54 +40,59 @@
38
40
 
39
41
  ### Overview
40
42
 
41
- 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.
43
+ 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.
42
44
 
43
- 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.
45
+ 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.
44
46
 
45
47
  ## **Why `bbstrader` Stands Out**
46
48
 
47
49
  In a crowded field of trading libraries, `bbstrader` is architected to solve the most challenging problems in algorithmic trading: performance, flexibility, and platform limitations.
48
50
 
49
- * **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.
50
- * **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.
51
- * **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.
52
- 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.
53
- * **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.
54
- **Flexible Interface**: CLI & GUI
55
- ``bbstrader`` adapts to your workflow.
51
+ - **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.
52
+ - **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.
53
+ - **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.
54
+ 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.
55
+ - **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.
56
+ **Flexible Interface**: CLI & GUI
57
+ `bbstrader` adapts to your workflow.
56
58
  - **Automation Fanatics**: Use the CLI for headless scripts, cron jobs, and server deployments.
57
59
  - **Visual Traders**: Launch the Desktop GUI (currently for Copy Trading) to monitor your master and slave accounts, check replication status, and manage connections visually.
58
60
  - **Cross-Platform & Future-Proof**: Works on Windows, macOS, Linux. (IBKR integration in development).
59
61
 
60
62
  ## **Trusted by Traders Worldwide**
61
- With thousands of downloads, ``bbstrader`` is trusted by traders worldwide. It's not just code – it's your ticket to profitable, scalable strategies.
63
+
64
+ With thousands of downloads, `bbstrader` is trusted by traders worldwide. It's not just code – it's your ticket to profitable, scalable strategies.
62
65
 
63
66
  ## **The `bbstrader` Edge: Uniting C++ Speed with Python Flexibility**
64
67
 
65
- bbstrader's hybrid design is its secret weapon. At the heart is a bidirectional C++/Python bridge via ``metatrader_client`` module:
68
+ bbstrader's hybrid design is its secret weapon. At the heart is a bidirectional C++/Python bridge via `metatrader_client` module:
66
69
 
67
- 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.
68
- 2. **Python for Smarts**: Orchestrate everything with modules like ``trading`` and ``btengine``.
69
- 3. **The Data Flow:** The result is a clean, efficient, and powerful execution loop:
70
- `Python (Orchestration & Analysis) -> C++ (High-Speed Signal Generation) -> Python (MT5 Communication) -> C++ (Receives Market Data)`
70
+ 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.
71
+ 2. **Python for Smarts**: Orchestrate everything with modules like `trading` and `btengine`.
72
+ 3. **The Data Flow:** The result is a clean, efficient, and powerful execution loop:
73
+ `Python (Orchestration & Analysis) -> C++ (High-Speed Signal Generation) -> Python (MT5 Communication) -> C++ (Receives Market Data)`
71
74
 
72
75
  This setup crushes performance ceilings: Run ML models in Python, execute trades in C++, and backtest millions of bars in minutes.
73
76
 
74
77
  ### **Overcoming the MQL5 Bottleneck**
78
+
75
79
  MetaTrader 5 is a world-class trading platform, but its native MQL5 language presents significant limitations for complex, high-frequency strategies:
76
- - **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.
77
- - **Ecosystem Constraints:** MQL5 lacks access to the vast, mature ecosystems of libraries for numerical computation, data science, and AI that C++ and Python offer.
78
- - **Architectural Rigidity:** Implementing sophisticated, multi-threaded, or event-driven architectures in MQL5 is often a complex and error-prone endeavor.
80
+
81
+ - **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.
82
+ - **Ecosystem Constraints:** MQL5 lacks access to the vast, mature ecosystems of libraries for numerical computation, data science, and AI that C++ and Python offer.
83
+ - **Architectural Rigidity:** Implementing sophisticated, multi-threaded, or event-driven architectures in MQL5 is often a complex and error-prone endeavor.
79
84
 
80
85
  `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.
81
86
 
82
87
  ## **Key Modules**
88
+
83
89
  bbstrader is modular, with each component laser-focused.
84
90
 
85
91
  ### 1. **btengine**: Event-Driven Backtesting Beast
86
- - **Purpose**: Simulate strategies with historical data, including slippage, commissions, and multi-asset portfolios. Optimizes parameters and computes metrics like Sharpe Ratio, Drawdown, and CAGR.
87
- - **Features**: Event queue for ticks/orders, vectorized operations for speed, integration with models for signal generation.
88
- - **Example**: Backtest a StockIndexSTBOTrading from the example strategies.
92
+
93
+ - **Purpose**: Simulate strategies with historical data, including slippage, commissions, and multi-asset portfolios. Optimizes parameters and computes metrics like Sharpe Ratio, Drawdown, and CAGR.
94
+ - **Features**: Event queue for ticks/orders, vectorized operations for speed, integration with models for signal generation.
95
+ - **Example**: Backtest a StockIndexSTBOTrading from the example strategies.
89
96
 
90
97
  ```Python
91
98
  # Inside the examples/
@@ -96,25 +103,28 @@ if __name__ == '__main__':
96
103
  ```
97
104
 
98
105
  ### Backtesting Results
99
- ![Backtesting Results1]( https://github.com/bbalouki/bbstrader/blob/main/assets/bbs_.png?raw=true)
100
- ![Backtesting Results2](https://github.com/bbalouki/bbstrader/blob/main/assets/qs_metrics_1.png?raw=true)
101
106
 
107
+ ![Backtesting Results1](https://github.com/bbalouki/bbstrader/blob/main/bbstrader/assets/bbs_.png?raw=true)
108
+ ![Backtesting Results2](https://github.com/bbalouki/bbstrader/blob/main/bbstrader/assets/qs_metrics_1.png?raw=true)
102
109
 
103
110
  ### 2. **metatrader**: The C++/Python Bridge to MT5
104
111
 
105
- - **Purpose**: High-speed MT5 integration. C++ MetaTraderClient mirrors MT5 API for orders, rates, and account management.
106
- - **Features**: Bidirectional callbacks, error handling, real-time tick processing.
107
- - **Strategy Patterns**: Two main patterns to build strategies:
112
+ - **Purpose**: High-speed MT5 integration. C++ MetaTraderClient mirrors MT5 API for orders, rates, and account management.
113
+ - **Features**: Bidirectional callbacks, error handling, real-time tick processing.
114
+ - **Strategy Patterns**: Two main patterns to build strategies:
108
115
 
109
116
  #### Pattern 1: C++ Core, Python Orchestrator (Maximum Performance)
117
+
110
118
  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.
111
119
 
112
120
  **Use this pattern when:**
121
+
113
122
  - Your strategy involves complex mathematical calculations that are slow in Python.
114
123
  - You need to react to market data in the shortest possible time.
115
124
  - Your production environment demands deterministic, low-latency performance.
116
125
 
117
126
  **C++ Side (`MovingAverageStrategy.cpp`):**
127
+
118
128
  ```cpp
119
129
  #include "bbstrader/metatrader.hpp"
120
130
  #include <numeric>
@@ -126,12 +136,12 @@ public:
126
136
 
127
137
  void on_tick(const std::string& symbol) {
128
138
  auto rates_opt = copy_rates_from_pos(symbol, 1, 0, 20);
129
-
139
+
130
140
  if (!rates_opt || rates_opt->size() < 20) return;
131
141
 
132
142
  const auto& rates = *rates_opt;
133
-
134
- double sum = std::accumulate(rates.begin(), rates.end(), 0.0,
143
+
144
+ double sum = std::accumulate(rates.begin(), rates.end(), 0.0,
135
145
  [](double a, const MT5::RateInfo& b) { return a + b.close; });
136
146
  double sma = sum / rates.size();
137
147
  double current_price = rates.back().close;
@@ -150,7 +160,9 @@ public:
150
160
  }
151
161
  };
152
162
  ```
153
- *This C++ class would then be exposed to Python using `pybind11`.*
163
+
164
+ _This C++ class would then be exposed to Python using `pybind11`._
165
+
154
166
  ```cpp
155
167
  // Inside bindings.cpp
156
168
  #include <pybind11/pybind11.h>
@@ -166,6 +178,7 @@ py::class_<MovingAverageStrategy, MT5::MetaTraderClient>(m, "MovingAverageStrate
166
178
  ```
167
179
 
168
180
  **Python Side (`main.py`):**
181
+
169
182
  ```python
170
183
  from bbstrader.api import Mt5Handlers
171
184
  import MetaTrader5 as mt5
@@ -183,9 +196,11 @@ if strategy.initialize():
183
196
  ```
184
197
 
185
198
  #### Pattern 2: Python-Driven with C++ Acceleration
199
+
186
200
  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.
187
201
 
188
202
  **Use this pattern when:**
203
+
189
204
  - Your strategy relies heavily on Python libraries like `pandas`, `scikit-learn`, or `tensorflow`.
190
205
  - Rapid prototyping and iteration are more important than absolute minimum latency.
191
206
  - Your core logic is more about decision-making based on pre-processed data than it is about raw computation speed.
@@ -209,16 +224,17 @@ if strategy.initialize():
209
224
  print(f"Retrieved {len(rates)} rates via the C++ bridge.")
210
225
  ```
211
226
 
212
- ### 3. **``trading``: Live Execution & Strategy Orchestrator**
227
+ ### 3. **`trading`: Live Execution & Strategy Orchestrator**
213
228
 
214
229
  - **Purpose**: Manages live sessions, coordinates signals from strategies, risk from models, and execution via metatrader.
215
230
  - **Features**: Multi-account support, position hedging, trailing stops.
216
231
 
217
- ### 4. ``models``: Quant Toolkit for Signals & Risk
232
+ ### 4. `models`: Quant Toolkit for Signals & Risk
218
233
 
219
234
  - **Purpose**: Build/test models like NLP sentiment, VaR/CVaR risk, optimization.
220
235
  - **Features**: Currently Sentiment analysis, and Topic Modeling.
221
236
  - **Example**: Sentiment-Based Entry:
237
+
222
238
  ```python
223
239
  from bbstrader.models import SentimenSentimentAnalyzer
224
240
 
@@ -230,9 +246,9 @@ if score > 0.7: # Bullish? Buy!
230
246
 
231
247
  ### **Other Modules:**
232
248
 
233
- ``core``: Utilities (data structs, logging).
234
- ``config``: Manages JSON configs in ~/.bbstrader/.
235
- ``api``: Handler injections for bridges.
249
+ `core`: Utilities (data structs, logging).
250
+ `config`: Manages JSON configs in ~/.bbstrader/.
251
+ `api`: Handler injections for bridges.
236
252
 
237
253
  ## Getting Started
238
254
 
@@ -243,10 +259,13 @@ if score > 0.7: # Bullish? Buy!
243
259
  - **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).
244
260
 
245
261
  ## Installation
262
+
246
263
  `bbstrader` is designed for both Python and C++ developers. Follow the instructions that best suit your needs.
247
264
 
248
265
  ### For the Python Quant
266
+
249
267
  Get started in minutes using `pip`. We strongly recommend using a virtual environment.
268
+
250
269
  ```bash
251
270
  # Create and activate a virtual environment
252
271
  python -m venv venv
@@ -259,7 +278,9 @@ pip install bbstrader # Linux/macOS
259
278
  ```
260
279
 
261
280
  ### For the C++ Developer
281
+
262
282
  To develop your own C++ strategies, you can use `vcpkg` to install the `bbstrader` library and its dependencies.
283
+
263
284
  ```bash
264
285
  # If you don't have vcpkg, clone and bootstrap it
265
286
  git clone https://github.com/microsoft/vcpkg
@@ -268,17 +289,20 @@ git clone https://github.com/microsoft/vcpkg
268
289
  # Install bbstrader
269
290
  ./vcpkg/vcpkg install bbstrader
270
291
  ```
292
+
271
293
  ## CLI workflow
294
+
272
295
  `bbstrader` shines via CLI – launch everything from one command!
273
296
 
274
- | Action | Command |
275
- | :--- | :--- |
276
- | **Run Backtest** | `python -m bbstrader --run backtest --strategy SMAStrategy --account MY_ACCOUNT --config backtest.json` |
297
+ | Action | Command |
298
+ | :----------------- | :-------------------------------------------------------------------------------------------------------------------- |
299
+ | **Run Backtest** | `python -m bbstrader --run backtest --strategy SMAStrategy --account MY_ACCOUNT --config backtest.json` |
277
300
  | **Live Execution** | `python -m bbstrader --run execution --strategy KalmanFilter --account MY_ACCOUNT --config execution.json --parallel` |
278
- | **Copy Trades** | `python -m bbstrader --run copier --source 123456 --targets 789012 --risk_multiplier 2.0` |
279
- | **Get Help** | `python -m bbstrader --help` |
301
+ | **Copy Trades** | `python -m bbstrader --run copier --source 123456 --targets 789012 --risk_multiplier 2.0` |
302
+ | **Get Help** | `python -m bbstrader --help` |
303
+
304
+ **Config Example** (`~/.bbstrader/execution/execution.json`):
280
305
 
281
- **Config Example** (``~/.bbstrader/execution/execution.json``):
282
306
  ```json
283
307
  {
284
308
  "SMAStrategy": {
@@ -294,9 +318,9 @@ git clone https://github.com/microsoft/vcpkg
294
318
 
295
319
  ## 🌍 Community & Support
296
320
 
297
- * **[Read the Docs](https://bbstrader.readthedocs.io/en/latest/)**: Full API reference and tutorials.
298
- * **[GitHub Issues](https://github.com/bbalouki/bbstrader/issues)**: Report bugs or request features.
299
- * **[LinkedIn](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)**: Connect with the creator.
321
+ - **[Read the Docs](https://bbstrader.readthedocs.io/en/latest/)**: Full API reference and tutorials.
322
+ - **[GitHub Issues](https://github.com/bbalouki/bbstrader/issues)**: Report bugs or request features.
323
+ - **[LinkedIn](https://www.linkedin.com/in/bertin-balouki-s-15b17a1a6)**: Connect with the creator.
300
324
 
301
325
  ---
302
326
 
@@ -315,7 +339,6 @@ If you find this project useful and would like to support its continued developm
315
339
 
316
340
  ☕ [Support the Developer](https://paypal.me/bertinbalouki?country.x=SN&locale.x=en_US)
317
341
 
318
-
319
342
  ---
320
343
 
321
- *Disclaimer: Trading involves significant risk. `bbstrader` provides the tools, but you provide the strategy. Test thoroughly on demo accounts before deploying real capital.*
344
+ _Disclaimer: Trading involves significant risk. `bbstrader` provides the tools, but you provide the strategy. Test thoroughly on demo accounts before deploying real capital._
@@ -0,0 +1 @@
1
+ 2.0.2
@@ -115,7 +115,7 @@ class BacktestEngine:
115
115
  self.events, self.symbol_list, **self.kwargs
116
116
  )
117
117
  self.strategy: Strategy = self.strategy_cls(
118
- bars=self.data_handler, events=self.events, **self.kwargs
118
+ self.events, self.symbol_list, self.data_handler, **self.kwargs
119
119
  )
120
120
  self.portfolio: Portfolio = Portfolio(
121
121
  self.data_handler,
@@ -282,10 +282,10 @@ def run_backtest(
282
282
  - Monthly returns saved as a PNG image.
283
283
 
284
284
  Example:
285
- >>> from bbstrader.trading.strategies import StockIndexSTBOTrading
286
- >>> from bbstrader.metatrader.utils import config_logger
287
- >>> from bbstrader.datahandlers import MT5DataHandler
288
- >>> from bbstrader.execution import MT5ExecutionHandler
285
+ >>> from examples.strategies import StockIndexSTBOTrading
286
+ >>> from bbstrader.config import config_logger
287
+ >>> from bbstrader.btengine.data import MT5DataHandler
288
+ >>> from bbstrader.btengine.execution import MT5ExecutionHandler
289
289
  >>> from datetime import datetime
290
290
  >>>
291
291
  >>> logger = config_logger('index_trade.log', console_log=True)
@@ -172,16 +172,9 @@ class MT5ExecutionHandler(ExecutionHandler):
172
172
  lot = quantity / contract_size
173
173
  if symbol_type == SymbolType.FOREX:
174
174
  lot = float(quantity * price / contract_size)
175
- return self._check_lot(symbol, lot)
176
-
177
- def _check_lot(self, symbol: str, lot: float) -> float:
178
- symbol_info = self.__account.get_symbol_info(symbol)
179
- if lot < symbol_info.volume_min:
180
- return float(symbol_info.volume_min)
181
- elif lot > symbol_info.volume_max:
182
- return float(symbol_info.volume_max)
183
- return round(lot, 2)
175
+ return self.__account.broker.validate_lot_size(symbol, lot)
184
176
 
177
+
185
178
  def _estimate_total_fees(
186
179
  self,
187
180
  symbol: str,
@@ -1,3 +1,4 @@
1
+ from abc import abstractmethod
1
2
  from datetime import datetime
2
3
  from queue import Queue
3
4
  from typing import Any, Callable, Dict, List, Optional, Union
@@ -7,7 +8,7 @@ import pandas as pd
7
8
  from loguru import logger
8
9
 
9
10
  from bbstrader.btengine.data import DataHandler
10
- from bbstrader.btengine.event import Events, FillEvent, SignalEvent
11
+ from bbstrader.btengine.event import Events, FillEvent, MarketEvent, SignalEvent
11
12
  from bbstrader.config import BBSTRADER_DIR
12
13
  from bbstrader.core.strategy import BaseStrategy, TradingMode
13
14
 
@@ -161,6 +162,9 @@ class BacktestStrategy(BaseStrategy):
161
162
  return {a: v[-window:] for a, v in asset_values.items()}
162
163
  return None
163
164
 
165
+ @abstractmethod
166
+ def calculate_signals(self, event: MarketEvent) -> None: ...
167
+
164
168
  def _send_order(
165
169
  self,
166
170
  id: int,
@@ -181,7 +181,7 @@ class Strategy(metaclass=ABCMeta):
181
181
  """
182
182
 
183
183
  @abstractmethod
184
- def calculate_signals(self, *args: Any, **kwargs: Any) -> List[TradeSignal]:
184
+ def calculate_signals(self, *args: Any, **kwargs: Any) -> List[TradeSignal] | None:
185
185
  raise NotImplementedError("Should implement calculate_signals()")
186
186
 
187
187
  def check_pending_orders(self, *args: Any, **kwargs: Any) -> None: ...
@@ -243,17 +243,16 @@ class BaseStrategy(Strategy):
243
243
  """Returns the available cash (virtual or real)."""
244
244
  raise NotImplementedError
245
245
 
246
- def calculate_signals(self, *args: Any, **kwargs: Any) -> List[TradeSignal]:
246
+ def calculate_signals(self, *args: Any, **kwargs: Any) -> List[TradeSignal] | None:
247
247
  """
248
248
  Provides the mechanisms to calculate signals for the strategy.
249
- This methods should return a list of signals for the strategy.
249
+ This methods should return a list of signals for the strategy For Live mode and None For Backtest mode.
250
250
 
251
251
  Each signal must be a ``TradeSignal`` object with the following attributes:
252
- - ``action``: The order to execute on the symbol (LONG, SHORT, EXIT, etc.), see `bbstrader.core.utils.TradeAction`.
253
- - ``price``: The price at which to execute the action, used for pending orders.
254
- - ``stoplimit``: The stop-limit price for STOP-LIMIT orders, used for pending stop limit orders.
255
252
  - ``id``: The unique identifier for the strategy or order.
256
- - ``comment``: An optional comment or description related to the trade signal.
253
+ - ``action``: The order to execute on the symbol (LONG, SHORT, EXIT, etc.), see `bbstrader.core.utils.TradeAction`.
254
+ - ``symbol``: The trading symbol (e.g., stock ticker, forex pair, crypto asset).
255
+ - See ``bbstrader.core.strategy.TradeSignal`` for other optionnal arguments.
257
256
  """
258
257
  raise NotImplementedError("Should implement calculate_signals()")
259
258
 
@@ -344,7 +344,7 @@ class Mt5ExecutionEngine:
344
344
  max_trades = {
345
345
  symbol: mtrades[symbol]
346
346
  if mtrades is not None and isinstance(mtrades, dict) and symbol in mtrades
347
- else self.trades_instances[symbol].max_trade()
347
+ else self.trades_instances[symbol].rm.max_trade()
348
348
  for symbol in self.symbols
349
349
  }
350
350
  return max_trades
@@ -361,7 +361,7 @@ class Mt5ExecutionEngine:
361
361
  def _init_strategy(self, **kwargs) -> LiveStrategy:
362
362
  try:
363
363
  check_mt5_connection(**kwargs)
364
- strategy = self.strategy_cls(symbol_list=self.symbols, **kwargs)
364
+ strategy = self.strategy_cls(self.symbols, **kwargs)
365
365
  except Exception as e:
366
366
  self._print_exc(
367
367
  f"Initializing strategy, STRATEGY={self.STRATEGY}, ACCOUNT={self.ACCOUNT}",
@@ -407,10 +407,10 @@ class Mt5ExecutionEngine:
407
407
  **common_data,
408
408
  symbol_type=account.get_symbol_type(symbol).value,
409
409
  description=symbol_info.description if symbol_info else "N/A",
410
- price=price if price else "MARKET",
411
- stoplimit=stoplimit,
412
- sl=sl if sl else "AUTO",
413
- tp=tp if tp else "AUTO",
410
+ price=round(price, 5) if price else "MARKET",
411
+ stoplimit=round(stoplimit, 5) if stoplimit else None,
412
+ sl=round(sl, 5) if sl else "AUTO",
413
+ tp=round(tp, 5) if tp else "AUTO",
414
414
  broker=account.broker.name,
415
415
  timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
416
416
  )
@@ -2,6 +2,7 @@ from datetime import datetime
2
2
  from enum import IntEnum
3
3
  from queue import Queue
4
4
  from typing import Any, Callable, Dict, List, Optional, Union
5
+ from abc import abstractmethod
5
6
 
6
7
  import numpy as np
7
8
  import pandas as pd
@@ -177,6 +178,9 @@ class LiveStrategy(BaseStrategy):
177
178
  )
178
179
 
179
180
  return generate_signal(signal_id, symbol, action, **kwargs)
181
+
182
+ @abstractmethod
183
+ def calculate_signals(self, *args: Any, **kwargs: Any) -> List[TradeSignal]: ...
180
184
 
181
185
  def ispositions(
182
186
  self,
@@ -178,7 +178,7 @@ function(apply_formating USE_PER_FILE_LOGIC)
178
178
  foreach(file ${ALL_FILES})
179
179
  add_custom_command(
180
180
  TARGET format
181
- POST_BUILD
181
+ PRE_BUILD
182
182
  COMMAND ${CLANG_FORMAT_EXE} -i "${file}"
183
183
  COMMENT "Formatting ${file}"
184
184
  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
@@ -5,7 +5,7 @@ build-backend = "scikit_build_core.build"
5
5
  [project]
6
6
  name = "bbstrader"
7
7
  dynamic = ["version"]
8
- description = "Simplified Investment & Trading Toolkit"
8
+ description = "Simplified Investment & Trading Toolkit with Python & C++"
9
9
  readme = "README.md"
10
10
  dependencies = [
11
11
  "beautifulsoup4>=4.13.5",
@@ -27,7 +27,7 @@ dependencies = [
27
27
  "PyYAML>=6.0.2",
28
28
  "QuantStats>=0.0.77",
29
29
  "seaborn>=0.13.2",
30
- "spacy>=3.8.7",
30
+ "spacy>=3.8.11",
31
31
  "sumy>=0.11.0",
32
32
  "tabulate>=0.9.0",
33
33
  "textblob>=0.19.0",
@@ -917,7 +917,8 @@ PYBIND11_MODULE(metatrader_client, m) {
917
917
  .def(
918
918
  "history_orders_get",
919
919
  py::overload_cast<uint64_t>(&MetaTraderClient::history_orders_get),
920
- py::arg("ticket")
920
+ py::arg("ticket"),
921
+ py::return_value_policy::move
921
922
  )
922
923
  .def(
923
924
  "history_orders_get_by_pos",
@@ -970,7 +971,8 @@ PYBIND11_MODULE(metatrader_client, m) {
970
971
  .def(
971
972
  "history_deals_get",
972
973
  py::overload_cast<uint64_t>(&MetaTraderClient::history_deals_get),
973
- py::arg("ticket")
974
+ py::arg("ticket"),
975
+ py::return_value_policy::move
974
976
  )
975
977
  .def(
976
978
  "history_deals_get_by_pos",
@@ -0,0 +1,59 @@
1
+ # -*- mode: python ; coding: utf-8 -*-
2
+
3
+ from PyInstaller.utils.hooks import collect_data_files, collect_submodules, collect_dynamic_libs
4
+
5
+ block_cipher = None
6
+
7
+ # Collect files for en_core_web_sm
8
+ datas_sm = collect_data_files('en_core_web_sm')
9
+ hiddenimports_sm = collect_submodules('en_core_web_sm')
10
+ hiddenimports_bbs = collect_submodules("bbstrader")
11
+ binaries_bbs = collect_dynamic_libs("bbstrader")
12
+ binaries_sm = collect_dynamic_libs('en_core_web_sm')
13
+
14
+ explicit_hidden_imports = [
15
+ 'bbstrader.api.metatrader_client',
16
+ 'MetaTrader5'
17
+ ]
18
+
19
+
20
+
21
+ a = Analysis(
22
+ ['bbstrader/metatrader/_copier.py'],
23
+ pathex=[],
24
+ binaries=binaries_sm + binaries_bbs,
25
+ datas=[('bbstrader/assets', 'assets')] + datas_sm,
26
+ hiddenimports=hiddenimports_sm + hiddenimports_bbs + explicit_hidden_imports,
27
+ hookspath=['hooks'],
28
+ hooksconfig={},
29
+ runtime_hooks=[],
30
+ excludes=[],
31
+ win_no_prefer_redirects=False,
32
+ win_private_assemblies=False,
33
+ cipher=block_cipher,
34
+ noarchive=False,
35
+ )
36
+ pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
37
+
38
+ exe = EXE(
39
+ pyz,
40
+ a.scripts,
41
+ a.binaries,
42
+ a.zipfiles,
43
+ a.datas,
44
+ [],
45
+ name='tcopier',
46
+ debug=False,
47
+ bootloader_ignore_signals=False,
48
+ strip=False,
49
+ upx=True,
50
+ upx_exclude=[],
51
+ runtime_tmpdir=None,
52
+ console=False, # --windowed
53
+ disable_windowed_traceback=False,
54
+ argv_emulation=False,
55
+ target_arch=None,
56
+ codesign_identity=None,
57
+ entitlements_file=None,
58
+ icon='bbstrader/assets/bbstrader.ico',
59
+ )
@@ -23,7 +23,7 @@ class Handlers:
23
23
  pass
24
24
 
25
25
 
26
- class TestMetaTraderClientAllMethods(unittest.TestCase):
26
+ class TestMetaTraderClient(unittest.TestCase):
27
27
  client: MetaTraderClient = None
28
28
 
29
29
  @classmethod
@@ -133,6 +133,7 @@ class TestMT5ExecutionHandler(unittest.TestCase):
133
133
  self.mock_account_instance.get_symbol_info.return_value = SymbolInfo(
134
134
  100000, 0.01, 1000
135
135
  )
136
+ self.mock_account_instance.broker.validate_lot_size.return_value = 0.1
136
137
 
137
138
  order_event = OrderEvent(symbol, "MKT", qty, "BUY", price, "LONG")
138
139
  self.handler.execute_order(order_event)
@@ -153,6 +154,7 @@ class TestMT5ExecutionHandler(unittest.TestCase):
153
154
  self.mock_account_instance.get_symbol_info.return_value = SymbolInfo(
154
155
  100, 0.01, 1000
155
156
  )
157
+ self.mock_account_instance.broker.validate_lot_size.return_value = 0.1
156
158
 
157
159
  order_event = OrderEvent(symbol, "MKT", qty, "BUY", price, "LONG")
158
160
  self.handler.execute_order(order_event)
@@ -168,6 +170,7 @@ class TestMT5ExecutionHandler(unittest.TestCase):
168
170
 
169
171
  self.mock_account_instance.get_symbol_type.return_value = SymbolType.INDICES
170
172
  self.mock_account_instance.get_symbol_info.return_value = SymbolInfo(1, 0.1, 50)
173
+ self.mock_account_instance.broker.validate_lot_size.return_value = 10
171
174
 
172
175
  order_event = OrderEvent(symbol, "MKT", qty, "BUY", price, "LONG")
173
176
  self.handler.execute_order(order_event)
@@ -185,6 +188,7 @@ class TestMT5ExecutionHandler(unittest.TestCase):
185
188
  self.mock_account_instance.get_symbol_info.return_value = SymbolInfo(
186
189
  100000, 0.01, 1000
187
190
  )
191
+ self.mock_account_instance.broker.validate_lot_size.return_value = 0.01
188
192
 
189
193
  order_event = OrderEvent(symbol, "MKT", qty, "BUY", price, "LONG")
190
194
  self.handler.execute_order(order_event)
@@ -1 +0,0 @@
1
- 2.0.1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes