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[source]

Class that initialise and hold references of main components like the broker interface, the strategy or the epic_ids list

close_open_positions()[source]

Closes all the open positions in the account

init_trading_services(config, credentials)[source]

Create instances of the trading services required, such as web interface for trading and fetch market data.

  • config The configuration json

  • credentials The credentials json

  • return: An instance of Broker class initialised

load_epic_ids_from_local_file(filepath)[source]

Read a file from filesystem containing a list of epic ids. The filepath is defined in config.json file Returns a ‘list’ of strings where each string is a market epic

load_json_file(filepath)[source]

Load a JSON formatted file from the given filepath

  • filepath The filepath including filename and extension

  • Return a dictionary of the loaded json

process_epic_list(epic_list)[source]

Process the given list of epic ids, one by one to find new trades

  • epic_list: list of epic ids as strings

process_market(epic)[source]

Process the givem epic using the defined strategy

  • epic: string representing a market epic id

  • Returns False if market is closed or if account reach maximum margin, otherwise True

process_market_exploration(node_id)[source]

Navigate the markets using IG API to fetch markets id dinamically

  • node_id: The node id to navigate markets in

process_open_positions(positions)[source]

process the open positions to find closing trades

  • positions: json object containing open positions

  • Returns False if an error occurs otherwise True

process_trade(epic)[source]

Process a trade checking if it is a “close position” trade or a new action

process_watchlist(watchlist_name)[source]

Process the markets included in the given IG watchlist

  • watchlist_name: IG watchlist name

read_configuration(config)[source]

Read the configuration from the config json

setup_logging()[source]

Setup the global logging settings

start(argv)[source]

Starts the TradingBot

wait_for_next_market_opening()[source]

Sleep until the next market opening. Takes into account weekends and bank holidays in UK

2.2. Interfaces

The Interfaces module contains all those interfaces with external services used by TradingBot. 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. IGInterface

class Interfaces.IGInterface.IGInterface(config, credentials)[source]

IG broker interface class, provides functions to use the IG REST API

authenticate(credentials)[source]

Authenticate the IGInterface instance with the given credentials

  • credentials: json object containing username, passowrd, default account and api key

  • Returns False if an error occurs otherwise True

close_all_positions()[source]

Try to close all the account open positions.

  • Returns False if an error occurs otherwise True

close_position(position)[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)[source]

Confirm an order from a dealing reference

  • dealRef: dealing reference to confirm

  • Returns False if an error occurs otherwise True

