bbstrader 0.2.99__py3-none-any.whl → 0.3.0__py3-none-any.whl

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.

Potentially problematic release.


This version of bbstrader might be problematic. Click here for more details.

@@ -31,6 +31,7 @@ from bbstrader.btengine.execution import MT5ExecutionHandler, SimExecutionHandle
31
31
  from bbstrader.btengine.strategy import Strategy
32
32
  from bbstrader.metatrader.account import Account
33
33
  from bbstrader.metatrader.rates import Rates
34
+ from bbstrader.metatrader.trade import TradingMode
34
35
  from bbstrader.models.risk import build_hmm_models
35
36
  from bbstrader.tseries import ArimaGarchModel, KalmanFilterModel
36
37
 
@@ -73,7 +74,7 @@ class SMAStrategy(Strategy):
73
74
  bars: DataHandler = None,
74
75
  events: Queue = None,
75
76
  symbol_list: List[str] = None,
76
- mode: Literal["backtest", "live"] = "backtest",
77
+ mode: TradingMode = TradingMode.BACKTEST,
77
78
  **kwargs,
78
79
  ):
79
80
  """
@@ -81,7 +82,7 @@ class SMAStrategy(Strategy):
81
82
  bars (DataHandler): A data handler object that provides market data.
82
83
  events (Queue): An event queue object where generated signals are placed.
83
84
  symbol_list (List[str]): A list of symbols to consider for trading.
84
- mode (Literal['backtest', 'live']): The mode of operation for the strategy.
85
+ mode TradingMode: The mode of operation for the strategy.
85
86
  short_window (int, optional): The period for the short moving average.
86
87
  long_window (int, optional): The period for the long moving average.
87
88
  time_frame (str, optional): The time frame for the data.
@@ -196,13 +197,13 @@ class SMAStrategy(Strategy):
196
197
  return signals
197
198
 
198
199
  def calculate_signals(self, event=None):
199
- if self.mode == "backtest" and event is not None:
200
+ if self.mode == TradingMode.BACKTEST and event is not None:
200
201
  if event.type == Events.MARKET:
201
202
  signals = self.create_backtest_signals()
202
203
  for signal in signals.values():
203
204
  if signal is not None:
204
205
  self.events.put(signal)
205
- elif self.mode == "live":
206
+ elif self.mode == TradingMode.LIVE:
206
207
  signals = self.create_live_signals()
207
208
  return signals
208
209
 
@@ -238,7 +239,7 @@ class ArimaGarchStrategy(Strategy):
238
239
  bars: DataHandler = None,
239
240
  events: Queue = None,
240
241
  symbol_list: List[str] = None,
241
- mode: Literal["backtest", "live"] = "backtest",
242
+ mode: TradingMode = TradingMode.BACKTEST,
242
243
  **kwargs,
243
244
  ):
244
245
  """
@@ -384,13 +385,13 @@ class ArimaGarchStrategy(Strategy):
384
385
  return signals
385
386
 
386
387
  def calculate_signals(self, event=None):
387
- if self.mode == "backtest" and event is not None:
388
+ if self.mode == TradingMode.BACKTEST and event is not None:
388
389
  if event.type == Events.MARKET:
389
390
  signals = self.create_backtest_signal()
390
391
  for signal in signals.values():
391
392
  if signal is not None:
392
393
  self.events.put(signal)
393
- elif self.mode == "live":
394
+ elif self.mode == TradingMode.LIVE:
394
395
  return self.create_live_signals()
395
396
 
396
397
 
@@ -408,7 +409,7 @@ class KalmanFilterStrategy(Strategy):
408
409
  bars: DataHandler = None,
409
410
  events: Queue = None,
410
411
  symbol_list: List[str] = None,
411
- mode: Literal["backtest", "live"] = "backtest",
412
+ mode: TradingMode = TradingMode.BACKTEST,
412
413
  **kwargs,
413
414
  ):
414
415
  """
@@ -567,10 +568,10 @@ class KalmanFilterStrategy(Strategy):
567
568
  """
568
569
  Calculate the Kalman Filter strategy.
569
570
  """
570
- if self.mode == "backtest" and event is not None:
571
+ if self.mode == TradingMode.BACKTEST and event is not None:
571
572
  if event.type == Events.MARKET:
572
573
  self.calculate_backtest_signals()
573
- elif self.mode == "live":
574
+ elif self.mode == TradingMode.LIVE:
574
575
  return self.calculate_live_signals()
575
576
 
576
577
 
@@ -589,7 +590,7 @@ class StockIndexSTBOTrading(Strategy):
589
590
  bars: DataHandler = None,
590
591
  events: Queue = None,
591
592
  symbol_list: List[str] = None,
592
- mode: Literal["backtest", "live"] = "backtest",
593
+ mode: TradingMode = TradingMode.BACKTEST,
593
594
  **kwargs,
594
595
  ):
595
596
  """
