
Product
Introducing Tier 1 Reachability: Precision CVE Triage for Enterprise Teams
Socket’s new Tier 1 Reachability filters out up to 80% of irrelevant CVEs, so security teams can focus on the vulnerabilities that matter.
bbstrader
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.
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.
You can read the full documentation here
bbstrader
is organized into several key modules, each designed to address specific aspects of the trading workflow:
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.
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
)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
)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.
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.
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.
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
)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.
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.
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.
To begin using bbstrader
, please ensure your system meets the following prerequisites and follow the installation steps.
bbstrader
currently supports:
It is highly recommended to install bbstrader
in a virtual environment to manage dependencies effectively.
Create and activate a virtual environment:
python3 -m venv venv
source venv/bin/activate
python -m venv venv
venv\Scripts\activate
Install bbstrader
:
pip install bbstrader[MT5]
MetaTrader5
package will be mocked by our compat
module, allowing development and use of non-MT5 specific features.
pip install bbstrader
With these steps completed, you are ready to explore the features and modules of bbstrader
!
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.
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:
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.
You can run backtests on strategies programmatically. The following example demonstrates how to test the sistbo
(Stock Index Short Term Buy Only) strategy:
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.
bbstrader
provides a CLI for various operations, including running live strategies, backtests, and utilities like the trade copier.
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
.
Create execution.json
:
Create the directory ~/.bbstrader/execution/
if it doesn't exist. Inside, create execution.json
with content like this for an SMAStrategy
:
{
"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.
Run the strategy via CLI: Open your terminal and run:
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.
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:
python -m bbstrader --run backtest --help
Example command to backtest an SMAStrategy
:
python -m bbstrader --run backtest --strategy SMAStrategy
bbstrader
includes a trade copier utility to replicate trades between different MetaTrader 5 accounts.
To see the available options for the trade copier:
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.
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.
~/.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.You may need to create the ~/.bbstrader/
directory and its subdirectories (like execution/
or logs/
) manually if they don't exist upon first use.
execution.json
)python -m bbstrader --run execution
command.~/.bbstrader/execution/execution.json
. You'll likely need to create this file and its parent directory."SMAStrategy"
)."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)."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.__init__
method (e.g., "short_window"
, "long_window"
, "time_frame"
, "quantities"
).bbstrader/config.py
)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
.bbstrader
might not find the terminal.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.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.bbstrader/config.py
)config_logger
function in bbstrader/config.py
sets up application-wide logging.~/.bbstrader/logs/
directory (e.g., bbstrader.log
). The exact path might depend on how config_logger
is invoked by the application.INFO
.DEBUG
level, providing more verbose output.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).bbstrader
modules if needed, though this might affect internal bbstrader
logging.bbstrader
documentation (if available) or consult the source code of the respective modules.~/.bbstrader/
directory for any new configuration files or logs that might appear as you use different features.For comprehensive information, including detailed API references, tutorials, and advanced guides for each module, please refer to our full documentation hosted on ReadTheDocs:
Additionally, the codebase is commented and includes docstrings, which can be a valuable resource for understanding the implementation details of specific functions and classes.
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.
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:
bbstrader
effectively.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.
Please include the following in your bug report:
python --version
).bbstrader
version (e.g., pip show bbstrader
).~/.bbstrader/logs/
). Please use code blocks for formatting.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.
When submitting a feature request, please:
bbstrader
repository to your GitHub account.bbstrader
repository. Include a clear description of the changes and any other relevant information.Please adhere to the following guidelines to ensure a smooth contribution process:
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.
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.
bbstrader
is open source and available under the MIT License.
FAQs
Simplified Investment & Trading Toolkit
We found that bbstrader demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket’s new Tier 1 Reachability filters out up to 80% of irrelevant CVEs, so security teams can focus on the vulnerabilities that matter.
Research
/Security News
Ongoing npm supply chain attack spreads to DuckDB: multiple packages compromised with the same wallet-drainer malware.
Security News
The MCP Steering Committee has launched the official MCP Registry in preview, a central hub for discovering and publishing MCP servers.