Metatrader +Python +Telegram

Matjaž Hozjan
InsiderFinance Wire
4 min readMar 31, 2022

--

Metatrader is a popular platform for trading Forex and even other assets. We can easily say that it is a market-leading platform and brokers love it. It uses its own coding language MQL and the most popular still is MT4 even though MT5 was released a few years back and that first one was causing me headaches when connecting it to python, just now with MT5 things changed and with the MetaTrader5 package, everything works smoothly. That is why I highly recommend using it.

Telegram is a free instant messaging service. As I see it is kind of a number one choice for the crypto world, signal/alert sending, etc… Personally, I am using it just for that and all other messaging is via other chats like WhatsApp, Viber, signal. Telegram is for me “just” for retrieving or sending trading-related messages.

In this article, I will show you a code example of how to gather data from MT5 and send some messages to Telegram with pictures as well. The part where you can store data in a database or file, build indicators from downloaded data is not covered.

Photo by Dimitri Karastelev on Unsplash

How To Connect MT5 and Python?

With help of python of course. And Is fairly simple to be fair. Thanks to the great MetaTrader module for integration with Python.

There are various ways that we can use the package. From trading, backtesting, building custom indicators, etc. Mainly I was using it for HFT trading against brokers once these on the retail side were still possible. Probably content for some of my next stories.

About the code:

Code below will download 1day OHLC data from Metatrader directly. These can be changed to tick or any other timeframe with a simple twist of mt5.TIMEFRAME_D1. The code itself is modified from the code posted at mql5.com to suit my needs. Data in the end is set as Pandas Dataframe. Then it is up to you what to do with it. At one of my recent projects for example I am storing data to MongoDB then am building indicators with help of the ta.volatility package. Then when all parameters are met msg plus picture is sent to telegram directly. Making good alert service for my trading based on my wanted parameters and levels.

# Package import
from datetime import datetime
import MetaTrader5 as mt5
import json
import pandas as pd

def LoadMt5(symbol):
# load credentials from credentials json
with open("credentials.json") as json_file:
config = json.load(json_file)

# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)


# establish connection to MetaTrader 5 terminal
if not mt5.initialize():
print("initialize() failed, error code =", mt5.last_error())
quit()
account = config["account"]
authorized = mt5.login(account, password=config["password"], server=config["server"], path=config["path"])
if authorized:
# display trading account data 'as is'
print(mt5.account_info())
# display trading account data in the form of a list
print("Show account_info()._asdict():")
account_info_dict = mt5.account_info()._asdict()
for prop in account_info_dict:
print(" {}={}".format(prop, account_info_dict[prop]))
else:
print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))
print("initialize() failed, error code =", mt5.last_error())

# current date
now = datetime.utcnow()

# request 120 D1 timeframes as OHLC data
# Download data from MT5
ticks = mt5.copy_rates_from(symbol, mt5.TIMEFRAME_D1, now, 119)
#print("Ticks received:", len(ticks))

symbol_info = mt5.symbol_info(symbol)

# get symbol digits length
symbol_info_dict = symbol_info._asdict()

# shut down connection to the MetaTrader 5 terminal
mt5.shutdown()

# display data on each tick on a new line
count = 0
for tick in ticks:
count += 1
if count >= 10:
break

# create DataFrame out of the obtained data
df = pd.DataFrame(ticks)

# convert time in seconds into the datetime format and OHLC to float
df['time'] = pd.to_datetime(df['time'], unit='s')
df["high"] = df["high"].astype(float)
df["low"] = df["low"].astype(float)
df["close"] = df["close"].astype(float)

return df

print(LoadMt5("EURUSD"))
metatrader, mql, mt5, mt4, python
Python result

Telegram and Python

Sending msg to Telegram can’t be more simple after hectic setup at telegram part is done. Telegram package is what you need and some setup is done at telegram part then the sky’s the limit actually.

BotFather is the bot you need that you will be able to communicate correctly with more than user + chat ID. more details here:

With the below code I am sending some custom text plus pictures of current market levels:

import telegram
import json

#load credentials from credentials.json
with open("credentials.json") as json_file:
config = json.load(json_file)

bot = telegram.Bot(token=config["token"])
text = "Some text"
class bots:
def msg(self, text):
# token ID needs to be obtained as shown earlier.
print("msg send")
print(text)
bot.send_photo(chat_id="@CHATIDHERE", photo=open('chart.png', 'rb'))
bot.sendMessage(chat_id="@CHATIDHERE", text=text)
telegram, bot, python
Telegram with my personal msg and pictures

Credentials.json

{
"account": "MT5acc numb",
"password": "MT5 password",
"server": "Demo 1-MT5",
"path=": "C://Program Files//MT5 Terminal//terminal64.exe",
"token": "TOKEN FOR TELEGRAM"
}

This is powerful knowledge to make some great marketing or self-using reports. Can be used for trading/alerting for FX or any other available symbols at your FX broker. Skipping MT5 part and just using Telegram possibilities to get messages are limitless.

Have fun using code, ideas, and please clap, follow for more!

--

--