@@ -632,7 +633,7 @@ class StockIndexSTBOTrading(Strategy):
632
633
  self.heightest_price = {index: None for index in symbols}
633
634
  self.lowerst_price = {index: None for index in symbols}
634
635
 
635
- if self.mode == "backtest":
636
+ if self.mode == TradingMode.BACKTEST:
636
637
  self.qty = get_quantities(quantities, symbols)
637
638
  self.num_buys = {index: 0 for index in symbols}
638
639
  self.buy_prices = {index: [] for index in symbols}
@@ -751,10 +752,10 @@ class StockIndexSTBOTrading(Strategy):
751
752
  self.buy_prices[index] = []
752
753
 
753
754
  def calculate_signals(self, event=None) -> Dict[str, Union[str, None]]:
754
- if self.mode == "backtest" and event is not None:
755
+ if self.mode == TradingMode.BACKTEST and event is not None:
755
756
  if event.type == Events.MARKET:
756
757
  self.calculate_backtest_signals()
757
- elif self.mode == "live":
758
+ elif self.mode == TradingMode.LIVE:
758
759
  return self.calculate_live_signals()
759
760
 
760
761
 
bbstrader/tseries.py CHANGED
@@ -514,9 +514,8 @@ def get_corr(tickers: Union[List[str], Tuple[str, ...]], start: str, end: str) -
514
514
  >>> get_corr(['AAPL', 'MSFT', 'GOOG'], '2023-01-01', '2023-12-31')
