bbstrader.core¶
Shared utilities used across the rest of the package: the venue-neutral Broker execution
abstraction (with the in-memory PaperBroker), data structures/logging, and built-in vectorized
indicators (SMA, EMA, RSI, ATR, Bollinger Bands, MACD, z-score).
core ¶
Overview¶
The Core Module provides the fundamental building blocks and abstract base classes for the trading system. It defines the essential components that are extended by other modules to create a complete trading application, ensuring a consistent and modular architecture.
Features¶
- Abstract Base Classes: Defines the interfaces for key components like data handlers and strategies, promoting a standardized approach to development.
- Modularity: Enforces a modular design by providing a clear separation of concerns between data handling, strategy logic, and execution.
- Extensibility: Designed to be easily extended with concrete implementations, allowing for the creation of custom data sources and trading strategies.
Components¶
- Data: Contains the abstract base class
DataHandler, which defines the interface for managing market data from various sources. - Strategy: Contains the abstract base class
Strategy, which provides the framework for developing trading strategies.
This module contains the abstract classes that form the foundation of the trading system.
Implementations of these classes can be found in other modules like btengine and trading.
BrokerOrder
dataclass
¶
BrokerOrder(symbol: str, side: OrderSide, quantity: float, order_type: OrderType = OrderType.MARKET, price: Optional[float] = None, id: Optional[int] = None)
A venue-neutral order request and its assigned id once submitted.
BrokerPosition
dataclass
¶
An open position: signed quantity and volume-weighted average price.
AccountInfo
dataclass
¶
A snapshot of account cash, mark-to-market equity and currency.
Broker ¶
Bases: ABC
The execution contract every venue adapter implements.
connect
abstractmethod
¶
disconnect
abstractmethod
¶
account
abstractmethod
¶
get_price
abstractmethod
¶
Return the latest market price for symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The instrument to price. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The latest price. |
submit_order
abstractmethod
¶
Submit order to the venue and return it with venue fields set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
BrokerOrder
|
The order to submit. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BrokerOrder |
BrokerOrder
|
The submitted order, populated with its assigned id. |
Source code in src/bbstrader/core/broker.py
positions
abstractmethod
¶
PaperBroker ¶
Bases: Broker
An in-memory simulated broker with immediate market fills.
Maintains cash, positions (volume-weighted average price) and an order log.
Prices are set with :meth:set_price; market orders fill at the current
price, limit/stop orders rest until :meth:set_price crosses their level.
Initialise the paper broker with starting cash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cash
|
float
|
The opening cash balance. |
100000.0
|
currency
|
str
|
The account currency code. |
'USD'
|
Source code in src/bbstrader/core/broker.py
connect ¶
disconnect ¶
set_price ¶
Update the market price and trigger any resting orders it crosses.
get_price ¶
Return the last price set for symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The instrument to price. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The most recently set price. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no price has been set for |
Source code in src/bbstrader/core/broker.py
account ¶
Return the account snapshot (cash, mark-to-market equity, currency).
equity ¶
Return cash plus the mark-to-market value of all open positions.
Source code in src/bbstrader/core/broker.py
positions ¶
orders ¶
submit_order ¶
Submit an order, filling market orders immediately at the set price.
Market orders fill at order.price or the current market price;
limit/stop orders rest and fill when :meth:set_price crosses them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
BrokerOrder
|
The order to submit. Its |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BrokerOrder |
BrokerOrder
|
The same order with its assigned |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/bbstrader/core/broker.py
FmpNews ¶
Bases: object
FmpNews is responsible for retrieving financial news, press releases, and articles from Financial Modeling Prep (FMP).
FmpNews provides methods to fetch the latest stock, crypto, forex, and general financial news,
as well as financial articles and press releases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api
|
str
|
The API key for accessing FMP's news data. |
required |
Example
fmp_news = FmpNews(api="your_api_key_here")
Source code in src/bbstrader/core/data.py
get_articles ¶
Fetch FMP articles with their HTML content stripped to plain text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
Any
|
Optional |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: Records with |
List[Dict[str, Any]]
|
(plain text) and |
Source code in src/bbstrader/core/data.py
get_releases ¶
Fetch the latest FMP press releases, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The press-release records. |
Source code in src/bbstrader/core/data.py
get_stock_news ¶
Fetch the latest FMP stock news, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The stock-news records. |
Source code in src/bbstrader/core/data.py
get_crypto_news ¶
Fetch the latest FMP crypto news, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The crypto-news records. |
Source code in src/bbstrader/core/data.py
get_forex_news ¶
Fetch the latest FMP forex news, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The forex-news records. |
Source code in src/bbstrader/core/data.py
parse_news ¶
Flatten and date-filter raw news records into text strings.
Keeps records published within the start/end window and, when a
symbol is given, only those mentioning it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
news
|
List[Dict[str, Any]]
|
The raw records to parse. |
required |
symbol
|
Optional[str]
|
Restrict to records mentioning this symbol. |
None
|
kwargs
|
Any
|
Optional |
{}
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: One flattened text string per matching record. |
Source code in src/bbstrader/core/data.py
get_latest_articles ¶
get_latest_articles(articles: Optional[List[Dict[str, Any]]] = None, save: bool = False, **kwargs: Any) -> List[Dict[str, Any]]
Return the latest FMP articles, using a local CSV cache when fresh.
Reads latest_fmp_articles.csv if present and recent enough; otherwise
downloads fresh articles and, when save is set, refreshes the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
articles
|
Optional[List[Dict[str, Any]]]
|
Pre-fetched articles to use instead of reading the cache or downloading. |
None
|
save
|
bool
|
When True, persist the fetched articles to the cache CSV. |
False
|
kwargs
|
Any
|
Optional |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The latest article records. |
Source code in src/bbstrader/core/data.py
get_news ¶
get_news(query: str, source: str = 'articles', articles: Optional[List[Dict[str, Any]]] = None, symbol: Optional[str] = None, **kwargs: Any) -> List[str]
Retrieves relevant financial news based on the specified source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The search query or keyword for filtering news, may also be a ticker. |
required |
source
|
str
|
The news source to retrieve from. Defaults to "articles". Available options: "articles", "releases", "stock", "crypto", "forex". |
'articles'
|
articles
|
list
|
List of pre-fetched articles to use when source="articles". Defaults to None. |
None
|
symbol
|
str
|
The financial asset symbol (e.g., "AAPL" for stocks, "BTC" for crypto). Defaults to None. |
None
|
**kwargs
|
dict
|
Additional arguments required for fetching news data. May include: - start (str): The start period for news retrieval (YYY-MM-DD) - end (str): The end period for news retrieval (YYY-MM-DD) - page (int): The number of page to load for each news - limit (int): Maximum Responses per API Call |
{}
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[dict]: A list of filtered news articles relevant to the query. Returns an empty list if no relevant news is found. |
Source code in src/bbstrader/core/data.py
FinancialNews ¶
Bases: object
The FinancialNews class provides methods to fetch financial news, articles, and discussions from various sources such as Yahoo Finance, Google Finance, Reddit, Coindesk and Twitter. It also supports retrieving news using Financial Modeling Prep (FMP).
get_yahoo_finance_news ¶
Fetches recent Yahoo Finance news headlines for a given financial asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The asset symbol or name (e.g., "AAPL"). |
required |
asset_type
|
str
|
The type of asset (e.g., "stock", "etf"). Defaults to "stock", supported types include: - "stock": Stock symbols (e.g., AAPL, MSFT) - "etf": Exchange-traded funds (e.g., SPY, QQQ) - "future": Futures contracts (e.g., CL=F for crude oil) - "forex": Forex pairs (e.g., EURUSD=X, USDJPY=X) - "crypto": Cryptocurrency pairs (e.g., BTC-USD, ETH-USD) - "index": Stock market indices (e.g., ^GSPC for S&P 500) |
'stock'
|
n_news
|
int
|
The number of news headlines to return. Defaults to 10. |
10
|
Note
For commotities and bonds, use the "Future" asset type.
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of Yahoo Finance news headlines relevant to the query. |
Source code in src/bbstrader/core/data.py
get_google_finance_news ¶
Fetches recent Google Finance news headlines for a given financial asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The asset symbol or name (e.g., "AAPL"). |
required |
asset_type
|
str
|
The type of asset (e.g., "stock", "crypto"). Defaults to "stock". Supported types include: - "stock": Stock symbols (e.g., AAPL, MSFT) - "etf": Exchange-traded funds (e.g., SPY, QQQ) - "future": Futures contracts (e.g., CL=F or crude oil) - "forex": Forex pairs (e.g., EURUSD, USDJPY) - "crypto": Cryptocurrency pairs (e.g., BTCUSD, ETHUSD) |
'stock'
|
n_news
|
int
|
The number of news headlines to return. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of Google Finance news headlines relevant to the query. |
Source code in src/bbstrader/core/data.py
get_reddit_posts ¶
get_reddit_posts(symbol: str, client_id=None, client_secret=None, user_agent=None, asset_class='stock', n_posts=10) -> List[str]
Fetches recent Reddit posts related to a financial asset.
This method queries relevant subreddits for posts mentioning the specified symbol and returns posts based on the selected asset class (e.g., stock, forex, crypto). The function uses the PRAW library to interact with Reddit's API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The financial asset's symbol or name to search for. |
required |
client_id
|
str
|
Reddit API client ID for authentication. |
None
|
client_secret
|
str
|
Reddit API client secret. |
None
|
user_agent
|
str
|
Reddit API user agent. |
None
|
asset_class
|
str
|
The type of financial asset. Defaults to "stock". - "stock": Searches in stock-related subreddits (e.g., wallstreetbets, stocks). - "forex": Searches in forex-related subreddits. - "commodities": Searches in commodity-related subreddits (e.g., gold, oil). - "etf": Searches in ETF-related subreddits. - "future": Searches in futures and options trading subreddits. - "crypto": Searches in cryptocurrency-related subreddits. - If an unrecognized asset class is provided, defaults to stock-related subreddits. |
'stock'
|
n_posts
|
int
|
The number of posts to return per subreddit. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of Reddit post contents matching the query. Each entry contains the post title and body. If no posts are found or an error occurs, returns an empty list. |
Raises:
| Type | Description |
|---|---|
PRAWException
|
If an error occurs while interacting with Reddit's API. |
Example
get_reddit_posts(symbol="AAPL", client_id="your_id", client_secret="your_secret", user_agent="your_agent", asset_class="stock", n_posts=5) ["Apple stock is rallying today due to strong earnings.", "Should I buy $AAPL now?", ...]
Notes
- Requires valid Reddit API credentials.
Source code in src/bbstrader/core/data.py
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | |
get_twitter_posts ¶
get_twitter_posts(query: str, asset_type: str = 'stock', bearer: Optional[str] = None, api_key: Optional[str] = None, api_secret: Optional[str] = None, access_token: Optional[str] = None, access_secret: Optional[str] = None, n_posts: int = 10) -> List[str]
Fetches recent tweets related to a financial asset.
This method queries Twitter for recent posts mentioning the specified asset and filters the results based on the asset type (e.g., stock, forex, crypto). The function uses the Tweepy API to fetch tweets and returns a list of tweet texts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The main keyword to search for (e.g., a stock ticker or asset name). |
required |
asset_type
|
str
|
The type of financial asset. Defaults to "stock". - "stock": Searches for tweets mentioning the stock or shares. - "forex": Searches for tweets mentioning foreign exchange (forex) or currency. - "crypto": Searches for tweets mentioning cryptocurrency or related terms. - "commodity": Searches for tweets mentioning commodities or futures trading. - "index": Searches for tweets mentioning stock market indices. - "bond": Searches for tweets mentioning bonds or fixed income securities. - If an unrecognized asset type is provided, defaults to general finance-related tweets. |
'stock'
|
bearer
|
str
|
Twitter API bearer token for authentication. |
None
|
api_key
|
str
|
Twitter API consumer key. |
None
|
api_secret
|
str
|
Twitter API consumer secret. |
None
|
access_token
|
str
|
Twitter API access token. |
None
|
access_secret
|
str
|
Twitter API access token secret. |
None
|
n_posts
|
int
|
The number of tweets to return. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of up to |
Raises:
| Type | Description |
|---|---|
TweepyException
|
If an error occurs while making the Twitter API request. |
Example
get_twitter_posts(query="AAPL", asset_type="stock", bearer="YOUR_BEARER_TOKEN", n_posts=5) ["Apple stock surges after strong earnings!", "Is $AAPL a buy at this price?", ...]
Source code in src/bbstrader/core/data.py
get_fmp_news ¶
Return an :class:FmpNews client for the given API key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api
|
str | None
|
The Financial Modeling Prep API key. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FmpNews |
FmpNews
|
A news client bound to |
Source code in src/bbstrader/core/data.py
get_coindesk_news ¶
get_coindesk_news(query='', lang: Literal['EN', 'ES', 'TR', 'FR', 'JP', 'PT'] = 'EN', limit=10, list_of_str=False) -> List[str] | List[dict]
Fetches and filters recent news articles from CoinDesk's News API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str, optional A search term to filter articles by title, body, or keywords. If empty, all articles are returned without filtering (default is ""). |
required | |
lang
|
Literal["EN", "ES", "TR", "FR", "JP", "PT"], optional Language in which to fetch news articles. Supported languages: English (EN), Spanish (ES), Turkish (TR), French (FR), Japanese (JP), and Portuguese (PT). Default is "EN". |
required | |
limit
|
int, optional Maximum number of articles to retrieve. Default is 50. |
required | |
list_of_str
|
bool, optional If True, returns a list of strings (concatenated article content). If False, returns a list of filtered article dictionaries. Default is False. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | List[dict]
|
List[str] | List[dict]
- If |
Each article dictionary contains the following fields
- 'published_on': datetime of publication
- 'title': article headline
- 'subtitle': secondary headline
- 'url': direct link to the article
- 'body': article content
- 'keywords': associated tags
- 'sentiment': sentiment label
- 'status': publication status
Notes
- Articles marked as sponsored are automatically excluded.
Source code in src/bbstrader/core/data.py
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | |
FmpData ¶
Bases: Toolkit
FMPData class for fetching data from Financial Modeling Prep API using the Toolkit class from financetoolkit package.
See financetoolkit for more details.
Initialise the FMP-backed toolkit for the given symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str
|
The Financial Modeling Prep API key. |
''
|
symbols
|
str | list
|
One symbol or a list of symbols to load. |
'AAPL'
|
Source code in src/bbstrader/core/data.py
TradeAction ¶
Bases: Enum
An enumeration class for trade actions.
TradeSignal
dataclass
¶
TradeSignal(id: int, symbol: str, action: TradeAction, price: float = None, stoplimit: float = None, sl: float = None, tp: float = None, comment: str = None)
Represents a trading signal generated by a trading system or strategy.
Notes¶
Attributes:
- id (int): A unique identifier for the trade signal or the strategy.
- symbol (str): The trading symbol (e.g., stock ticker, forex pair, crypto asset).
- action (TradeAction): The trading action to perform. Must be an instance of the
TradeActionenum (e.g., BUY, SELL). - price (float, optional): The price at which the trade should be executed.
- stoplimit (float, optional): A stop-limit price for the trade. Must not be set without specifying a price.
- sl (float, optional): A stop loss price for the trade.
- tp (float, optional): A take profit price for the trade.
- comment (str, optional): An optional comment or description related to the trade signal.
Strategy ¶
A Strategy() object encapsulates all calculation on market data
that generate advisory signals to a Portfolio object. Thus all of
the "strategy logic" resides within this class. We opted to separate
out the Strategy and Portfolio objects for this backtester,
since we believe this is more amenable to the situation of multiple
strategies feeding "ideas" to a larger Portfolio, which then can handle
its own risk (such as sector allocation, leverage). In higher frequency trading,
the strategy and portfolio concepts will be tightly coupled and extremely
hardware dependent.
At this stage in the event-driven backtester development there is no concept of an indicator or filter, such as those found in technical trading. These are also good candidates for creating a class hierarchy.
The strategy hierarchy is relatively simple as it consists of an abstract
base class with a single pure virtual method for generating SignalEvent objects.
Other methods are provided to check for pending orders, update trades from fills,
and get updates from the portfolio.
calculate_signals
abstractmethod
¶
Generate advisory trade signals from market data.
The single abstract method every strategy must implement; backtest and live engines both call it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Any
|
Engine-supplied positional context (for example a market event). |
()
|
kwargs
|
Any
|
Engine-supplied keyword context. |
{}
|
Returns:
| Type | Description |
|---|---|
List[TradeSignal] | None
|
List[TradeSignal] | None: The signals to act on, or None. |
Source code in src/bbstrader/core/strategy.py
check_pending_orders ¶
get_update_from_portfolio ¶
update_trades_from_fill ¶
perform_period_end_checks ¶
sma ¶
Simple moving average over window bars (NaN-padded).
Source code in src/bbstrader/core/indicators.py
ema ¶
Exponential moving average with span window (NaN until seeded).
The average is seeded with the SMA of the first window values, matching
the common charting convention.
Source code in src/bbstrader/core/indicators.py
wma ¶
Linearly weighted moving average (most recent bar weighted highest).
Source code in src/bbstrader/core/indicators.py
rolling_std ¶
Rolling standard deviation over window bars (NaN-padded).
Source code in src/bbstrader/core/indicators.py
zscore ¶
Rolling z-score: (price - rolling_mean) / rolling_std.
Bars where the rolling standard deviation is zero yield NaN to avoid a
divide-by-zero.
Source code in src/bbstrader/core/indicators.py
roc ¶
Rate of change in percent over window bars.
Source code in src/bbstrader/core/indicators.py
rsi ¶
Wilder's Relative Strength Index over window bars (NaN-padded).
Source code in src/bbstrader/core/indicators.py
true_range ¶
True range: max(high-low, |high-prev_close|, |low-prev_close|).
Source code in src/bbstrader/core/indicators.py
atr ¶
Average True Range using Wilder's smoothing (NaN-padded).
Source code in src/bbstrader/core/indicators.py
bollinger_bands ¶
bollinger_bands(values: ArrayLike, window: int = 20, num_std: float = 2.0) -> Tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]
Bollinger Bands; returns (lower, middle, upper) arrays.
Source code in src/bbstrader/core/indicators.py
macd ¶
macd(values: ArrayLike, fast: int = 12, slow: int = 26, signal: int = 9) -> Tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]
MACD; returns (macd_line, signal_line, histogram) arrays.
Source code in src/bbstrader/core/indicators.py
stochastic ¶
stochastic(high: ArrayLike, low: ArrayLike, close: ArrayLike, k_window: int = 14, d_window: int = 3) -> Tuple[NDArray[np.float64], NDArray[np.float64]]
Stochastic oscillator; returns (%K, %D) arrays.
Source code in src/bbstrader/core/indicators.py
donchian ¶
donchian(high: ArrayLike, low: ArrayLike, window: int = 20) -> Tuple[NDArray[np.float64], NDArray[np.float64]]
Donchian channel; returns (lower, upper) arrays over window bars.
The channel at bar i uses bars [i-window+1, i] (inclusive), so it is
safe to compare the previous bar's channel against the current price for a
breakout without look-ahead.
Source code in src/bbstrader/core/indicators.py
generate_signal ¶
generate_signal(id: int, symbol: str, action: TradeAction, price: float = None, stoplimit: float = None, sl: float = None, tp: float = None, comment: str = None) -> TradeSignal
Generates a trade signal for MetaTrader 5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int
|
Unique identifier for the trade signal. |
required |
symbol
|
str
|
The symbol for which the trade signal is generated. |
required |
action
|
TradeAction
|
The action to be taken (e.g., BUY, SELL). |
required |
price
|
float
|
The price at which to execute the trade. |
None
|
stoplimit
|
float
|
The stop limit price for the trade. |
None
|
sl
|
float
|
The stop loss price for the trade. |
None
|
tp
|
float
|
The take profit price for the trade. |
None
|
comment
|
str
|
Additional comments for the trade. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
TradeSignal |
TradeSignal
|
A TradeSignal object containing the details of the trade signal. |
Source code in src/bbstrader/core/strategy.py
broker ¶
Broker-neutral execution abstraction.
A thin Broker interface decouples strategy/execution logic from any specific
venue, so the same strategy can target MT5 today and IBKR / a crypto exchange
later by swapping the adapter. PaperBroker is a fully in-memory simulated
adapter useful for paper trading, tests, and as the reference implementation
of the contract. Live adapters (e.g. an MT5 adapter over
:mod:bbstrader.metatrader) implement the same methods.
BrokerOrder
dataclass
¶
BrokerOrder(symbol: str, side: OrderSide, quantity: float, order_type: OrderType = OrderType.MARKET, price: Optional[float] = None, id: Optional[int] = None)
A venue-neutral order request and its assigned id once submitted.
BrokerPosition
dataclass
¶
An open position: signed quantity and volume-weighted average price.
AccountInfo
dataclass
¶
A snapshot of account cash, mark-to-market equity and currency.
Broker ¶
Bases: ABC
The execution contract every venue adapter implements.
connect
abstractmethod
¶
disconnect
abstractmethod
¶
account
abstractmethod
¶
get_price
abstractmethod
¶
Return the latest market price for symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The instrument to price. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The latest price. |
submit_order
abstractmethod
¶
Submit order to the venue and return it with venue fields set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
BrokerOrder
|
The order to submit. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BrokerOrder |
BrokerOrder
|
The submitted order, populated with its assigned id. |
Source code in src/bbstrader/core/broker.py
positions
abstractmethod
¶
PaperBroker ¶
Bases: Broker
An in-memory simulated broker with immediate market fills.
Maintains cash, positions (volume-weighted average price) and an order log.
Prices are set with :meth:set_price; market orders fill at the current
price, limit/stop orders rest until :meth:set_price crosses their level.
Initialise the paper broker with starting cash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cash
|
float
|
The opening cash balance. |
100000.0
|
currency
|
str
|
The account currency code. |
'USD'
|
Source code in src/bbstrader/core/broker.py
connect ¶
disconnect ¶
set_price ¶
Update the market price and trigger any resting orders it crosses.
get_price ¶
Return the last price set for symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The instrument to price. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The most recently set price. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no price has been set for |
Source code in src/bbstrader/core/broker.py
account ¶
Return the account snapshot (cash, mark-to-market equity, currency).
equity ¶
Return cash plus the mark-to-market value of all open positions.
Source code in src/bbstrader/core/broker.py
positions ¶
orders ¶
submit_order ¶
Submit an order, filling market orders immediately at the set price.
Market orders fill at order.price or the current market price;
limit/stop orders rest and fill when :meth:set_price crosses them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
BrokerOrder
|
The order to submit. Its |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BrokerOrder |
BrokerOrder
|
The same order with its assigned |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/bbstrader/core/broker.py
data ¶
FmpNews ¶
Bases: object
FmpNews is responsible for retrieving financial news, press releases, and articles from Financial Modeling Prep (FMP).
FmpNews provides methods to fetch the latest stock, crypto, forex, and general financial news,
as well as financial articles and press releases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api
|
str
|
The API key for accessing FMP's news data. |
required |
Example
fmp_news = FmpNews(api="your_api_key_here")
Source code in src/bbstrader/core/data.py
get_articles ¶
Fetch FMP articles with their HTML content stripped to plain text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
Any
|
Optional |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: Records with |
List[Dict[str, Any]]
|
(plain text) and |
Source code in src/bbstrader/core/data.py
get_releases ¶
Fetch the latest FMP press releases, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The press-release records. |
Source code in src/bbstrader/core/data.py
get_stock_news ¶
Fetch the latest FMP stock news, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The stock-news records. |
Source code in src/bbstrader/core/data.py
get_crypto_news ¶
Fetch the latest FMP crypto news, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The crypto-news records. |
Source code in src/bbstrader/core/data.py
get_forex_news ¶
Fetch the latest FMP forex news, optionally for one symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Restrict to a single symbol. |
None
|
kwargs
|
Any
|
Optional paging/date parameters (see :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The forex-news records. |
Source code in src/bbstrader/core/data.py
parse_news ¶
Flatten and date-filter raw news records into text strings.
Keeps records published within the start/end window and, when a
symbol is given, only those mentioning it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
news
|
List[Dict[str, Any]]
|
The raw records to parse. |
required |
symbol
|
Optional[str]
|
Restrict to records mentioning this symbol. |
None
|
kwargs
|
Any
|
Optional |
{}
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: One flattened text string per matching record. |
Source code in src/bbstrader/core/data.py
get_latest_articles ¶
get_latest_articles(articles: Optional[List[Dict[str, Any]]] = None, save: bool = False, **kwargs: Any) -> List[Dict[str, Any]]
Return the latest FMP articles, using a local CSV cache when fresh.
Reads latest_fmp_articles.csv if present and recent enough; otherwise
downloads fresh articles and, when save is set, refreshes the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
articles
|
Optional[List[Dict[str, Any]]]
|
Pre-fetched articles to use instead of reading the cache or downloading. |
None
|
save
|
bool
|
When True, persist the fetched articles to the cache CSV. |
False
|
kwargs
|
Any
|
Optional |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: The latest article records. |
Source code in src/bbstrader/core/data.py
get_news ¶
get_news(query: str, source: str = 'articles', articles: Optional[List[Dict[str, Any]]] = None, symbol: Optional[str] = None, **kwargs: Any) -> List[str]
Retrieves relevant financial news based on the specified source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The search query or keyword for filtering news, may also be a ticker. |
required |
source
|
str
|
The news source to retrieve from. Defaults to "articles". Available options: "articles", "releases", "stock", "crypto", "forex". |
'articles'
|
articles
|
list
|
List of pre-fetched articles to use when source="articles". Defaults to None. |
None
|
symbol
|
str
|
The financial asset symbol (e.g., "AAPL" for stocks, "BTC" for crypto). Defaults to None. |
None
|
**kwargs
|
dict
|
Additional arguments required for fetching news data. May include: - start (str): The start period for news retrieval (YYY-MM-DD) - end (str): The end period for news retrieval (YYY-MM-DD) - page (int): The number of page to load for each news - limit (int): Maximum Responses per API Call |
{}
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[dict]: A list of filtered news articles relevant to the query. Returns an empty list if no relevant news is found. |
Source code in src/bbstrader/core/data.py
FinancialNews ¶
Bases: object
The FinancialNews class provides methods to fetch financial news, articles, and discussions from various sources such as Yahoo Finance, Google Finance, Reddit, Coindesk and Twitter. It also supports retrieving news using Financial Modeling Prep (FMP).
get_yahoo_finance_news ¶
Fetches recent Yahoo Finance news headlines for a given financial asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The asset symbol or name (e.g., "AAPL"). |
required |
asset_type
|
str
|
The type of asset (e.g., "stock", "etf"). Defaults to "stock", supported types include: - "stock": Stock symbols (e.g., AAPL, MSFT) - "etf": Exchange-traded funds (e.g., SPY, QQQ) - "future": Futures contracts (e.g., CL=F for crude oil) - "forex": Forex pairs (e.g., EURUSD=X, USDJPY=X) - "crypto": Cryptocurrency pairs (e.g., BTC-USD, ETH-USD) - "index": Stock market indices (e.g., ^GSPC for S&P 500) |
'stock'
|
n_news
|
int
|
The number of news headlines to return. Defaults to 10. |
10
|
Note
For commotities and bonds, use the "Future" asset type.
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of Yahoo Finance news headlines relevant to the query. |
Source code in src/bbstrader/core/data.py
get_google_finance_news ¶
Fetches recent Google Finance news headlines for a given financial asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The asset symbol or name (e.g., "AAPL"). |
required |
asset_type
|
str
|
The type of asset (e.g., "stock", "crypto"). Defaults to "stock". Supported types include: - "stock": Stock symbols (e.g., AAPL, MSFT) - "etf": Exchange-traded funds (e.g., SPY, QQQ) - "future": Futures contracts (e.g., CL=F or crude oil) - "forex": Forex pairs (e.g., EURUSD, USDJPY) - "crypto": Cryptocurrency pairs (e.g., BTCUSD, ETHUSD) |
'stock'
|
n_news
|
int
|
The number of news headlines to return. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of Google Finance news headlines relevant to the query. |
Source code in src/bbstrader/core/data.py
get_reddit_posts ¶
get_reddit_posts(symbol: str, client_id=None, client_secret=None, user_agent=None, asset_class='stock', n_posts=10) -> List[str]
Fetches recent Reddit posts related to a financial asset.
This method queries relevant subreddits for posts mentioning the specified symbol and returns posts based on the selected asset class (e.g., stock, forex, crypto). The function uses the PRAW library to interact with Reddit's API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The financial asset's symbol or name to search for. |
required |
client_id
|
str
|
Reddit API client ID for authentication. |
None
|
client_secret
|
str
|
Reddit API client secret. |
None
|
user_agent
|
str
|
Reddit API user agent. |
None
|
asset_class
|
str
|
The type of financial asset. Defaults to "stock". - "stock": Searches in stock-related subreddits (e.g., wallstreetbets, stocks). - "forex": Searches in forex-related subreddits. - "commodities": Searches in commodity-related subreddits (e.g., gold, oil). - "etf": Searches in ETF-related subreddits. - "future": Searches in futures and options trading subreddits. - "crypto": Searches in cryptocurrency-related subreddits. - If an unrecognized asset class is provided, defaults to stock-related subreddits. |
'stock'
|
n_posts
|
int
|
The number of posts to return per subreddit. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of Reddit post contents matching the query. Each entry contains the post title and body. If no posts are found or an error occurs, returns an empty list. |
Raises:
| Type | Description |
|---|---|
PRAWException
|
If an error occurs while interacting with Reddit's API. |
Example
get_reddit_posts(symbol="AAPL", client_id="your_id", client_secret="your_secret", user_agent="your_agent", asset_class="stock", n_posts=5) ["Apple stock is rallying today due to strong earnings.", "Should I buy $AAPL now?", ...]
Notes
- Requires valid Reddit API credentials.
Source code in src/bbstrader/core/data.py
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | |
get_twitter_posts ¶
get_twitter_posts(query: str, asset_type: str = 'stock', bearer: Optional[str] = None, api_key: Optional[str] = None, api_secret: Optional[str] = None, access_token: Optional[str] = None, access_secret: Optional[str] = None, n_posts: int = 10) -> List[str]
Fetches recent tweets related to a financial asset.
This method queries Twitter for recent posts mentioning the specified asset and filters the results based on the asset type (e.g., stock, forex, crypto). The function uses the Tweepy API to fetch tweets and returns a list of tweet texts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The main keyword to search for (e.g., a stock ticker or asset name). |
required |
asset_type
|
str
|
The type of financial asset. Defaults to "stock". - "stock": Searches for tweets mentioning the stock or shares. - "forex": Searches for tweets mentioning foreign exchange (forex) or currency. - "crypto": Searches for tweets mentioning cryptocurrency or related terms. - "commodity": Searches for tweets mentioning commodities or futures trading. - "index": Searches for tweets mentioning stock market indices. - "bond": Searches for tweets mentioning bonds or fixed income securities. - If an unrecognized asset type is provided, defaults to general finance-related tweets. |
'stock'
|
bearer
|
str
|
Twitter API bearer token for authentication. |
None
|
api_key
|
str
|
Twitter API consumer key. |
None
|
api_secret
|
str
|
Twitter API consumer secret. |
None
|
access_token
|
str
|
Twitter API access token. |
None
|
access_secret
|
str
|
Twitter API access token secret. |
None
|
n_posts
|
int
|
The number of tweets to return. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
List[str]
|
list[str]: A list of up to |
Raises:
| Type | Description |
|---|---|
TweepyException
|
If an error occurs while making the Twitter API request. |
Example
get_twitter_posts(query="AAPL", asset_type="stock", bearer="YOUR_BEARER_TOKEN", n_posts=5) ["Apple stock surges after strong earnings!", "Is $AAPL a buy at this price?", ...]
Source code in src/bbstrader/core/data.py
get_fmp_news ¶
Return an :class:FmpNews client for the given API key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api
|
str | None
|
The Financial Modeling Prep API key. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FmpNews |
FmpNews
|
A news client bound to |
Source code in src/bbstrader/core/data.py
get_coindesk_news ¶
get_coindesk_news(query='', lang: Literal['EN', 'ES', 'TR', 'FR', 'JP', 'PT'] = 'EN', limit=10, list_of_str=False) -> List[str] | List[dict]
Fetches and filters recent news articles from CoinDesk's News API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str, optional A search term to filter articles by title, body, or keywords. If empty, all articles are returned without filtering (default is ""). |
required | |
lang
|
Literal["EN", "ES", "TR", "FR", "JP", "PT"], optional Language in which to fetch news articles. Supported languages: English (EN), Spanish (ES), Turkish (TR), French (FR), Japanese (JP), and Portuguese (PT). Default is "EN". |
required | |
limit
|
int, optional Maximum number of articles to retrieve. Default is 50. |
required | |
list_of_str
|
bool, optional If True, returns a list of strings (concatenated article content). If False, returns a list of filtered article dictionaries. Default is False. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | List[dict]
|
List[str] | List[dict]
- If |
Each article dictionary contains the following fields
- 'published_on': datetime of publication
- 'title': article headline
- 'subtitle': secondary headline
- 'url': direct link to the article
- 'body': article content
- 'keywords': associated tags
- 'sentiment': sentiment label
- 'status': publication status
Notes
- Articles marked as sponsored are automatically excluded.
Source code in src/bbstrader/core/data.py
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | |
FmpData ¶
Bases: Toolkit
FMPData class for fetching data from Financial Modeling Prep API using the Toolkit class from financetoolkit package.
See financetoolkit for more details.
Initialise the FMP-backed toolkit for the given symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str
|
The Financial Modeling Prep API key. |
''
|
symbols
|
str | list
|
One symbol or a list of symbols to load. |
'AAPL'
|
Source code in src/bbstrader/core/data.py
indicators ¶
Vectorized technical indicators.
A small, dependency-free indicator library built on NumPy so that it can be used
identically from backtest strategies (BacktestStrategy) and live strategies
(LiveStrategy). Every function operates on a 1-D array of prices (or OHLC
arrays) and returns an array of the same length as the input, left-padded
with NaN where there is not yet enough history. This lines up with the
output of BaseStrategy.get_asset_values(...) so an indicator value at index
-1 corresponds to the latest bar.
The implementations are plain NumPy (no third-party TA dependency), which keeps the install lean and leaves the door open to JIT-compiling the hot paths later.
sma ¶
Simple moving average over window bars (NaN-padded).
Source code in src/bbstrader/core/indicators.py
ema ¶
Exponential moving average with span window (NaN until seeded).
The average is seeded with the SMA of the first window values, matching
the common charting convention.
Source code in src/bbstrader/core/indicators.py
wma ¶
Linearly weighted moving average (most recent bar weighted highest).
Source code in src/bbstrader/core/indicators.py
rolling_std ¶
Rolling standard deviation over window bars (NaN-padded).
Source code in src/bbstrader/core/indicators.py
zscore ¶
Rolling z-score: (price - rolling_mean) / rolling_std.
Bars where the rolling standard deviation is zero yield NaN to avoid a
divide-by-zero.
Source code in src/bbstrader/core/indicators.py
roc ¶
Rate of change in percent over window bars.
Source code in src/bbstrader/core/indicators.py
rsi ¶
Wilder's Relative Strength Index over window bars (NaN-padded).
Source code in src/bbstrader/core/indicators.py
true_range ¶
True range: max(high-low, |high-prev_close|, |low-prev_close|).
Source code in src/bbstrader/core/indicators.py
atr ¶
Average True Range using Wilder's smoothing (NaN-padded).
Source code in src/bbstrader/core/indicators.py
bollinger_bands ¶
bollinger_bands(values: ArrayLike, window: int = 20, num_std: float = 2.0) -> Tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]
Bollinger Bands; returns (lower, middle, upper) arrays.
Source code in src/bbstrader/core/indicators.py
macd ¶
macd(values: ArrayLike, fast: int = 12, slow: int = 26, signal: int = 9) -> Tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]
MACD; returns (macd_line, signal_line, histogram) arrays.
Source code in src/bbstrader/core/indicators.py
stochastic ¶
stochastic(high: ArrayLike, low: ArrayLike, close: ArrayLike, k_window: int = 14, d_window: int = 3) -> Tuple[NDArray[np.float64], NDArray[np.float64]]
Stochastic oscillator; returns (%K, %D) arrays.
Source code in src/bbstrader/core/indicators.py
donchian ¶
donchian(high: ArrayLike, low: ArrayLike, window: int = 20) -> Tuple[NDArray[np.float64], NDArray[np.float64]]
Donchian channel; returns (lower, upper) arrays over window bars.
The channel at bar i uses bars [i-window+1, i] (inclusive), so it is
safe to compare the previous bar's channel against the current price for a
breakout without look-ahead.
Source code in src/bbstrader/core/indicators.py
strategy ¶
TradeAction ¶
Bases: Enum
An enumeration class for trade actions.
TradeSignal
dataclass
¶
TradeSignal(id: int, symbol: str, action: TradeAction, price: float = None, stoplimit: float = None, sl: float = None, tp: float = None, comment: str = None)
Represents a trading signal generated by a trading system or strategy.
Notes¶
Attributes:
- id (int): A unique identifier for the trade signal or the strategy.
- symbol (str): The trading symbol (e.g., stock ticker, forex pair, crypto asset).
- action (TradeAction): The trading action to perform. Must be an instance of the
TradeActionenum (e.g., BUY, SELL). - price (float, optional): The price at which the trade should be executed.
- stoplimit (float, optional): A stop-limit price for the trade. Must not be set without specifying a price.
- sl (float, optional): A stop loss price for the trade.
- tp (float, optional): A take profit price for the trade.
- comment (str, optional): An optional comment or description related to the trade signal.
Strategy ¶
A Strategy() object encapsulates all calculation on market data
that generate advisory signals to a Portfolio object. Thus all of
the "strategy logic" resides within this class. We opted to separate
out the Strategy and Portfolio objects for this backtester,
since we believe this is more amenable to the situation of multiple
strategies feeding "ideas" to a larger Portfolio, which then can handle
its own risk (such as sector allocation, leverage). In higher frequency trading,
the strategy and portfolio concepts will be tightly coupled and extremely
hardware dependent.
At this stage in the event-driven backtester development there is no concept of an indicator or filter, such as those found in technical trading. These are also good candidates for creating a class hierarchy.
The strategy hierarchy is relatively simple as it consists of an abstract
base class with a single pure virtual method for generating SignalEvent objects.
Other methods are provided to check for pending orders, update trades from fills,
and get updates from the portfolio.
calculate_signals
abstractmethod
¶
Generate advisory trade signals from market data.
The single abstract method every strategy must implement; backtest and live engines both call it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Any
|
Engine-supplied positional context (for example a market event). |
()
|
kwargs
|
Any
|
Engine-supplied keyword context. |
{}
|
Returns:
| Type | Description |
|---|---|
List[TradeSignal] | None
|
List[TradeSignal] | None: The signals to act on, or None. |
Source code in src/bbstrader/core/strategy.py
check_pending_orders ¶
get_update_from_portfolio ¶
update_trades_from_fill ¶
perform_period_end_checks ¶
BaseStrategy ¶
Bases: Strategy
Base class containing shared logic for both Backtest and Live MT5 strategies. This class handles configuration, logging, and common utility calculations.
Initialise shared strategy configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_list
|
List[str]
|
The symbols the strategy trades. |
required |
kwargs
|
Any
|
Common options, including |
{}
|
Source code in src/bbstrader/core/strategy.py
calculate_signals ¶
Provides the mechanisms to calculate signals for the strategy. This methods should return a list of signals for the strategy For Live mode and None For Backtest mode.
Each signal must be a TradeSignal object with the following attributes:
- id: The unique identifier for the strategy or order.
- action: The order to execute on the symbol (LONG, SHORT, EXIT, etc.), see bbstrader.core.utils.TradeAction.
- symbol: The trading symbol (e.g., stock ticker, forex pair, crypto asset).
- See bbstrader.core.strategy.TradeSignal for other optionnal arguments.
Source code in src/bbstrader/core/strategy.py
perform_period_end_checks ¶
Some strategies may require additional checks at the end of the period, such as closing all positions or orders or tracking the performance of the strategy etc.
This method is called at the end of the period to perform such checks.
Source code in src/bbstrader/core/strategy.py
get_asset_values
abstractmethod
¶
get_asset_values(symbol_list: List[str], window: int, value_type: str = 'returns', array: bool = True, **kwargs) -> Optional[Dict[str, Union[np.typing.NDArray, pd.Series]]]
Get the historical OHLCV value or returns or custum value based on the DataHandker of the assets in the symbol list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_list
|
List of ticker symbols for the pairs trading strategy. |
required | |
window
|
The lookback period for resquesting the data. |
required | |
value_type
|
The type of value to get (e.g., returns, open, high, low, close, adjclose, volume). |
required | |
array
|
If True, return the values as numpy arrays, otherwise as pandas Series. |
required | |
error
|
The error handling method for the function. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
asset_values |
Optional[Dict[str, Union[NDArray, Series]]]
|
Historical values of the assets in the symbol list. |
Note
In Live mode, the bbstrader.metatrader.rates.Rates class is used to get the historical data
so the value_type must be 'returns', 'open', 'high', 'low', 'close', 'adjclose', 'volume'.
Source code in src/bbstrader/core/strategy.py
apply_risk_management ¶
apply_risk_management(optimizer: str, symbols: Optional[List[str]] = None, freq: int = 252) -> Optional[Dict[str, float]]
Apply risk management optimization.
Source code in src/bbstrader/core/strategy.py
get_quantity ¶
get_quantity(symbol: str, weight: float, price: Optional[float] = None, volume: Optional[float] = None, maxqty: Optional[int] = None) -> int
Calculate the quantity to buy or sell for a given symbol based on the dollar value provided. The quantity calculated can be used to evalute a strategy's performance for each symbol given the fact that the dollar value is the same for all symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
qty |
int
|
The quantity to buy or sell for the symbol. |
Source code in src/bbstrader/core/strategy.py
get_quantities ¶
Get the quantities to buy or sell for the symbols in the strategy. This method is used when whe need to assign different quantities to the symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantities
|
The quantities for the symbols in the strategy. |
required |
Source code in src/bbstrader/core/strategy.py
calculate_pct_change
staticmethod
¶
Return the percentage change from lh_price to current_price.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_price
|
float
|
The current price. |
required |
lh_price
|
float
|
The reference (look-back/historical) price. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The change as a percentage (for example 5.0 for +5%). |
Source code in src/bbstrader/core/strategy.py
is_signal_time
staticmethod
¶
Check if we can generate a signal based on the current period count. We use the signal interval as a form of periodicity or rebalancing period.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period_count
|
The current period count (e.g., number of bars). |
required | |
signal_inverval
|
The signal interval for generating signals (e.g., every 5 bars). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if we can generate a signal, False otherwise |
Source code in src/bbstrader/core/strategy.py
get_current_dt
staticmethod
¶
Return the current time in the given timezone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_zone
|
str
|
The IANA timezone name (default |
'US/Eastern'
|
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
The timezone-aware current datetime. |
Source code in src/bbstrader/core/strategy.py
convert_time_zone
staticmethod
¶
convert_time_zone(dt: Union[datetime, int, Timestamp], from_tz: str = 'UTC', to_tz: str = 'US/Eastern') -> pd.Timestamp
Convert datetime from one timezone to another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
The datetime to convert. |
required | |
from_tz
|
The timezone to convert from. |
required | |
to_tz
|
The timezone to convert to. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dt_to |
Timestamp
|
The converted datetime. |
Source code in src/bbstrader/core/strategy.py
stop_time
staticmethod
¶
Return True once the current time has reached stop_time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_zone
|
str
|
The IANA timezone the times are evaluated in. |
required |
stop_time
|
str
|
The cut-off time as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the current time is at or past |
Source code in src/bbstrader/core/strategy.py
TWSStrategy ¶
Bases: Strategy
Placeholder strategy base for the Interactive Brokers (TWS) adapter.
calculate_signals ¶
Generate trade signals for a TWS strategy (must be implemented).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Any
|
Engine-supplied positional context. |
()
|
kwargs
|
Any
|
Engine-supplied keyword context. |
{}
|
Returns:
| Type | Description |
|---|---|
List[TradeSignal]
|
List[TradeSignal]: The signals to act on. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, until a concrete subclass implements it. |
Source code in src/bbstrader/core/strategy.py
generate_signal ¶
generate_signal(id: int, symbol: str, action: TradeAction, price: float = None, stoplimit: float = None, sl: float = None, tp: float = None, comment: str = None) -> TradeSignal
Generates a trade signal for MetaTrader 5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int
|
Unique identifier for the trade signal. |
required |
symbol
|
str
|
The symbol for which the trade signal is generated. |
required |
action
|
TradeAction
|
The action to be taken (e.g., BUY, SELL). |
required |
price
|
float
|
The price at which to execute the trade. |
None
|
stoplimit
|
float
|
The stop limit price for the trade. |
None
|
sl
|
float
|
The stop loss price for the trade. |
None
|
tp
|
float
|
The take profit price for the trade. |
None
|
comment
|
str
|
Additional comments for the trade. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
TradeSignal |
TradeSignal
|
A TradeSignal object containing the details of the trade signal. |