get_account_balances()[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()[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)[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)[source]

Get the list of markets included in the watchlist

  • name: name of the watchlist

get_open_positions()[source]

Returns the account open positions in an json object

  • Returns the json object returned by the IG API

get_positions_map()[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)

get_prices(epic_id, interval, data_range)[source]

Returns past prices for the given epic

  • epic_id: market epic as string

  • interval: resolution of the time series: minute, hours, etc.

  • data_range: amount of datapoint to fetch

  • Returns None if an error occurs otherwise the json object returned by IG API

get_watchlist(id)[source]

Get the watchlist info

  • id: id of the watchlist. If empty id is provided, the function returns the list of all the watchlist in the account

http_get(url)[source]

Perform an HTTP GET request to the url. Return the json object returned from the API if 200 is received Return None if an error is received from the API

macd_dataframe(epic, interval)[source]

Return a datafram with MACD data for the requested market

navigate_market_node(node_id)[source]

Navigate the market node id

  • Returns the json representing the market node

read_configuration(config)[source]

Read the configuration from the config json

set_default_account(accountId)[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, trade_direction, limit, stop)[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.2. AVInterface

class Interfaces.AVInterface.AVInterface(apiKey, config)[source]

AlphaVantage interface class, provides methods to call AlphaVantage API and return the result in useful format handling possible errors.

daily(marketId)[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

get_prices(market_id, interval)[source]

Return the price time series of the requested market with the interval granularity. Return None if the interval is invalid

intraday(marketId, interval)[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, interval)[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, interval)[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)[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)[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.3. Broker

class Interfaces.Broker.Broker(config, services)[source]

This class provides a template interface for all those broker related actions/tasks wrapping the actual implementation class internally

close_all_positions()[source]

IG INDEX API ONLY Attempt to close all the current open positions

close_position(position)[source]

IG INDEX API ONLY Attempt to close the requested open position

get_account_used_perc()[source]

IG INDEX API ONLY Returns the account used value in percentage

get_market_from_watchlist(watchlist_name)[source]

IG INDEX API ONLY Return a name list of the markets in the required watchlist

get_market_info(epic)[source]

IG INDEX API ONLY Return the last available snapshot of the requested market as a dict: - data = {‘market_id’: <value>, ‘bid’: <value>,’offer’: <value>, ‘stop_distance_min’: <value>}

get_open_positions()[source]

IG INDEX API ONLY Returns the current open positions

get_prices(epic, market_id, interval, data_range)[source]
Return historic price of the requested market as a dictionary:
  • data = {‘high’: [], ‘low’: [], ‘close’: [], ‘volume’: []}

macd_dataframe(epic, market_id, interval)[source]

Return a pandas dataframe containing MACD technical indicator for the requested market with requested interval

navigate_market_node(node_id)[source]

IG INDEX API ONLY Return the children nodes of the requested node

to_av_interval(interval)[source]

Convert the Broker Interval to AlphaVantage compatible intervals. Return the converted interval or None if a conversion is not available

trade(epic, trade_direction, limit, stop)[source]

IG INDEX API ONLY Request a trade of the given market

2.3. 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.3.1. Strategy

class Strategies.Strategy.Strategy(config, broker)[source]

Generic strategy template to use as a parent class for custom strategies. Provide safety checks for new trades and handling of open positions.

find_trade_signal(epic_id)[source]

Must override

get_seconds_to_next_spin()[source]

Must override

read_configuration(config)[source]

Must override

2.3.2. StrategyFactory

class Strategies.StrategyFactory.StrategyFactory(config, broker)[source]

Factory class to create instances of Strategies. The class provide an interface to instantiate new objects of a given Strategy name

make_strategy(strategy_name)[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.3.3. SimpleMACD

class Strategies.SimpleMACD.SimpleMACD(config, 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.

calculate_stop_limit(tradeDirection, current_offer, current_bid, limit_perc, stop_perc)[source]

Calculate the stop and limit levels from the given percentages

find_trade_signal(epic_id)[source]

Calculate the MACD of the previous days and find a cross between MACD and MACD signal

  • epic_id: market epic as string

  • Returns TradeDirection, limit_level, stop_level or TradeDirection.NONE, None, None

get_seconds_to_next_spin()[source]

Calculate the amount of seconds to wait for between each strategy spin

read_configuration(config)[source]

Read the json configuration

2.3.4. Weighted Average Peak Detection

class Strategies.WeightedAvgPeak.WeightedAvgPeak(config, broker)[source]

All credits of this strategy goes to GitHub user @tg12.

find_trade_signal(epic_id)[source]

TODO add description of strategy key points

get_seconds_to_next_spin()[source]

Must override

peakdet(v, delta, x=None)[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)[source]

Read the json configuration

weighted_avg_and_std(values, weights)[source]

Return the weighted average and standard deviation.

values, weights – Numpy ndarrays with the same shape.

2.4. Utils

class Utils.Utils[source]

Utility class containing static methods to perform simple general actions

static get_seconds_to_market_opening(from_time)[source]

Return the amount of seconds from now to the next market opening, taking into account UK bank holidays and weekends

static humanize_time(secs)[source]

Convert the given time (in seconds) into a readable format hh:mm:ss

static is_between(time, time_range)[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 is_market_open(timezone)[source]

Return True if the market is open, false otherwise

  • timezone: string representing the timezone

static midpoint(p1, p2)[source]

Return the midpoint

static percentage(part, whole)[source]

Return the percentage value of the part on the whole

static percentage_of(percent, whole)[source]

Return the value of the percentage on the whole