img

Retrieve Live Price Information from MetaTrader 5 with Your Python Trading Bot

img
valuezone 12 December 2022

Retrieve Live Price Information from MetaTrader 5 with Your Python Trading Bot

Integrating live pricing data into an algorithmic trading bot provides you with many options. Some traders use this information to keep track of their risk. Others use the information to make decisions on their overall portfolio.

It’s critical to nail this functionality. Getting it done right ensures that your trading bot has the most up-to-date pricing information available, and provides insight into the state of the market. It can provide you with a way to dynamically adjust your trailing stops, or stop trading when the spread reaches a certain level.

Get wrong or delayed, and you can miss critical market moments.

In this chapter, I’ll show you how to retrieve live pricing data and then calculate the spread.

The Bid-Ask Spread

The bid-ask spread refers to the difference between a bid (the price a buyer is willing to pay) and the ask (the price a seller is willing to sell at), and it’s often referred to as ‘the spread’. In the resources section at the bottom of the chapter, I’ve included a link to a page that explains this further.

Why It Matters

When it comes to your algorithmic trading bot, the spread can be used to indicate the strength of the market of a different symbol.

For instance, if you’re trading the USDJPY Forex pair, you’ll often notice that in the time between the US FOREX market close and the early Australian market open, the spread often increases dramatically. This is an indication that the market does not have a lot of buyers/sellers. Depending on what algorithmic trading approach you’re using, this might be a huge opportunity or a huge increase in risk.

Knowing how to calculate the spread means you can fine-tune your trading bot to maximize your returns and minimize your risk.

How it Relates to MetaTrader 5

In MetaTrader, pricing information is referred to as a tick. Each tick contains several fields, including for our purposes:

  1. Time
  2. Bid
  3. Ask

Using this information, you can calculate the spread as the difference between the Bid and the Ask.

Note. If you’d like more information about live tick data from MetaTrader 5, check out the API documentation, linked in the resources section.

Retrieve Live Price Data

Overview

To retrieve the full price data for a symbol in MetaTrader, the following steps are needed:

  1. Retrieve the latest tick information from MetaTrader
  2. Calculate the bid-ask spread
  3. Return a dictionary object with the information

All work will be conducted in the mt5_interaction.py file in metatrader_lib.

How To Retrieve Latest Tick Data from MetaTrader 5 with Python

Here’s the code to retrieve the latest tick for a symbol from MetaTrader:

def retrieve_latest_tick(symbol):
"""
Function to retrieve the latest tick for a symbol
:param symbol: String
:return: Dictionary object
"""

# Retrieve the tick information
tick = MetaTrader5.symbol_info_tick(symbol)._asdict()
print(tick)

How to Calculate a Spread from MetaTrader 5 Tick Data with Python

To calculate the spread, calculate the difference between the bid and the ask, and then append the result to the dictionary object. Here’s what your retrieve_latest_tick should look like:

def retrieve_latest_tick(symbol):
"""
Function to retrieve the latest tick for a symbol
:param symbol: String
:return: Dictionary object
"""

# Retrieve the tick information
tick = MetaTrader5.symbol_info_tick(symbol)._asdict()
spread = tick['ask'] - tick['bid']
tick['spread'] = spread
return tick

Make It So

To demonstrate the retrieval of data, update your __main__ in main.py as follows:

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Import project settings
project_settings = get_project_settings(import_filepath=import_filepath)
# Check Exchanges
check_exchanges(project_settings=project_settings)
# Retreive Tick Data
tick = mt5_interaction.retrieve_latest_tick("BTCUSD.a") # Add in whatever symbol you'd like to check
print(tick)

If you’ve set everything up correctly, you should receive a dictionary object similar to the below (your values may be different depending on when you run it and for which symbol):

{'time': 1670811044, 'bid': 17033.64, 'ask': 17038.6, 'last': 0.0, 'volume': 0, 'time_msc': 1670811044785, 'flags': 6, 'volume_real': 0.0, 'spread': 4.959999999999127}

Note. Time and time_MSC are both in Unix time if you need to convert them.

Enjoy!

def retrieve_latest_tick(symbol):
"""
Function to retrieve the latest tick for a symbol
:param symbol: String
:return: Dictionary object
"""
# Retrieve the tick information
tick = MetaTrader5.symbol_info_tick(symbol)._asdict()
spread = tick['ask'] - tick['bid']
tick['spread'] = spread
return tick
view rawmt5_interaction.py hosted with ❤ by GitHub