# Simplified Investment & Trading Toolkit
[](https://bbstrader.readthedocs.io/en/latest/?badge=latest)
[](https://pypi.org/project/bbstrader/)
[](https://pypi.python.org/pypi/bbstrader)
[](https://pypi.org/project/bbstrader/)
[](https://pepy.tech/projects/bbstrader)
[](https://www.codefactor.io/repository/github/bbalouki/bbstrader)
[](https://www.linkedin.com/in/bertin-balouki-simyeli-15b17a1a6/)
[](https://paypal.me/bertinbalouki?country.x=SN&locale.x=en_US)
[Dcoumentation](https://bbstrader.readthedocs.io/en/latest/index.html)
## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Core Components](#core-components)
- [Getting Started](#getting-started)
- [Usage Examples](#usage-examples)
- [Configuration](#configuration)
- [Documentation](#documentation)
- [Customization and Contribution](#customization-and-contribution)
- [Contributing to `bbstrader`](#contributing-to-bbstrader)
- [Disclaimer](#disclaimer)
- [License](#license)
`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.
## Overview
`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.
## Features
- **Comprehensive Backtesting**: Rigorously test strategies with historical data to optimize performance before live deployment.
- **Integrated Risk Management**: Utilize sophisticated techniques to manage risk and adapt to fluctuating market conditions.
- **Automated Trading Execution**: Seamlessly execute trades on MT5, with real-time management of orders and positions. (IBKR support coming soon).
- **Trade Copier**: Effortlessly replicate trades across multiple accounts.
- **Flexible Strategy Framework**: Customize existing strategies or develop new ones with our adaptable, modular architecture.
- **Advanced Time Series Analysis**: Uncover market patterns and insights with powerful tools for in-depth financial data analysis.
- **Multi-Platform Support**: Designed for MetaTrader 5 with Interactive Brokers (IBKR) integration under active development.
You can read the full documentation [here](https://bbstrader.readthedocs.io/en/latest/index.html)
## Core Components
`bbstrader` is organized into several key modules, each designed to address specific aspects of the trading workflow:
### Backtesting Engine (`btengine`)
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.
### MetaTrader5 Module (`metatrader`)
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.
### Trading Strategies (`trading.strategies`)
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.
### Models Module (`models`)
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.
### Time Series Module (`tseries`)
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.
### Live Trading Engine (`trading`)
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.
### Interactive Brokers Module (`ibkr`)
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.
### Core Utilities (`core`)
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.
### Configuration (`config`)
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.
### Compatibility Layer (`compat`)
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.
## Getting Started
To begin using `bbstrader`, please ensure your system meets the following prerequisites and follow the installation steps.
### Prerequisites
* **Python**: Python 3.8+ is required.
* **MetaTrader 5 (MT5)**:
* The MetaTrader 5 platform must be installed on your system (primarily for Windows users needing live trading or direct MT5 interaction).
* An active trading account with a MetaTrader 5 broker. `bbstrader` currently supports:
* [Admirals Group AS](https://cabinet.a-partnership.com/visit/?bta=35537&brand=admiralmarkets) (for Stocks, ETFs, Indices, Commodities, Futures, Forex)
* [Just Global Markets Ltd.](https://one.justmarkets.link/a/tufvj0xugm/registration/trader) (for Stocks, Crypto, Indices, Commodities, Forex)
* [FTMO](https://trader.ftmo.com/?affiliates=JGmeuQqepAZLMcdOEQRp) (Proprietary Firm)
### Installation
It is highly recommended to install `bbstrader` in a virtual environment to manage dependencies effectively.
1. **Create and activate a virtual environment:**
* On macOS and Linux:
```bash
python3 -m venv venv
source venv/bin/activate
```
* On Windows:
```bash
python -m venv venv
venv\Scripts\activate
```
2. **Install `bbstrader`:**
* **For Windows users (with MetaTrader 5):**
To include the official MetaTrader 5 package (which is Windows-only), install using:
```bash
pip install bbstrader[MT5]
```
* **For macOS, Linux users, or Windows users not needing direct MT5 interaction:**
Install the base package. The `MetaTrader5` package will be mocked by our `compat` module, allowing development and use of non-MT5 specific features.
```bash
pip install bbstrader
```
With these steps completed, you are ready to explore the features and modules of `bbstrader`!
## Usage Examples
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.
### Connecting to MetaTrader 5 (Conceptual)
`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).
If you were to connect to MetaTrader 5 manually using the `MetaTrader5` library, it would look something like this:
```python
import MetaTrader5 as mt5
# Ensure the MetaTrader 5 terminal is running
# For Windows, specify the path to terminal64.exe
# For Linux/MacOS with Wine, specify the path and use mt5.wine_mode()
# Example for Windows:
# path_to_mt5 = r"C:\Program Files\MetaTrader 5\terminal64.exe"
# if not mt5.initialize(path=path_to_mt5, login=123456, server="YourServer", password="YourPassword"):
# For default path lookup (often sufficient if MT5 is installed and logged in):
if not mt5.initialize(login=123456, server="YourServer", password="YourPassword"):
print("initialize() failed, error code =", mt5.last_error())
quit()
# Display account information
account_info = mt5.account_info()
if account_info is not None:
print(account_info)
else:
print("Failed to get account info, error code =", mt5.last_error())
# ... your trading logic would go here ...
# Shutdown connection
mt5.shutdown()
```
**Note:** `bbstrader`'s `metatrader` module and execution scripts abstract this process, using configured credentials and settings.
### Programmatic Backtesting Example
You can run backtests on strategies programmatically. The following example demonstrates how to test the `sistbo` (Stock Index Short Term Buy Only) strategy:
```python
from bbstrader.trading.strategies import test_strategy
if __name__ == '__main__':
# Run backtesting for Stock Index Short Term Buy Only Strategy
# This function call will use default parameters for the 'sistbo' strategy
# and save results to the default 'data/results' directory.
test_strategy(strategy='sistbo')
```
This will typically output performance metrics and charts to a results directory.
### Backtesting Results





### Command-Line Interface (CLI) Examples
`bbstrader` provides a CLI for various operations, including running live strategies, backtests, and utilities like the trade copier.
#### CLI - Running a Live Strategy
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`.
1. **Create `execution.json`**:
Create the directory `~/.bbstrader/execution/` if it doesn't exist. Inside, create `execution.json` with content like this for an `SMAStrategy`:
```json
{
"SMAStrategy": {
"MY_MT5_ACCOUNT_1": {
"symbol_list": ["EURUSD", "GBPUSD"],
"trades_kwargs": {"magic": 12345, "comment": "SMAStrategy_Live"},
"short_window": 20,
"long_window": 50,
"time_frame": "H1",
"quantities": 0.1
}
}
}
```
Replace `MY_MT5_ACCOUNT_1` with your account identifier used in `bbstrader`'s configuration. Adjust strategy parameters as needed.
2. **Run the strategy via CLI**:
Open your terminal and run:
```bash
python -m bbstrader --run execution -s SMAStrategy -a MY_MT5_ACCOUNT_1
```
* `-s SMAStrategy`: Specifies the strategy class name to run.
* `-a MY_MT5_ACCOUNT_1`: Specifies the account name (must match a key in `execution.json` under the strategy).
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.
#### CLI - Running a Backtest
You can also initiate backtests via the CLI. This is useful for quick tests or integrating into automated scripts.
To see all available options for backtesting:
```bash
python -m bbstrader --run backtest --help
```
Example command to backtest an `SMAStrategy`:
```bash
python -m bbstrader --run backtest --strategy SMAStrategy
```
#### CLI - Trade Copier
`bbstrader` includes a trade copier utility to replicate trades between different MetaTrader 5 accounts.
To see the available options for the trade copier:
```bash
python -m bbstrader --run copier --help
```
This will display detailed instructions on how to specify source and target accounts, along with other relevant parameters for copying trades.
## Configuration
`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.
### User Configuration Directory: `~/.bbstrader/`
`bbstrader` uses a hidden directory in your user's home folder, `~/.bbstrader/`, to store user-specific files. This typically includes:
* `execution/execution.json`: For live strategy execution parameters.
* `logs/`: Default directory for log files.
* Potentially other configuration files for different modules in the future.
You may need to create the `~/.bbstrader/` directory and its subdirectories (like `execution/` or `logs/`) manually if they don't exist upon first use.
### Strategy Execution (`execution.json`)
* **Purpose**: Defines parameters for live strategy execution when using the `python -m bbstrader --run execution` command.
* **Default Location**: `~/.bbstrader/execution/execution.json`. You'll likely need to create this file and its parent directory.
* **Structure**:
* The file is a JSON object where top-level keys are strategy class names (e.g., `"SMAStrategy"`).
* 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).
* Under each account, you specify:
* `"symbol_list"`: A list of symbols the strategy will trade (e.g., `["EURUSD", "GBPUSD"]`).
* `"trades_kwargs"`: A dictionary for MetaTrader 5 specific order parameters, commonly including:
* `"magic"`: The magic number for orders placed by this strategy instance.
* `"comment"`: A comment for orders.
* Custom strategy parameters: Any other parameters required by your strategy's `__init__` method (e.g., `"short_window"`, `"long_window"`, `"time_frame"`, `"quantities"`).
* **Example**: Refer to the example in the "Usage Examples" -> "CLI - Running a Live Strategy" section.
### MetaTrader 5 Broker Paths (`bbstrader/config.py`)
* 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`.
* **Customization**:
* If your MT5 terminal is installed in a non-standard location, or you use a broker not listed, `bbstrader` might not find the terminal.
* Ideally, future versions might support environment variables or a user-specific configuration file to override these paths.
* 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.
* 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.
### Logging Configuration (`bbstrader/config.py`)
* **Setup**: The `config_logger` function in `bbstrader/config.py` sets up application-wide logging.
* **Log Files**:
* 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.
* The default file logging level is `INFO`.
* **Console Logging**:
* If enabled (usually by default for CLI operations), console logging is set to `DEBUG` level, providing more verbose output.
* **Customization**:
* 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).
* For programmatic use, you can re-configure logging after importing `bbstrader` modules if needed, though this might affect internal `bbstrader` logging.
### General Advice
* 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.
* Keep an eye on the `~/.bbstrader/` directory for any new configuration files or logs that might appear as you use different features.
## Documentation
For comprehensive information, including detailed API references, tutorials, and advanced guides for each module, please refer to our full documentation hosted on ReadTheDocs:
[**View the Full Documentation on ReadTheDocs**](https://bbstrader.readthedocs.io/en/latest/)
Additionally, the codebase is commented and includes docstrings, which can be a valuable resource for understanding the implementation details of specific functions and classes.
## Customization and Contribution
`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.
## Contributing to `bbstrader`
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:
### Ways to Contribute
- **Develop New Strategies**: Implement and share your unique trading strategies or models.
- **Enhance Existing Modules**: Optimize the performance, extend the functionality, or improve the usability of existing modules.
- **Report Bugs**: Identify and report bugs to help us improve the system's stability and performance. (See "Reporting Issues" below).
- **Improve Documentation**: Contribute to the project's documentation for clearer guidance and better usability.
- **Share Insights and Best Practices**: Provide examples, tutorials, or best practices on utilizing `bbstrader` effectively.
- **Request Features**: Suggest new functionalities or improvements. (See "Requesting Features" below).
### Reporting Issues
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.
[**Report an Issue on GitHub**](https://github.com/bbalouki/bbstrader/issues)
Please include the following in your bug report:
* **Clear Title**: A concise and descriptive title for the issue.
* **Steps to Reproduce**: Detailed steps that consistently reproduce the bug.
* **Expected Behavior**: What you expected to happen.
* **Actual Behavior**: What actually happened.
* **Environment Details**:
* Python version (e.g., `python --version`).
* `bbstrader` version (e.g., `pip show bbstrader`).
* Operating System (e.g., Windows 10, Ubuntu 22.04, macOS Sonoma).
* **Logs and Error Messages**: Any relevant console output, error messages, or snippets from log files (`~/.bbstrader/logs/`). Please use code blocks for formatting.
### Requesting Features
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.
[**Request a Feature on GitHub**](https://github.com/bbalouki/bbstrader/issues)
When submitting a feature request, please:
* **Clear Title**: A concise and descriptive title for the feature.
* **Describe the Feature**: Clearly explain the proposed functionality and its potential benefits to users.
* **Use Case / Problem Solved**: Describe the specific scenario or problem this feature would address.
* **Suggested Implementation (Optional)**: If you have ideas on how the feature could be implemented, feel free to share them.
### How to Get Started
1. **Fork the Repository**: Start by forking the `bbstrader` repository to your GitHub account.
2. **Clone Your Fork**: Clone your forked repository to your local machine to start making changes.
3. **Set Up Your Development Environment**: Ensure you have the necessary development environment set up, including Python, MetaTrader 5, and any dependencies.
4. **Create a New Branch**: Make your changes in a new git branch, branching off from the main branch.
5. **Implement Your Changes**: Work on bug fixes, features, or documentation improvements.
6. **Test Your Changes**: Ensure your changes do not introduce new issues and that they work as intended.
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.
### Contribution Guidelines
Please adhere to the following guidelines to ensure a smooth contribution process:
- **Follow the Coding Standards**: Write clean, readable code and follow the coding conventions used throughout the project.
- **Document Your Changes**: Add comments and update the README.md files as necessary to explain your changes or additions.
- **Respect the License**: All contributions are subject to the MIT License under which `bbstrader` is distributed.
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.
## Disclaimer
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.
## License
`bbstrader` is open source and available under the MIT License.
Raw data
{
"_id": null,
"home_page": "https://github.com/bbalouki/bbstrader",
"name": "bbstrader",
"maintainer": "Bertin Balouki SIMYELI",
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "Finance, Toolkit, Financial, Analysis, Fundamental, Quantitative, Database, Equities, Currencies, Economics, ETFs, Funds, Indices, Moneymarkets, Commodities, Futures, CFDs, Derivatives, Trading, Investing, Portfolio, Optimization, Performance",
"author": "Bertin Balouki SIMYELI",
"author_email": "<bertin@bbstrader.com>",
"download_url": "https://files.pythonhosted.org/packages/fb/3f/5f38b8ac6549caa349ccee7d21ed8ca4c7136dfbb94dc4c3f7bb220b9d64/bbstrader-0.3.2.tar.gz",
"platform": null,
"description": "# Simplified Investment & Trading Toolkit\n[](https://bbstrader.readthedocs.io/en/latest/?badge=latest)\n[](https://pypi.org/project/bbstrader/)\n[](https://pypi.python.org/pypi/bbstrader)\n[](https://pypi.org/project/bbstrader/)\n[](https://pepy.tech/projects/bbstrader)\n[](https://www.codefactor.io/repository/github/bbalouki/bbstrader)\n[](https://www.linkedin.com/in/bertin-balouki-simyeli-15b17a1a6/)\n[](https://paypal.me/bertinbalouki?country.x=SN&locale.x=en_US)\n\n[Dcoumentation](https://bbstrader.readthedocs.io/en/latest/index.html)\n\n## Table of Contents\n- [Overview](#overview)\n- [Features](#features)\n- [Core Components](#core-components)\n- [Getting Started](#getting-started)\n- [Usage Examples](#usage-examples)\n- [Configuration](#configuration)\n- [Documentation](#documentation)\n- [Customization and Contribution](#customization-and-contribution)\n- [Contributing to `bbstrader`](#contributing-to-bbstrader)\n- [Disclaimer](#disclaimer)\n- [License](#license)\n\n`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.\n\n## Overview\n\n`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.\n\n## Features\n\n- **Comprehensive Backtesting**: Rigorously test strategies with historical data to optimize performance before live deployment.\n- **Integrated Risk Management**: Utilize sophisticated techniques to manage risk and adapt to fluctuating market conditions.\n- **Automated Trading Execution**: Seamlessly execute trades on MT5, with real-time management of orders and positions. (IBKR support coming soon).\n- **Trade Copier**: Effortlessly replicate trades across multiple accounts.\n- **Flexible Strategy Framework**: Customize existing strategies or develop new ones with our adaptable, modular architecture.\n- **Advanced Time Series Analysis**: Uncover market patterns and insights with powerful tools for in-depth financial data analysis.\n- **Multi-Platform Support**: Designed for MetaTrader 5 with Interactive Brokers (IBKR) integration under active development.\n\nYou can read the full documentation [here](https://bbstrader.readthedocs.io/en/latest/index.html)\n\n## Core Components\n\n`bbstrader` is organized into several key modules, each designed to address specific aspects of the trading workflow:\n\n### Backtesting Engine (`btengine`)\nThe **`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.\n\n### MetaTrader5 Module (`metatrader`)\nThis **`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.\n\n### Trading Strategies (`trading.strategies`)\nThe **`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.\n\n### Models Module (`models`)\nThe **`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.\n\n### Time Series Module (`tseries`)\nSpecialized 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.\n\n### Live Trading Engine (`trading`)\nThe **`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.\n\n### Interactive Brokers Module (`ibkr`)\nCurrently 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.\n\n### Core Utilities (`core`)\nThe **`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.\n\n### Configuration (`config`)\nThis **`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.\n\n### Compatibility Layer (`compat`)\nThe **`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.\n\n## Getting Started\n\nTo begin using `bbstrader`, please ensure your system meets the following prerequisites and follow the installation steps.\n\n### Prerequisites\n\n* **Python**: Python 3.8+ is required.\n* **MetaTrader 5 (MT5)**:\n * The MetaTrader 5 platform must be installed on your system (primarily for Windows users needing live trading or direct MT5 interaction).\n * An active trading account with a MetaTrader 5 broker. `bbstrader` currently supports:\n * [Admirals Group AS](https://cabinet.a-partnership.com/visit/?bta=35537&brand=admiralmarkets) (for Stocks, ETFs, Indices, Commodities, Futures, Forex)\n * [Just Global Markets Ltd.](https://one.justmarkets.link/a/tufvj0xugm/registration/trader) (for Stocks, Crypto, Indices, Commodities, Forex)\n * [FTMO](https://trader.ftmo.com/?affiliates=JGmeuQqepAZLMcdOEQRp) (Proprietary Firm)\n\n\n### Installation\n\nIt is highly recommended to install `bbstrader` in a virtual environment to manage dependencies effectively.\n\n1. **Create and activate a virtual environment:**\n\n * On macOS and Linux:\n ```bash\n python3 -m venv venv\n source venv/bin/activate\n ```\n * On Windows:\n ```bash\n python -m venv venv\n venv\\Scripts\\activate\n ```\n\n2. **Install `bbstrader`:**\n\n * **For Windows users (with MetaTrader 5):**\n To include the official MetaTrader 5 package (which is Windows-only), install using:\n ```bash\n pip install bbstrader[MT5]\n ```\n * **For macOS, Linux users, or Windows users not needing direct MT5 interaction:**\n Install the base package. The `MetaTrader5` package will be mocked by our `compat` module, allowing development and use of non-MT5 specific features.\n ```bash\n pip install bbstrader\n ```\n\nWith these steps completed, you are ready to explore the features and modules of `bbstrader`!\n\n## Usage Examples\n\nThis 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.\n\n### Connecting to MetaTrader 5 (Conceptual)\n\n`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).\n\nIf you were to connect to MetaTrader 5 manually using the `MetaTrader5` library, it would look something like this:\n\n```python\nimport MetaTrader5 as mt5\n\n# Ensure the MetaTrader 5 terminal is running\n# For Windows, specify the path to terminal64.exe\n# For Linux/MacOS with Wine, specify the path and use mt5.wine_mode()\n\n# Example for Windows:\n# path_to_mt5 = r\"C:\\Program Files\\MetaTrader 5\\terminal64.exe\"\n# if not mt5.initialize(path=path_to_mt5, login=123456, server=\"YourServer\", password=\"YourPassword\"):\n# For default path lookup (often sufficient if MT5 is installed and logged in):\nif not mt5.initialize(login=123456, server=\"YourServer\", password=\"YourPassword\"):\n print(\"initialize() failed, error code =\", mt5.last_error())\n quit()\n\n# Display account information\naccount_info = mt5.account_info()\nif account_info is not None:\n print(account_info)\nelse:\n print(\"Failed to get account info, error code =\", mt5.last_error())\n\n# ... your trading logic would go here ...\n\n# Shutdown connection\nmt5.shutdown()\n```\n**Note:** `bbstrader`'s `metatrader` module and execution scripts abstract this process, using configured credentials and settings.\n\n### Programmatic Backtesting Example\n\nYou can run backtests on strategies programmatically. The following example demonstrates how to test the `sistbo` (Stock Index Short Term Buy Only) strategy:\n\n```python\nfrom bbstrader.trading.strategies import test_strategy\n\nif __name__ == '__main__':\n # Run backtesting for Stock Index Short Term Buy Only Strategy\n # This function call will use default parameters for the 'sistbo' strategy\n # and save results to the default 'data/results' directory.\n test_strategy(strategy='sistbo')\n```\nThis will typically output performance metrics and charts to a results directory.\n### Backtesting Results\n\n\n\n\n\n\n### Command-Line Interface (CLI) Examples\n\n`bbstrader` provides a CLI for various operations, including running live strategies, backtests, and utilities like the trade copier.\n\n#### CLI - Running a Live Strategy\n\nTo 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`.\n\n1. **Create `execution.json`**:\n Create the directory `~/.bbstrader/execution/` if it doesn't exist. Inside, create `execution.json` with content like this for an `SMAStrategy`:\n\n ```json\n {\n \"SMAStrategy\": {\n \"MY_MT5_ACCOUNT_1\": {\n \"symbol_list\": [\"EURUSD\", \"GBPUSD\"],\n \"trades_kwargs\": {\"magic\": 12345, \"comment\": \"SMAStrategy_Live\"},\n \"short_window\": 20,\n \"long_window\": 50,\n \"time_frame\": \"H1\",\n \"quantities\": 0.1\n }\n }\n }\n ```\n Replace `MY_MT5_ACCOUNT_1` with your account identifier used in `bbstrader`'s configuration. Adjust strategy parameters as needed.\n\n2. **Run the strategy via CLI**:\n Open your terminal and run:\n ```bash\n python -m bbstrader --run execution -s SMAStrategy -a MY_MT5_ACCOUNT_1\n ```\n * `-s SMAStrategy`: Specifies the strategy class name to run.\n * `-a MY_MT5_ACCOUNT_1`: Specifies the account name (must match a key in `execution.json` under the strategy).\n\n 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.\n\n#### CLI - Running a Backtest\n\nYou can also initiate backtests via the CLI. This is useful for quick tests or integrating into automated scripts.\n\nTo see all available options for backtesting:\n```bash\npython -m bbstrader --run backtest --help\n```\n\nExample command to backtest an `SMAStrategy`:\n```bash\npython -m bbstrader --run backtest --strategy SMAStrategy\n```\n\n#### CLI - Trade Copier\n\n`bbstrader` includes a trade copier utility to replicate trades between different MetaTrader 5 accounts.\n\nTo see the available options for the trade copier:\n```bash\npython -m bbstrader --run copier --help\n```\nThis will display detailed instructions on how to specify source and target accounts, along with other relevant parameters for copying trades.\n\n## Configuration\n\n`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.\n\n### User Configuration Directory: `~/.bbstrader/`\n\n`bbstrader` uses a hidden directory in your user's home folder, `~/.bbstrader/`, to store user-specific files. This typically includes:\n* `execution/execution.json`: For live strategy execution parameters.\n* `logs/`: Default directory for log files.\n* Potentially other configuration files for different modules in the future.\n\nYou may need to create the `~/.bbstrader/` directory and its subdirectories (like `execution/` or `logs/`) manually if they don't exist upon first use.\n\n### Strategy Execution (`execution.json`)\n\n* **Purpose**: Defines parameters for live strategy execution when using the `python -m bbstrader --run execution` command.\n* **Default Location**: `~/.bbstrader/execution/execution.json`. You'll likely need to create this file and its parent directory.\n* **Structure**:\n * The file is a JSON object where top-level keys are strategy class names (e.g., `\"SMAStrategy\"`).\n * 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).\n * Under each account, you specify:\n * `\"symbol_list\"`: A list of symbols the strategy will trade (e.g., `[\"EURUSD\", \"GBPUSD\"]`).\n * `\"trades_kwargs\"`: A dictionary for MetaTrader 5 specific order parameters, commonly including:\n * `\"magic\"`: The magic number for orders placed by this strategy instance.\n * `\"comment\"`: A comment for orders.\n * Custom strategy parameters: Any other parameters required by your strategy's `__init__` method (e.g., `\"short_window\"`, `\"long_window\"`, `\"time_frame\"`, `\"quantities\"`).\n* **Example**: Refer to the example in the \"Usage Examples\" -> \"CLI - Running a Live Strategy\" section.\n\n### MetaTrader 5 Broker Paths (`bbstrader/config.py`)\n\n* 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`.\n* **Customization**:\n * If your MT5 terminal is installed in a non-standard location, or you use a broker not listed, `bbstrader` might not find the terminal.\n * Ideally, future versions might support environment variables or a user-specific configuration file to override these paths.\n * 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.\n * 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.\n\n### Logging Configuration (`bbstrader/config.py`)\n\n* **Setup**: The `config_logger` function in `bbstrader/config.py` sets up application-wide logging.\n* **Log Files**:\n * 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.\n * The default file logging level is `INFO`.\n* **Console Logging**:\n * If enabled (usually by default for CLI operations), console logging is set to `DEBUG` level, providing more verbose output.\n* **Customization**:\n * 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).\n * For programmatic use, you can re-configure logging after importing `bbstrader` modules if needed, though this might affect internal `bbstrader` logging.\n\n### General Advice\n\n* 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.\n* Keep an eye on the `~/.bbstrader/` directory for any new configuration files or logs that might appear as you use different features.\n\n## Documentation\n\nFor comprehensive information, including detailed API references, tutorials, and advanced guides for each module, please refer to our full documentation hosted on ReadTheDocs:\n\n[**View the Full Documentation on ReadTheDocs**](https://bbstrader.readthedocs.io/en/latest/)\n\nAdditionally, the codebase is commented and includes docstrings, which can be a valuable resource for understanding the implementation details of specific functions and classes.\n\n## Customization and Contribution\n\n`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.\n\n## Contributing to `bbstrader`\n\nWe 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:\n\n### Ways to Contribute\n\n- **Develop New Strategies**: Implement and share your unique trading strategies or models.\n- **Enhance Existing Modules**: Optimize the performance, extend the functionality, or improve the usability of existing modules.\n- **Report Bugs**: Identify and report bugs to help us improve the system's stability and performance. (See \"Reporting Issues\" below).\n- **Improve Documentation**: Contribute to the project's documentation for clearer guidance and better usability.\n- **Share Insights and Best Practices**: Provide examples, tutorials, or best practices on utilizing `bbstrader` effectively.\n- **Request Features**: Suggest new functionalities or improvements. (See \"Requesting Features\" below).\n\n### Reporting Issues\n\nIf 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.\n\n[**Report an Issue on GitHub**](https://github.com/bbalouki/bbstrader/issues)\n\nPlease include the following in your bug report:\n\n* **Clear Title**: A concise and descriptive title for the issue.\n* **Steps to Reproduce**: Detailed steps that consistently reproduce the bug.\n* **Expected Behavior**: What you expected to happen.\n* **Actual Behavior**: What actually happened.\n* **Environment Details**:\n * Python version (e.g., `python --version`).\n * `bbstrader` version (e.g., `pip show bbstrader`).\n * Operating System (e.g., Windows 10, Ubuntu 22.04, macOS Sonoma).\n* **Logs and Error Messages**: Any relevant console output, error messages, or snippets from log files (`~/.bbstrader/logs/`). Please use code blocks for formatting.\n\n### Requesting Features\n\nWe 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.\n\n[**Request a Feature on GitHub**](https://github.com/bbalouki/bbstrader/issues)\n\nWhen submitting a feature request, please:\n\n* **Clear Title**: A concise and descriptive title for the feature.\n* **Describe the Feature**: Clearly explain the proposed functionality and its potential benefits to users.\n* **Use Case / Problem Solved**: Describe the specific scenario or problem this feature would address.\n* **Suggested Implementation (Optional)**: If you have ideas on how the feature could be implemented, feel free to share them.\n\n### How to Get Started\n\n1. **Fork the Repository**: Start by forking the `bbstrader` repository to your GitHub account.\n2. **Clone Your Fork**: Clone your forked repository to your local machine to start making changes.\n3. **Set Up Your Development Environment**: Ensure you have the necessary development environment set up, including Python, MetaTrader 5, and any dependencies.\n4. **Create a New Branch**: Make your changes in a new git branch, branching off from the main branch.\n5. **Implement Your Changes**: Work on bug fixes, features, or documentation improvements.\n6. **Test Your Changes**: Ensure your changes do not introduce new issues and that they work as intended.\n7. **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.\n\n### Contribution Guidelines\n\nPlease adhere to the following guidelines to ensure a smooth contribution process:\n\n- **Follow the Coding Standards**: Write clean, readable code and follow the coding conventions used throughout the project.\n- **Document Your Changes**: Add comments and update the README.md files as necessary to explain your changes or additions.\n- **Respect the License**: All contributions are subject to the MIT License under which `bbstrader` is distributed.\n\nWe'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.\n\n\n## Disclaimer\n\nTrading 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.\n\n## License\n`bbstrader` is open source and available under the MIT License.\n",
"bugtrack_url": null,
"license": "The MIT License (MIT)",
"summary": "Simplified Investment & Trading Toolkit",
"version": "0.3.2",
"project_urls": {
"Documentation": "https://bbstrader.readthedocs.io/en/latest/",
"Download": "https://pypi.org/project/bbstrader/",
"Homepage": "https://github.com/bbalouki/bbstrader",
"Source Code": "https://github.com/bbalouki/bbstrader"
},
"split_keywords": [
"finance",
" toolkit",
" financial",
" analysis",
" fundamental",
" quantitative",
" database",
" equities",
" currencies",
" economics",
" etfs",
" funds",
" indices",
" moneymarkets",
" commodities",
" futures",
" cfds",
" derivatives",
" trading",
" investing",
" portfolio",
" optimization",
" performance"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "fbff0cee4eedcac7e04f5346123600181ca10e1abb97135b787d50e15042dac2",
"md5": "380d6b6535818675ccee3f1c935edaf4",
"sha256": "dd11ee2b25de4e154304aa5fc93540c1a99e1bc64ea4b01805479a0ba3a34570"
},
"downloads": -1,
"filename": "bbstrader-0.3.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "380d6b6535818675ccee3f1c935edaf4",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 178233,
"upload_time": "2025-07-19T10:14:33",
"upload_time_iso_8601": "2025-07-19T10:14:33.572037Z",
"url": "https://files.pythonhosted.org/packages/fb/ff/0cee4eedcac7e04f5346123600181ca10e1abb97135b787d50e15042dac2/bbstrader-0.3.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "fb3f5f38b8ac6549caa349ccee7d21ed8ca4c7136dfbb94dc4c3f7bb220b9d64",
"md5": "0a3c26b40dc6eae133a0c01e21b3957e",
"sha256": "cdecc2615afa4c97cc6c6a35cd84220fdd898025c30b9bd37ac96d6efb8bbb38"
},
"downloads": -1,
"filename": "bbstrader-0.3.2.tar.gz",
"has_sig": false,
"md5_digest": "0a3c26b40dc6eae133a0c01e21b3957e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 174148,
"upload_time": "2025-07-19T10:14:35",
"upload_time_iso_8601": "2025-07-19T10:14:35.025970Z",
"url": "https://files.pythonhosted.org/packages/fb/3f/5f38b8ac6549caa349ccee7d21ed8ca4c7136dfbb94dc4c3f7bb220b9d64/bbstrader-0.3.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-19 10:14:35",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "bbalouki",
"github_project": "bbstrader",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "alphalens-reloaded",
"specs": [
[
">=",
"0.4.5"
]
]
},
{
"name": "beautifulsoup4",
"specs": [
[
">=",
"4.13.1"
]
]
},
{
"name": "colorama",
"specs": [
[
">=",
"0.4.6"
]
]
},
{
"name": "CurrencyConverter",
"specs": [
[
">=",
"0.18.2"
]
]
},
{
"name": "dash",
"specs": [
[
">=",
"2.18.2"
]
]
},
{
"name": "eodhd",
"specs": [
[
">=",
"1.0.32"
]
]
},
{
"name": "exchange-calendars",
"specs": [
[
">=",
"4.9"
]
]
},
{
"name": "filterpy",
"specs": [
[
">=",
"1.4.5"
]
]
},
{
"name": "financetoolkit",
"specs": [
[
">=",
"1.9.9"
]
]
},
{
"name": "ipython",
"specs": [
[
">=",
"8.32.0"
]
]
},
{
"name": "lightgbm",
"specs": [
[
">=",
"4.5.0"
]
]
},
{
"name": "nltk",
"specs": [
[
">=",
"3.9.1"
]
]
},
{
"name": "notify-py",
"specs": [
[
">=",
"0.3.43"
]
]
},
{
"name": "numpy",
"specs": [
[
"<",
"2.0.0"
],
[
">=",
"1.26.0"
]
]
},
{
"name": "pandas_ta",
"specs": [
[
">=",
"0.3.14b0"
]
]
},
{
"name": "praw",
"specs": [
[
">=",
"7.8.1"
]
]
},
{
"name": "pyfiglet",
"specs": [
[
">=",
"1.0.2"
]
]
},
{
"name": "pykalman",
"specs": [
[
">=",
"0.10.1"
]
]
},
{
"name": "pyportfolioopt",
"specs": [
[
">=",
"1.5.6"
]
]
},
{
"name": "python-dotenv",
"specs": [
[
">=",
"1.0.1"
]
]
},
{
"name": "python-telegram-bot",
"specs": [
[
">=",
"21.10"
]
]
},
{
"name": "PyYAML",
"specs": [
[
">=",
"6.0.2"
]
]
},
{
"name": "QuantStats",
"specs": [
[
">=",
"0.0.64"
]
]
},
{
"name": "scikit-learn",
"specs": [
[
">=",
"1.6.1"
]
]
},
{
"name": "seaborn",
"specs": [
[
">=",
"0.13.2"
]
]
},
{
"name": "spacy",
"specs": [
[
">=",
"3.8.4"
]
]
},
{
"name": "statsmodels",
"specs": [
[
">=",
"0.14.4"
]
]
},
{
"name": "sumy",
"specs": [
[
">=",
"0.11.0"
]
]
},
{
"name": "tables",
"specs": [
[
">=",
"3.10.2"
]
]
},
{
"name": "tabulate",
"specs": [
[
">=",
"0.9.0"
]
]
},
{
"name": "textblob",
"specs": [
[
">=",
"0.19.0"
]
]
},
{
"name": "tqdm",
"specs": [
[
">=",
"4.67.1"
]
]
},
{
"name": "tweepy",
"specs": [
[
">=",
"4.15.0"
]
]
},
{
"name": "vaderSentiment",
"specs": [
[
">=",
"3.3.2"
]
]
},
{
"name": "yfinance",
"specs": [
[
">=",
"0.2.55"
]
]
}
],
"lcname": "bbstrader"
}