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
-
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
-
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
Navigate the market node id
Returns the json representing the market node
-
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
-
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
-
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_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
IG INDEX API ONLY Return the children nodes of the requested node
-
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¶
2.3.2. StrategyFactory¶
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
-
2.3.4. Weighted Average Peak Detection¶
-
class
Strategies.WeightedAvgPeak.
WeightedAvgPeak
(config, broker)[source]¶ All credits of this strategy goes to GitHub user @tg12.
-
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.
-
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