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

close_open_positions() → None[source]

Closes all the open positions in the account

process_market(market: tradingbot.Interfaces.Market.Market, open_positions: List[tradingbot.Interfaces.Position.Position]) → None[source]

Spin the strategy on all the markets

process_market_source() → None[source]

Process markets from the configured market source

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

safety_checks() → None[source]

Perform some safety checks before running the strategy against the next market

Raise exceptions if not safe to trade

setup_logging() → None[source]

Setup the global logging settings

start() → None[source]

Starts the TradingBot main loop - process open positions - process markets from market source - wait for configured wait time - start over

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]
class Components.Broker.AbstractInterfaces.AccountInterface(config: tradingbot.Components.Configuration.Configuration)[source]
class Components.Broker.AbstractInterfaces.StocksInterface(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_market_node(node_id: str) → Dict[str, Any][source]

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.2.1. Enums
class Components.Broker.IGInterface.IG_API_URL[source]

IG REST API urls

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
quote_endpoint(market_id: str) → pandas.core.frame.DataFrame[source]

Calls AlphaVantage API and return the Quote Endpoint data for the given market

  • market_id: string representing the market id to fetch data of
  • Returns None if an error occurs otherwise the pandas dataframe
weekly(marketId: str) → pandas.core.frame.DataFrame[source]

Calls AlphaVantage API and return the Weekly time series for the given market

  • marketId: string representing an AlphaVantage compatible market id
  • Returns None if an error occurs otherwise the pandas dataframe
2.2.1.3.1. Enums
class Components.Broker.AVInterface.AVInterval[source]

AlphaVantage interval types: ‘1min’, ‘5min’, ‘15min’, ‘30min’, ‘60min’

2.2.1.4. YFinanceInterface

class Components.Broker.YFinanceInterface.YFInterval[source]

An enumeration.

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_all_positions() → bool[source]

Attempt to close all the current open positions

close_position(position: tradingbot.Interfaces.Position.Position) → bool[source]

Attempt to close the requested open position

get_account_used_perc() → Optional[float][source]

Returns the account used value in percentage

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
navigate_market_node(node_id: str) → Dict[str, Any][source]

Return the children nodes of the requested node

search_market(search: str) → List[tradingbot.Interfaces.Market.Market][source]

Search for a market from a search string

trade(market_id: str, trade_direction: tradingbot.Components.Utils.TradeDirection, limit: float, stop: float)[source]

Request a trade of the given market

2.2.1.6. BrokerFactory

class Components.Broker.BrokerFactory.BrokerFactory(config: tradingbot.Components.Configuration.Configuration)[source]
class Components.Broker.BrokerFactory.InterfaceNames[source]

An enumeration.

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

next() → tradingbot.Interfaces.Market.Market[source]

Return the next market from the configured source

reset() → None[source]

Reset internal market pointer to the beginning

search_market(search: str) → tradingbot.Interfaces.Market.Market[source]

Tries to find the market which id matches the given search string. If successful return the market snapshot. Raise an exception when multiple markets match the search string

2.2.2.1. Enums

class Components.MarketProvider.MarketSource[source]

Available market sources: local file list, watch list, market navigation through API, etc.

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

is_market_open(timezone: str) → bool[source]

Return True if the market is open, false otherwise

  • timezone: string representing the timezone
wait_for(time_amount_type: Components.TimeProvider.TimeAmount, amount: float = -1.0) → None[source]

Wait for the specified amount of time. An TimeAmount type can be specified

2.2.3.1. Enums

class Components.TimeProvider.TimeAmount[source]

Types of amount of time to wait for

2.2.4. Backtester

class Components.Backtester.Backtester(broker: tradingbot.Components.Broker.Broker.Broker, strategy: Union[tradingbot.Strategies.SimpleMACD.SimpleMACD, tradingbot.Strategies.WeightedAvgPeak.WeightedAvgPeak])[source]

Provides capability to backtest markets on a defined range of time

print_results() → None[source]

Print backtest result in log file

start(market: tradingbot.Interfaces.Market.Market, start_dt: datetime.datetime, end_dt: datetime.datetime) → None[source]

Backtest the given market within the specified range

2.2.5. Configuration

class Components.Configuration.Configuration(dictionary: Dict[str, Any])[source]

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 percentage(part: Union[int, float], whole: Union[int, float]) → Union[int, float][source]

Return the percentage value of the part on the whole

static percentage_of(percent: Union[int, float], whole: Union[int, float]) → Union[int, float][source]

Return the value of the percentage on the whole

2.2.6.1. Enums

class Components.Utils.TradeDirection[source]

Enumeration that represents the trade direction in the market: NONE means no action to take.

class Components.Utils.Interval[source]

Time intervals for price and technical indicators requests

2.2.6.2. Exceptions

class Components.Utils.MarketClosedException[source]

Error to notify that the market is currently closed

class Components.Utils.NotSafeToTradeException[source]

Error to notify that it is not safe to trade

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

class Interfaces.Market.Market[source]

Represent a tradable market with latest price information

2.3.2. MarketHistory

class Interfaces.MarketHistory.MarketHistory(market: tradingbot.Interfaces.Market.Market, date: List[str], high: List[float], low: List[float], close: List[float], volume: List[float])[source]

2.3.3. MarketMACD

class Interfaces.MarketMACD.MarketMACD(market: tradingbot.Interfaces.Market.Market, date: List[str], macd: List[float], signal: List[float], hist: List[float])[source]

2.3.4. Position

class Interfaces.Position.Position(**kargs)[source]

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.

run(market: tradingbot.Interfaces.Market.Market) → Tuple[tradingbot.Components.Utils.TradeDirection, Optional[float], Optional[float]][source]

Run the strategy against the specified market

set_open_positions(positions: List[tradingbot.Interfaces.Position.Position]) → None[source]

Set the account open positions

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
initialise() → None[source]

Initialise SimpleMACD strategy

read_configuration(config: tradingbot.Components.Configuration.Configuration) → None[source]

Read the json configuration

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

initialise() → None[source]

Initialise the strategy

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.

read_configuration(config: tradingbot.Components.Configuration.Configuration) → None[source]

Read the json configuration

weighted_avg_and_std(values: numpy.ndarray, weights: numpy.ndarray) → Tuple[float, float][source]

Return the weighted average and standard deviation.

values, weights – Numpy ndarrays with the same shape.