515
515
  """
516
516
  # Download historical data
517
- data = yf.download(tickers, start=start, end=end, multi_level_index=False)[
518
- "Adj Close"
519
- ]
517
+ data = yf.download(tickers, start=start, end=end, multi_level_index=False, auto_adjust=True)
518
+ data = data["Adj Close"] if "Adj Close" in data.columns else data["Close"]
520
519
 
521
520
  # Calculate correlation matrix
522
521
  correlation_matrix = data.corr()
@@ -685,8 +684,8 @@ def run_cadf_test(
685
684
  auto_adjust=True,
686
685
  )
687
686
  df = pd.DataFrame(index=_p0.index)
688
- df[p0] = _p0["Adj Close"]
689
- df[p1] = _p1["Adj Close"]
687
+ df[p0] = _p0["Close"]
688
+ df[p1] = _p1["Close"]
690
689
  df = df.dropna()
691
690
 
692
691
  # Calculate optimal hedge ratio "beta"
@@ -784,7 +783,7 @@ def run_hurst_test(symbol: str, start: str, end: str):
784
783
  print(f"\nHurst(GBM): {_hurst(gbm)}")
785
784
  print(f"Hurst(MR): {_hurst(mr)}")
786
785
  print(f"Hurst(TR): {_hurst(tr)}")
787
- print(f"Hurst({symbol}): {hurst(data['Adj Close'])}\n")
786
+ print(f"Hurst({symbol}): {hurst(data['Close'])}\n")
788
787
 
789
788
 
790
789
  def test_cointegration(ticker1, ticker2, start, end):
@@ -796,7 +795,7 @@ def test_cointegration(ticker1, ticker2, start, end):
796
795
  progress=False,
797
796
  multi_level_index=False,
798
797
  auto_adjust=True,
799
- )["Adj Close"].dropna()
798
+ )["Close"].dropna()
800
799
 
801
800
  # Perform Johansen cointegration test
802
801
  result = coint_johansen(stock_data_pair, det_order=0, k_ar_diff=1)
@@ -947,8 +946,8 @@ def run_kalman_filter(
947
946
  )
948
947
 
949
948
  prices = pd.DataFrame(index=etf_df1.index)
950
- prices[etfs[0]] = etf_df1["Adj Close"]
951
- prices[etfs[1]] = etf_df2["Adj Close"]
949
+ prices[etfs[0]] = etf_df1["Close"]
950
+ prices[etfs[1]] = etf_df2["Close"]
952
951
 
953
952
  draw_date_coloured_scatterplot(etfs, prices)
954
953
  state_means, state_covs = calc_slope_intercept_kalman(etfs, prices)
@@ -0,0 +1,469 @@
1
+ Metadata-Version: 2.4
2
+ Name: bbstrader
3
+ Version: 0.3.0
4
+ Summary: Simplified Investment & Trading Toolkit
5
+ Home-page: https://github.com/bbalouki/bbstrader
6
+ Download-URL: https://pypi.org/project/bbstrader/
7
+ Author: Bertin Balouki SIMYELI
8
+ Author-email: <bertin@bbstrader.com>
9
+ Maintainer: Bertin Balouki SIMYELI
10
+ License: The MIT License (MIT)
11
+ Project-URL: Documentation, https://bbstrader.readthedocs.io/en/latest/
12
+ Project-URL: Source Code, https://github.com/bbalouki/bbstrader
13
+ Keywords: Finance,Toolkit,Financial,Analysis,Fundamental,Quantitative,Database,Equities,Currencies,Economics,ETFs,Funds,Indices,Moneymarkets,Commodities,Futures,CFDs,Derivatives,Trading,Investing,Portfolio,Optimization,Performance
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Financial and Insurance Industry
17
+ Classifier: Topic :: Office/Business :: Financial :: Investment
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Operating System :: Microsoft :: Windows
22
+ Classifier: Operating System :: POSIX :: Linux
23
+ Classifier: Operating System :: MacOS
24
+ Classifier: License :: OSI Approved :: MIT License
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: numpy<2.0.0,>=1.26.0
28
+ Requires-Dist: scikit-learn
29
+ Requires-Dist: statsmodels
30
+ Requires-Dist: seaborn
31
+ Requires-Dist: lightgbm
32
+ Requires-Dist: dash
33
+ Requires-Dist: nltk
34
+ Requires-Dist: spacy
35
+ Requires-Dist: pmdarima
36
+ Requires-Dist: pyportfolioopt
37
+ Requires-Dist: alphalens-reloaded
38
+ Requires-Dist: pandas_ta
39
+ Requires-Dist: yfinance
40
+ Requires-Dist: hmmlearn
41
+ Requires-Dist: arch
42
+ Requires-Dist: hurst
43
+ Requires-Dist: filterpy
44
+ Requires-Dist: pykalman
45
+ Requires-Dist: CurrencyConverter
46
+ Requires-Dist: tabulate
47
+ Requires-Dist: python-dotenv
48
+ Requires-Dist: ipython
49
+ Requires-Dist: QuantStats
50
+ Requires-Dist: exchange-calendars
51
+ Requires-Dist: tqdm
52
+ Requires-Dist: notify-py
53
+ Requires-Dist: python-telegram-bot
54
+ Requires-Dist: eodhd
55
+ Requires-Dist: financetoolkit
56
+ Requires-Dist: PyYAML
57
+ Requires-Dist: tables
58
+ Requires-Dist: pyfiglet
59
+ Requires-Dist: colorama
60
+ Requires-Dist: praw
61
+ Requires-Dist: tweepy
62
+ Requires-Dist: beautifulsoup4
63
+ Requires-Dist: textblob
64
+ Requires-Dist: vaderSentiment
65
+ Requires-Dist: pytest
66
+ Requires-Dist: pytest-mock
67
+ Provides-Extra: mt5
68
+ Requires-Dist: MetaTrader5; extra == "mt5"
69
+ Dynamic: author
70
+ Dynamic: author-email
71
+ Dynamic: classifier
72
+ Dynamic: description
73
+ Dynamic: description-content-type
74
+ Dynamic: download-url
75
+ Dynamic: home-page
76
+ Dynamic: keywords
77
+ Dynamic: license
78
+ Dynamic: license-file
79
+ Dynamic: maintainer
80
+ Dynamic: project-url
81
+ Dynamic: provides-extra
82
+ Dynamic: requires-dist
83
+ Dynamic: summary
84
+
85
+ # Simplified Investment & Trading Toolkit
86
+ [![Documentation Status](https://readthedocs.org/projects/bbstrader/badge/?version=latest)](https://bbstrader.readthedocs.io/en/latest/?badge=latest)
87
+ [![PYPI Version](https://img.shields.io/pypi/v/bbstrader)](https://pypi.org/project/bbstrader/)
88
+ [![PyPi status](https://img.shields.io/pypi/status/bbstrader.svg?maxAge=60)](https://pypi.python.org/pypi/bbstrader)
89
+ [![Supported Python Versions](https://img.shields.io/pypi/pyversions/bbstrader)](https://pypi.org/project/bbstrader/)
90
+ [![PyPI Downloads](https://static.pepy.tech/badge/bbstrader)](https://pepy.tech/projects/bbstrader)
91
+ [![CodeFactor](https://www.codefactor.io/repository/github/bbalouki/bbstrader/badge)](https://www.codefactor.io/repository/github/bbalouki/bbstrader)
92
+ [![LinkedIn](https://img.shields.io/badge/LinkedIn-grey?logo=Linkedin&logoColor=white)](https://www.linkedin.com/in/bertin-balouki-simyeli-15b17a1a6/)
93
+ [![PayPal Me](https://img.shields.io/badge/PayPal%20Me-blue?logo=paypal)](https://paypal.me/bertinbalouki?country.x=SN&locale.x=en_US)
94
+
95
+ [Dcoumentation](https://bbstrader.readthedocs.io/en/latest/index.html)
96
+
97
+ ## Table of Contents
98
+ - [Overview](#overview)
99
+ - [Features](#features)
100
+ - [Core Components](#core-components)
101
+ - [Getting Started](#getting-started)
102
+ - [Usage Examples](#usage-examples)
103
+ - [Configuration](#configuration)
104
+ - [Documentation](#documentation)
105
+ - [Customization and Contribution](#customization-and-contribution)
106
+ - [Contributing to `bbstrader`](#contributing-to-bbstrader)
107
+ - [Disclaimer](#disclaimer)
108
+ - [License](#license)
109
+
110
+ `bbstrader` is a trading system suite developed for MetaTrader 5 (MT5) and IBKR platforms (coming soon), designed to offer a comprehensive set of tools for developing, backtesting, executing, and managing a wide array of trading strategies. It targets algorithmic traders, quantitative analysts, and developers looking to build, test, and deploy trading strategies. With an emphasis on algorithmic and quantitative trading, `bbstrader` aims to provide users with a robust platform for exploring and deploying sophisticated trading strategies.
111
+
112
+ ## Overview
113
+
114
+ `bbstrader` aims to empower traders by providing a comprehensive and flexible suite of tools that simplify the development-to-deployment pipeline for algorithmic trading strategies. Our philosophy centers on offering powerful, accessible technology to navigate the complexities of financial markets, enabling users to efficiently design, test, and execute their trading ideas. By focusing on robust analytics and seamless platform integration, `bbstrader` strives to be an indispensable partner for traders seeking to enhance their market analysis and execution capabilities.
115
+
116
+ ## Features
117
+
118
+ - **Comprehensive Backtesting**: Rigorously test strategies with historical data to optimize performance before live deployment.
119
+ - **Integrated Risk Management**: Utilize sophisticated techniques to manage risk and adapt to fluctuating market conditions.
120
+ - **Automated Trading Execution**: Seamlessly execute trades on MT5, with real-time management of orders and positions. (IBKR support coming soon).
121
+ - **Trade Copier**: Effortlessly replicate trades across multiple accounts.
122
+ - **Flexible Strategy Framework**: Customize existing strategies or develop new ones with our adaptable, modular architecture.
123
+ - **Advanced Time Series Analysis**: Uncover market patterns and insights with powerful tools for in-depth financial data analysis.
124
+ - **Multi-Platform Support**: Designed for MetaTrader 5 with Interactive Brokers (IBKR) integration under active development.
125
+
126
+ You can read the full documentation [here](https://bbstrader.readthedocs.io/en/latest/index.html)
127
+
128
+ ## Core Components
129
+
130
+ `bbstrader` is organized into several key modules, each designed to address specific aspects of the trading workflow:
131
+
132
+ ### Backtesting Engine (`btengine`)
133
+ The **`btengine`** module enables traders to rigorously test their trading strategies using historical market data. It features an event-driven architecture, provides comprehensive performance metrics, and supports parameter optimization to evaluate and refine strategies before live deployment.
134
+
135
+ ### MetaTrader5 Module (`metatrader`)
136
+ This **`metatrader`** module facilitates direct interaction with the MetaTrader 5 platform. It allows for seamless execution of trading strategies, including managing accounts, sending orders, and monitoring positions and balances in real-time.
137
+
138
+ ### Trading Strategies (`trading.strategies`)
139
+ The **`trading.strategies`** sub-module offers a collection of pre-built trading strategies, such as those based on ARIMA+GARCH models, Kalman Filters, and Simple Moving Averages. These strategies often come equipped with risk management features, like Hidden Markov Models, and serve as practical examples or starting points for custom development.
140
+
141
+ ### Models Module (`models`)
142
+ The **`models`** module provides a versatile framework for implementing and utilizing various types of financial models. This includes statistical models for market analysis, machine learning models for predictive insights, NLP models for sentiment analysis, optimization algorithms for portfolio balancing, and risk management models to safeguard investments.
143
+
144
+ ### Time Series Module (`tseries`)
145
+ Specialized for advanced analysis of financial time series, the **`tseries`** module offers tools for cointegration testing, volatility modeling (e.g., GARCH), and various filtering techniques. These capabilities help in identifying market regimes, understanding asset correlations, and forecasting.
146
+
147
+ ### Live Trading Engine (`trading`)
148
+ The **`trading`** module serves as a higher-level interface for implementing and managing live trading logic. It coordinates between strategy signals, risk management, and execution modules like `metatrader` and `ibkr` to manage the full lifecycle of trades.
149
+
150
+ ### Interactive Brokers Module (`ibkr`)
151
+ Currently under development, the **`ibkr`** module aims to provide integration with the Interactive Brokers platform. It is expected to offer functionalities similar to the `metatrader` module, including account interaction, order execution, and position management for IBKR users.
152
+
153
+ ### Core Utilities (`core`)
154
+ The **`core`** module is the backbone of `bbstrader`, providing fundamental data structures, utility functions, configuration management, and shared functionalities. These components are used across the entire `bbstrader` ecosystem to ensure consistency and efficiency.
155
+
156
+ ### Configuration (`config`)
157
+ This **`config`** component handles the management of all system settings, including API keys, broker executable paths, database connections, and logging configurations, making it easier to customize `bbstrader` to specific user environments.
158
+
159
+ ### Compatibility Layer (`compat`)
160
+ The **`compat`** module is designed to enhance cross-platform development and testing. It achieves this by mocking the MetaTrader 5 environment, allowing developers on non-Windows systems to work with `bbstrader`'s core functionalities without needing a live MT5 instance.
161
+
162
+ ## Getting Started
163
+
164
+ To begin using `bbstrader`, please ensure your system meets the following prerequisites and follow the installation steps.
165
+
166
+ ### Prerequisites
167
+
168
+ * **Python**: Python 3.8+ is required.
169
+ * **MetaTrader 5 (MT5)**:
170
+ * The MetaTrader 5 platform must be installed on your system (primarily for Windows users needing live trading or direct MT5 interaction).
171
+ * An active trading account with a MetaTrader 5 broker. `bbstrader` currently supports:
172
+ * [Admirals Group AS](https://cabinet.a-partnership.com/visit/?bta=35537&brand=admiralmarkets) (for Stocks, ETFs, Indices, Commodities, Futures, Forex)
173
+ * [Just Global Markets Ltd.](https://one.justmarkets.link/a/tufvj0xugm/registration/trader) (for Stocks, Crypto, Indices, Commodities, Forex)
174
+ * [FTMO](https://trader.ftmo.com/?affiliates=JGmeuQqepAZLMcdOEQRp) (Proprietary Firm)
175
+ * **Interactive Brokers (IBKR)** (Optional, for IBKR integration):
176
+ * Interactive Brokers Trader Workstation (TWS) or IB Gateway must be installed and running.
177
+ * An active account with Interactive Brokers.
178
+ * The Python client library for the IBKR API: `ibapi`.
179
+
180
+ ### Installation
181
+
182
+ It is highly recommended to install `bbstrader` in a virtual environment to manage dependencies effectively.
183
+
184
+ 1. **Create and activate a virtual environment:**
185
+
186
+ * On macOS and Linux:
187
+ ```bash
188
+ python3 -m venv venv
189
+ source venv/bin/activate
190
+ ```
191
+ * On Windows:
192
+ ```bash
193
+ python -m venv venv
194
+ venv\Scripts\activate
195
+ ```
196
+
197
+ 2. **Install `bbstrader`:**
198
+
199
+ * **For Windows users (with MetaTrader 5):**
200
+ To include the official MetaTrader 5 package (which is Windows-only), install using:
201
+ ```bash
202
+ pip install bbstrader[MT5]
203
+ ```
204
+ * **For macOS, Linux users, or Windows users not needing direct MT5 interaction:**
205
+ Install the base package. The `MetaTrader5` package will be mocked by our `compat` module, allowing development and use of non-MT5 specific features.
206
+ ```bash
207
+ pip install bbstrader
208
+ ```
209
+
210
+ With these steps completed, you are ready to explore the features and modules of `bbstrader`!
211
+
212
+ ## Usage Examples
213
+
214
+ This section provides examples of how to use `bbstrader` for various tasks. Remember to replace placeholder values (like account numbers, server names, file paths, and strategy parameters) with your actual details.
215
+
216
+ ### Connecting to MetaTrader 5 (Conceptual)
217
+
218
+ `bbstrader` scripts and modules that interact with MetaTrader 5 handle the connection process internally, typically based on your configuration (`~/.bbstrader/config/config.ini` or environment variables).
219
+
220
+ If you were to connect to MetaTrader 5 manually using the `MetaTrader5` library, it would look something like this:
221
+
222
+ ```python
223
+ import MetaTrader5 as mt5
224
+
225
+ # Ensure the MetaTrader 5 terminal is running
226
+ # For Windows, specify the path to terminal64.exe
227
+ # For Linux/MacOS with Wine, specify the path and use mt5.wine_mode()
228
+
229
+ # Example for Windows:
230
+ # path_to_mt5 = r"C:\Program Files\MetaTrader 5\terminal64.exe"
231
+ # if not mt5.initialize(path=path_to_mt5, login=123456, server="YourServer", password="YourPassword"):
232
+ # For default path lookup (often sufficient if MT5 is installed and logged in):
233
+ if not mt5.initialize(login=123456, server="YourServer", password="YourPassword"):
234
+ print("initialize() failed, error code =", mt5.last_error())
235
+ quit()
236
+
237
+ # Display account information
238
+ account_info = mt5.account_info()
239
+ if account_info is not None:
240
+ print(account_info)
241
+ else:
242
+ print("Failed to get account info, error code =", mt5.last_error())
243
+
244
+ # ... your trading logic would go here ...
245
+
246
+ # Shutdown connection
247
+ mt5.shutdown()
248
+ ```
249
+ **Note:** `bbstrader`'s `metatrader` module and execution scripts abstract this process, using configured credentials and settings.
250
+
251
+ ### Programmatic Backtesting Example
252
+
253
+ You can run backtests on strategies programmatically. The following example demonstrates how to test the `sistbo` (Stock Index Short Term Buy Only) strategy:
254
+
255
+ ```python
256
+ from bbstrader.trading.strategies import test_strategy
257
+
258
+ if __name__ == '__main__':
259
+ # Run backtesting for Stock Index Short Term Buy Only Strategy
260
+ # This function call will use default parameters for the 'sistbo' strategy
261
+ # and save results to the default 'data/results' directory.
262
+ test_strategy(strategy='sistbo')
263
+ ```
264
+ This will typically output performance metrics and charts to a results directory.
265
+ ### Backtesting Results
266
+ ![Backtesting Results 1](https://github.com/bbalouki/bbstrader/blob/main/assets/bbs_.png?raw=true)
267
+ ![Backtesting Results 2](https://github.com/bbalouki/bbstrader/blob/main/assets/qs_metrics_1.png?raw=true)
268
+ ![Backtesting Results 3](https://github.com/bbalouki/bbstrader/blob/main/assets/qs_metrics_2.png?raw=true)
269
+ ![Backtesting Results 4](https://github.com/bbalouki/bbstrader/blob/main/assets/qs_plots_1_.png?raw=true)
270
+ ![Backtesting Results 5](https://github.com/bbalouki/bbstrader/blob/main/assets/qs_plots_2_.png?raw=true)
271
+
272
+ ### Command-Line Interface (CLI) Examples
273
+
274
+ `bbstrader` provides a CLI for various operations, including running live strategies, backtests, and utilities like the trade copier.
275
+
276
+ #### CLI - Running a Live Strategy
277
+
278
+ To run a live strategy, you first need to define its parameters in an `execution.json` file. By default, `bbstrader` looks for this file at `~/.bbstrader/execution/execution.json`.
279
+
280
+ 1. **Create `execution.json`**:
281
+ Create the directory `~/.bbstrader/execution/` if it doesn't exist. Inside, create `execution.json` with content like this for an `SMAStrategy`:
282
+
283
+ ```json
284
+ {
285
+ "SMAStrategy": {
286
+ "MY_MT5_ACCOUNT_1": {
287
+ "symbol_list": ["EURUSD", "GBPUSD"],
288
+ "trades_kwargs": {"magic": 12345, "comment": "SMAStrategy_Live"},
289
+ "short_window": 20,
290
+ "long_window": 50,
291
+ "time_frame": "H1",
292
+ "quantities": 0.1
293
+ }
294
+ }
295
+ }
296
+ ```
297
+ Replace `MY_MT5_ACCOUNT_1` with your account identifier used in `bbstrader`'s configuration. Adjust strategy parameters as needed.
298
+
299
+ 2. **Run the strategy via CLI**:
300
+ Open your terminal and run:
301
+ ```bash
302
+ python -m bbstrader --run execution -s SMAStrategy -a MY_MT5_ACCOUNT_1
303
+ ```
304
+ * `-s SMAStrategy`: Specifies the strategy class name to run.
305
+ * `-a MY_MT5_ACCOUNT_1`: Specifies the account name (must match a key in `execution.json` under the strategy).
306
+
307
+ The `SMAStrategy` (and other built-in strategies) should be discoverable by Python as they are part of the `bbstrader` package. For custom strategies, ensure they are in your `PYTHONPATH` or use the `-p` option to specify the directory.
308
+
309
+ #### CLI - Running a Backtest
310
+
311
+ You can also initiate backtests via the CLI. This is useful for quick tests or integrating into automated scripts.
312
+
313
+ To see all available options for backtesting:
314
+ ```bash
315
+ python -m bbstrader --run backtest --help
316
+ ```
317
+
318
+ Example command to backtest an `SMAStrategy`:
319
+ ```bash
320
+ python -m bbstrader --run backtest --strategy SMAStrategy
321
+ ```
322
+
323
+ #### CLI - Trade Copier
324
+
325
+ `bbstrader` includes a trade copier utility to replicate trades between different MetaTrader 5 accounts.
326
+
327
+ To see the available options for the trade copier:
328
+ ```bash
329
+ python -m bbstrader --run copier --help
330
+ ```
331
+ This will display detailed instructions on how to specify source and target accounts, along with other relevant parameters for copying trades.
332
+
333
+ ## Configuration
334
+
335
+ `bbstrader` uses a combination of user-defined JSON files and internal Python scripts for configuration. Understanding these will help you customize the system to your needs.
336
+
337
+ ### User Configuration Directory: `~/.bbstrader/`
338
+
339
+ `bbstrader` uses a hidden directory in your user's home folder, `~/.bbstrader/`, to store user-specific files. This typically includes:
340
+ * `execution/execution.json`: For live strategy execution parameters.
341
+ * `logs/`: Default directory for log files.
342
+ * Potentially other configuration files for different modules in the future.
343
+
344
+ You may need to create the `~/.bbstrader/` directory and its subdirectories (like `execution/` or `logs/`) manually if they don't exist upon first use.
345
+
346
+ ### Strategy Execution (`execution.json`)
347
+
348
+ * **Purpose**: Defines parameters for live strategy execution when using the `python -m bbstrader --run execution` command.
349
+ * **Default Location**: `~/.bbstrader/execution/execution.json`. You'll likely need to create this file and its parent directory.
350
+ * **Structure**:
351
+ * The file is a JSON object where top-level keys are strategy class names (e.g., `"SMAStrategy"`).
352
+ * Each strategy key contains another JSON object where keys are your account identifiers (e.g., `"MY_MT5_ACCOUNT_1"`). These account identifiers should match those you've configured for MT5 connections (often set via environment variables or a central configuration not detailed here but handled by the `metatrader` module).
353
+ * Under each account, you specify:
354
+ * `"symbol_list"`: A list of symbols the strategy will trade (e.g., `["EURUSD", "GBPUSD"]`).
355
+ * `"trades_kwargs"`: A dictionary for MetaTrader 5 specific order parameters, commonly including:
356
+ * `"magic"`: The magic number for orders placed by this strategy instance.
357
+ * `"comment"`: A comment for orders.
358
+ * Custom strategy parameters: Any other parameters required by your strategy's `__init__` method (e.g., `"short_window"`, `"long_window"`, `"time_frame"`, `"quantities"`).
359
+ * **Example**: Refer to the example in the "Usage Examples" -> "CLI - Running a Live Strategy" section.
360
+
361
+ ### MetaTrader 5 Broker Paths (`bbstrader/config.py`)
362
+
363
+ * The file `bbstrader/config.py` within the installed package contains a dictionary named `BROKERS_PATHS`. This dictionary maps broker shortnames (e.g., "AMG", "FTMO") to the default installation paths of their MetaTrader 5 `terminal64.exe`.
364
+ * **Customization**:
365
+ * If your MT5 terminal is installed in a non-standard location, or you use a broker not listed, `bbstrader` might not find the terminal.
366
+ * Ideally, future versions might support environment variables or a user-specific configuration file to override these paths.
367
+ * Currently, the most direct way to change these is by modifying `bbstrader/config.py` in your Python environment's `site-packages` directory. This should be done with caution as changes might be overwritten during package updates.
368
+ * Alternatively, when initializing `MetaTrader5` in your custom scripts, you can often pass the `path` argument directly to `mt5.initialize(path="C:\\path\\to\\your\\terminal64.exe", ...)`. `bbstrader`'s internal scripts might not use this method by default.
369
+
370
+ ### Logging Configuration (`bbstrader/config.py`)
371
+
372
+ * **Setup**: The `config_logger` function in `bbstrader/config.py` sets up application-wide logging.
373
+ * **Log Files**:
374
+ * By default, logs are typically saved to a file within the `~/.bbstrader/logs/` directory (e.g., `bbstrader.log`). The exact path might depend on how `config_logger` is invoked by the application.
375
+ * The default file logging level is `INFO`.
376
+ * **Console Logging**:
377
+ * If enabled (usually by default for CLI operations), console logging is set to `DEBUG` level, providing more verbose output.
378
+ * **Customization**:
379
+ * You can modify logging behavior (e.g., log levels, output formats, log file location) by editing the `config_logger` function in `bbstrader/config.py` within your `site-packages`. This is subject to the same caveats as modifying broker paths (potential overwrites on update).
380
+ * For programmatic use, you can re-configure logging after importing `bbstrader` modules if needed, though this might affect internal `bbstrader` logging.
381
+
382
+ ### General Advice
383
+
384
+ * For detailed configuration options specific to certain modules or advanced use cases, always refer to the official `bbstrader` documentation (if available) or consult the source code of the respective modules.
385
+ * Keep an eye on the `~/.bbstrader/` directory for any new configuration files or logs that might appear as you use different features.
386
+
387
+ ## Documentation
388
+
389
+ For comprehensive information, including detailed API references, tutorials, and advanced guides for each module, please refer to our full documentation hosted on ReadTheDocs:
390
+
391
+ [**View the Full Documentation on ReadTheDocs**](https://bbstrader.readthedocs.io/en/latest/)
392
+
393
+ Additionally, the codebase is commented and includes docstrings, which can be a valuable resource for understanding the implementation details of specific functions and classes.
394
+
395
+ ## Customization and Contribution
396
+
397
+ `bbstrader`'s modular design allows for easy customization and extension. Traders and developers are encouraged to modify existing strategies, add new ones, or enhance the system's capabilities. Contributions to the `bbstrader` project are welcome.
398
+
399
+ ## Contributing to `bbstrader`
400
+
401
+ We warmly welcome contributions from the trading and development community! Whether you're interested in fixing bugs, adding new features, or improving documentation, your help is invaluable to making `bbstrader` more robust and versatile. Here's how you can contribute:
402
+
403
+ ### Ways to Contribute
404
+
405
+ - **Develop New Strategies**: Implement and share your unique trading strategies or models.
406
+ - **Enhance Existing Modules**: Optimize the performance, extend the functionality, or improve the usability of existing modules.
407
+ - **Report Bugs**: Identify and report bugs to help us improve the system's stability and performance. (See "Reporting Issues" below).
408
+ - **Improve Documentation**: Contribute to the project's documentation for clearer guidance and better usability.
409
+ - **Share Insights and Best Practices**: Provide examples, tutorials, or best practices on utilizing `bbstrader` effectively.
410
+ - **Request Features**: Suggest new functionalities or improvements. (See "Requesting Features" below).
411
+
412
+ ### Reporting Issues
413
+
414
+ If you encounter a bug or unexpected behavior, please help us by reporting it on GitHub Issues. A well-detailed bug report makes it easier and faster to identify and fix the problem.
415
+
416
+ [**Report an Issue on GitHub**](https://github.com/bbalouki/bbstrader/issues)
417
+
418
+ Please include the following in your bug report:
419
+
420
+ * **Clear Title**: A concise and descriptive title for the issue.
421
+ * **Steps to Reproduce**: Detailed steps that consistently reproduce the bug.
422
+ * **Expected Behavior**: What you expected to happen.
423
+ * **Actual Behavior**: What actually happened.
424
+ * **Environment Details**:
425
+ * Python version (e.g., `python --version`).
426
+ * `bbstrader` version (e.g., `pip show bbstrader`).
427
+ * Operating System (e.g., Windows 10, Ubuntu 22.04, macOS Sonoma).
428
+ * **Logs and Error Messages**: Any relevant console output, error messages, or snippets from log files (`~/.bbstrader/logs/`). Please use code blocks for formatting.
429
+
430
+ ### Requesting Features
431
+
432
+ We are always open to suggestions for new features and improvements! If you have an idea that could make `bbstrader` better, please submit it via GitHub Issues.
433
+
434
+ [**Request a Feature on GitHub**](https://github.com/bbalouki/bbstrader/issues)
435
+
436
+ When submitting a feature request, please:
437
+
438
+ * **Clear Title**: A concise and descriptive title for the feature.
439
+ * **Describe the Feature**: Clearly explain the proposed functionality and its potential benefits to users.
440
+ * **Use Case / Problem Solved**: Describe the specific scenario or problem this feature would address.
441
+ * **Suggested Implementation (Optional)**: If you have ideas on how the feature could be implemented, feel free to share them.
442
+
443
+ ### How to Get Started
444
+
445
+ 1. **Fork the Repository**: Start by forking the `bbstrader` repository to your GitHub account.
446
+ 2. **Clone Your Fork**: Clone your forked repository to your local machine to start making changes.
447
+ 3. **Set Up Your Development Environment**: Ensure you have the necessary development environment set up, including Python, MetaTrader 5, and any dependencies.
448
+ 4. **Create a New Branch**: Make your changes in a new git branch, branching off from the main branch.
449
+ 5. **Implement Your Changes**: Work on bug fixes, features, or documentation improvements.
450
+ 6. **Test Your Changes**: Ensure your changes do not introduce new issues and that they work as intended.
451
+ 7. **Submit a Pull Request**: Once you're ready, submit a pull request (PR) against the main `bbstrader` repository. Include a clear description of the changes and any other relevant information.
452
+
453
+ ### Contribution Guidelines
454
+
455
+ Please adhere to the following guidelines to ensure a smooth contribution process:
456
+
457
+ - **Follow the Coding Standards**: Write clean, readable code and follow the coding conventions used throughout the project.
458
+ - **Document Your Changes**: Add comments and update the README.md files as necessary to explain your changes or additions.
459
+ - **Respect the License**: All contributions are subject to the MIT License under which `bbstrader` is distributed.
460
+
461
+ We're excited to see your contributions and to welcome you to the `bbstrader` community. Together, we can build a powerful tool that serves the needs of traders around the world.
462
+
463
+
464
+ ## Disclaimer
465
+
466
+ Trading financial instruments involves a high level of risk and may not be suitable for all investors. The developers of `bbstrader` are not responsible for any financial losses incurred from the use of this software. Trade responsibly and at your own risk.
467
+
468
+ ## License
469
+ `bbstrader` is open source and available under the MIT License.