2. Modules¶
TradingBot is composed by different modules organised by their nature. Each section of this document provide a description of the module meaning along with the documentation of its internal members.
2.1. TradingBot¶
-
class
TradingBot.
TradingBot
(time_provider: Optional[tradingbot.Components.TimeProvider.TimeProvider] = None, config_filepath: Optional[pathlib.Path] = None)[source]¶ Class that initialise and hold references of main components like the broker interface, the strategy or the epic_ids list
-
backtest
(market_id: str, start_date: str, end_date: str, epic_id: Optional[str] = None) → None[source]¶ Backtest a market using the configured strategy
-
process_market
(market: tradingbot.Interfaces.Market.Market, open_positions: List[tradingbot.Interfaces.Position.Position]) → None[source]¶ Spin the strategy on all the markets
-
process_open_positions
() → None[source]¶ Fetch open positions markets and run the strategy against them closing the trades if required
-
process_trade
(market: tradingbot.Interfaces.Market.Market, direction: tradingbot.Components.Utils.TradeDirection, limit: Optional[float], stop: Optional[float], open_positions: List[tradingbot.Interfaces.Position.Position]) → None[source]¶ Process a trade checking if it is a “close position” trade or a new trade
-
2.2. Components¶
The Components
module contains the components that provides services
used by TradingBot.
2.2.1. Broker¶
The Broker
class is the wrapper of all the trading services and provides
the main interface for the strategies
to access market data and perform
trades.
2.2.1.1. AbstractInterfaces¶
-
class
Components.Broker.AbstractInterfaces.
AbstractInterface
(config: tradingbot.Components.Configuration.Configuration)[source]¶
2.2.1.2. IGInterface¶
-
class
Components.Broker.IGInterface.
IGInterface
(config: tradingbot.Components.Configuration.Configuration)[source]¶ IG broker interface class, provides functions to use the IG REST API
-
authenticate
() → bool[source]¶ Authenticate the IGInterface instance with the configured credentials
-
close_all_positions
() → bool[source]¶ Try to close all the account open positions.
- Returns False if an error occurs otherwise True
-
close_position
(position: tradingbot.Interfaces.Position.Position) → bool[source]¶ Close the given market position
- position: position json object obtained from IG API
- Returns False if an error occurs otherwise True
-
confirm_order
(dealRef: str) → bool[source]¶ Confirm an order from a dealing reference
- dealRef: dealing reference to confirm
- Returns False if an error occurs otherwise True
-
get_account_balances
() → Tuple[Optional[float], Optional[float]][source]¶ Returns a tuple (balance, deposit) for the account in use
- Returns (None,None) if an error occurs otherwise (balance, deposit)
-
get_account_used_perc
() → Optional[float][source]¶ Fetch the percentage of available balance is currently used
- Returns the percentage of account used over total available amount
-
get_market_info
(epic_id: str) → tradingbot.Interfaces.Market.Market[source]¶ Returns info for the given market including a price snapshot
- epic_id: market epic as string
- Returns None if an error occurs otherwise the json returned by IG API
-
get_markets_from_watchlist
(name: str) → List[tradingbot.Interfaces.Market.Market][source]¶ Get the list of markets included in the watchlist
- name: name of the watchlist
-
get_open_positions
() → List[tradingbot.Interfaces.Position.Position][source]¶ Returns the account open positions in an json object
- Returns the json object returned by the IG API
-
get_positions_map
() → Dict[str, int][source]¶ Returns a dict containing the account open positions in the form {string: int} where the string is defined as ‘marketId-tradeDirection’ and the int is the trade size
- Returns None if an error occurs otherwise a dict(string:int)
Navigate the market node id
- Returns the json representing the market node
-
search_market
(search: str) → List[tradingbot.Interfaces.Market.Market][source]¶ Returns a list of markets that matched the search string
-
set_default_account
(accountId: str) → bool[source]¶ Sets the IG account to use
- accountId: String representing the accound id to use
- Returns False if an error occurs otherwise True
-
trade
(epic_id: str, trade_direction: tradingbot.Components.Utils.TradeDirection, limit: float, stop: float) → bool[source]¶ Try to open a new trade for the given epic
- epic_id: market epic as string
- trade_direction: BUY or SELL
- limit: limit level
- stop: stop level
- Returns False if an error occurs otherwise True
-
2.2.1.3. AVInterface¶
-
class
Components.Broker.AVInterface.
AVInterface
(config: tradingbot.Components.Configuration.Configuration)[source]¶ AlphaVantage interface class, provides methods to call AlphaVantage API and return the result in useful format handling possible errors.
-
daily
(marketId: str) → pandas.core.frame.DataFrame[source]¶ Calls AlphaVantage API and return the Daily time series for the given market
- marketId: string representing an AlphaVantage compatible market id
- Returns None if an error occurs otherwise the pandas dataframe
-
intraday
(marketId: str, interval: Components.Broker.AVInterface.AVInterval) → pandas.core.frame.DataFrame[source]¶ Calls AlphaVantage API and return the Intraday time series for the given market
- marketId: string representing an AlphaVantage compatible market id
- interval: string representing an AlphaVantage interval type
- Returns None if an error occurs otherwise the pandas dataframe
-
macd
(marketId: str, interval: Components.Broker.AVInterface.AVInterval) → pandas.core.frame.DataFrame[source]¶ Calls AlphaVantage API and return the MACDEXT tech indicator series for the given market
- marketId: string representing an AlphaVantage compatible market id
- interval: string representing an AlphaVantage interval type
- Returns None if an error occurs otherwise the pandas dataframe
-
macdext
(marketId: str, interval: Components.Broker.AVInterface.AVInterval) → pandas.core.frame.DataFrame[source]¶ Calls AlphaVantage API and return the MACDEXT tech indicator series for the given market
- marketId: string representing an AlphaVantage compatible market id
- interval: string representing an AlphaVantage interval type
- Returns None if an error occurs otherwise the pandas dataframe
-
2.2.1.4. YFinanceInterface¶
2.2.1.5. Broker¶
-
class
Components.Broker.Broker.
Broker
(factory: tradingbot.Components.Broker.BrokerFactory.BrokerFactory)[source]¶ This class provides a template interface for all those broker related actions/tasks wrapping the actual implementation class internally
-
close_position
(position: tradingbot.Interfaces.Position.Position) → bool[source]¶ Attempt to close the requested open position
-
get_macd
(market: tradingbot.Interfaces.Market.Market, interval: tradingbot.Components.Utils.Interval, datapoints_range: int) → tradingbot.Interfaces.MarketMACD.MarketMACD[source]¶ Return a pandas dataframe containing MACD technical indicator for the requested market with requested interval
-
get_market_info
(market_id: str) → tradingbot.Interfaces.Market.Market[source]¶ Return the last available snapshot of the requested market
-
get_markets_from_watchlist
(watchlist_name: str) → List[tradingbot.Interfaces.Market.Market][source]¶ Return a name list of the markets in the required watchlist
-
get_open_positions
() → List[tradingbot.Interfaces.Position.Position][source]¶ Returns the current open positions
-
get_prices
(market: tradingbot.Interfaces.Market.Market, interval: tradingbot.Components.Utils.Interval, data_range: int) → tradingbot.Interfaces.MarketHistory.MarketHistory[source]¶ Returns past prices for the given market
- market: market to query prices for
- interval: resolution of the time series: minute, hours, etc.
- data_range: amount of past datapoint to fetch
- Returns the MarketHistory instance
Return the children nodes of the requested node
-
2.2.2. MarketProvider¶
-
class
Components.MarketProvider.
MarketProvider
(config: tradingbot.Components.Configuration.Configuration, broker: tradingbot.Components.Broker.Broker.Broker)[source]¶ Provide markets from different sources based on configuration. Supports market lists, dynamic market exploration or watchlists
-
get_market_from_epic
(epic: str) → tradingbot.Interfaces.Market.Market[source]¶ Given a market epic id returns the related market snapshot
-
2.2.3. TimeProvider¶
-
class
Components.TimeProvider.
TimeProvider
[source]¶ Class that handle functions dependents on actual time such as wait, sleep or compute date/time operations
-
get_seconds_to_market_opening
(from_time: datetime.datetime) → float[source]¶ Return the amount of seconds from now to the next market opening, taking into account UK bank holidays and weekends
-
2.2.4. Backtester¶
2.2.5. Configuration¶
2.2.6. Utils¶
-
class
Components.Utils.
Utils
[source]¶ Utility class containing static methods to perform simple general actions
-
static
humanize_time
(secs: Union[int, float]) → str[source]¶ Convert the given time (in seconds) into a readable format hh:mm:ss
-
static
is_between
(time: str, time_range: Tuple[str, str])[source]¶ Return True if time is between the time_range. time must be a string. time_range must be a tuple (a,b) where a and b are strings in format ‘HH:MM’
-
static
macd_df_from_list
(price_list: List[float]) → pandas.core.frame.DataFrame[source]¶ Return a MACD pandas dataframe with columns “MACD”, “Signal” and “Hist
-
static
midpoint
(p1: Union[int, float], p2: Union[int, float]) → Union[int, float][source]¶ Return the midpoint
-
static
2.3. Interfaces¶
The Interfaces
module contains all the interfaces used to exchange
information between different TradingBot components.
The purpose of this module is have clear internal API and avoid integration
errors.
2.3.1. Market¶
2.3.2. MarketHistory¶
2.3.3. MarketMACD¶
2.4. Strategies¶
The Strategies
module contains the strategies used by TradingBot to
analyse the markets. The Strategy
class is the parent from where
any custom strategy must inherit from.
The other modules described here are strategies available in TradingBot.
2.4.1. Strategy¶
-
class
Strategies.Strategy.
Strategy
(config: tradingbot.Components.Configuration.Configuration, broker: tradingbot.Components.Broker.Broker.Broker)[source]¶ Generic strategy template to use as a parent class for custom strategies.
2.4.2. StrategyFactory¶
-
class
Strategies.StrategyFactory.
StrategyFactory
(config: tradingbot.Components.Configuration.Configuration, broker: tradingbot.Components.Broker.Broker.Broker)[source]¶ Factory class to create instances of Strategies. The class provide an interface to instantiate new objects of a given Strategy name
-
make_from_configuration
() → Union[tradingbot.Strategies.SimpleMACD.SimpleMACD, tradingbot.Strategies.WeightedAvgPeak.WeightedAvgPeak][source]¶ Create and return an instance of the Strategy class as configured in the configuration file
-
make_strategy
(strategy_name: str) → Union[tradingbot.Strategies.SimpleMACD.SimpleMACD, tradingbot.Strategies.WeightedAvgPeak.WeightedAvgPeak][source]¶ Create and return an instance of the Strategy class specified by the strategy_name
- strategy_name: name of the strategy as defined in the json config file
- Returns an instance of the requested Strategy or None if an error occurres
-
2.4.3. SimpleMACD¶
-
class
Strategies.SimpleMACD.
SimpleMACD
(config: tradingbot.Components.Configuration.Configuration, broker: tradingbot.Components.Broker.Broker.Broker)[source]¶ Strategy that use the MACD technical indicator of a market to decide whether to buy, sell or hold. Buy when the MACD cross over the MACD signal. Sell when the MACD cross below the MACD signal.
-
backtest
(market: tradingbot.Interfaces.Market.Market, start_date: datetime.datetime, end_date: datetime.datetime) → Dict[str, Union[float, List[Tuple[str, tradingbot.Components.Utils.TradeDirection, float]]]][source]¶ Backtest the strategy
-
calculate_stop_limit
(tradeDirection: tradingbot.Components.Utils.TradeDirection, current_offer: float, current_bid: float, limit_perc: float, stop_perc: float) → Tuple[float, float][source]¶ Calculate the stop and limit levels from the given percentages
-
fetch_datapoints
(market: tradingbot.Interfaces.Market.Market) → tradingbot.Interfaces.MarketMACD.MarketMACD[source]¶ Fetch historic MACD data
-
find_trade_signal
(market: tradingbot.Interfaces.Market.Market, datapoints: tradingbot.Interfaces.MarketMACD.MarketMACD) → Tuple[tradingbot.Components.Utils.TradeDirection, Optional[float], Optional[float]][source]¶ Calculate the MACD of the previous days and find a cross between MACD and MACD signal
- market: Market object
- datapoints: datapoints used to analyse the market
- Returns TradeDirection, limit_level, stop_level or TradeDirection.NONE, None, None
-
2.4.4. Weighted Average Peak Detection¶
-
class
Strategies.WeightedAvgPeak.
WeightedAvgPeak
(config: tradingbot.Components.Configuration.Configuration, broker: tradingbot.Components.Broker.Broker.Broker)[source]¶ All credits of this strategy goes to GitHub user @tg12.
-
backtest
(market: tradingbot.Interfaces.Market.Market, start_date: datetime.datetime, end_date: datetime.datetime) → Dict[str, Union[float, List[Tuple[str, tradingbot.Components.Utils.TradeDirection, float]]]][source]¶ Backtest the strategy
-
fetch_datapoints
(market: tradingbot.Interfaces.Market.Market) → tradingbot.Interfaces.MarketHistory.MarketHistory[source]¶ Fetch weekly prices of past 18 weeks
-
find_trade_signal
(market: tradingbot.Interfaces.Market.Market, datapoints: tradingbot.Interfaces.MarketHistory.MarketHistory) → Tuple[tradingbot.Components.Utils.TradeDirection, Optional[float], Optional[float]][source]¶ TODO add description of strategy key points
-
peakdet
(v: numpy.ndarray, delta: float, x: Optional[numpy.ndarray] = None) → Tuple[Optional[numpy.ndarray], Optional[numpy.ndarray]][source]¶ Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays
function [maxtab, mintab]=peakdet(v, delta, x) %PEAKDET Detect peaks in a vector % [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local % maxima and minima (“peaks”) in the vector V. % MAXTAB and MINTAB consists of two columns. Column 1 % contains indices in V, and column 2 the found values. % % With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices % in MAXTAB and MINTAB are replaced with the corresponding % X-values. % % A point is considered a maximum peak if it has the maximal % value, and was preceded (to the left) by a value lower by % DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted). % This function is released to the public domain; Any use is allowed.
-