Python

WARNING: All these source codes are only examples used for testing. We don’t provide any guarantee or responsibility about it. Use these examples at your own risk.

Examples using python 3.6.8

Basic Examples for MT5 (for MT4 click here)

Example 1: Get actual EURUSD price from MT5 using Python

import socket
import sys
import json


buffer_size = 326582
host = "127.0.0.1"
port = 77           # Default command port used by the server 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)     # 3 seconds timeout if we don't receive response from the API
s.connect((host, port))

s.sendall(b'{"MSG": "QUOTE", "SYMBOL": "EURUSD"}\r\n')
print(s.recv(buffer_size).decode('ascii'))

Reply:

{
   "MSG":"QUOTE",
   "SYMBOL":"EURUSD",
   "ASK":1.08293,
   "BID":1.08291,
   "FLAGS":6,
   "TIME":"2022.04.13 08:33:48.0",
   "VOLUME":0,
   "ERROR_ID":0,
   "ERROR_DESCRIPTION":"The operation completed successfully"
}

Example 2: Send Order to MT5 using Python

import socket
import sys
import json


buffer_size = 326582
host = "127.0.0.1"
port = 77           # Default command port used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)     # 3 seconds timeout if we don't receive response from the API
s.connect((host, port))

s.sendall(b'{"MSG": "ORDER_SEND", "SYMBOL": "EURUSD","TYPE":"ORDER_TYPE_BUY","VOLUME":0.02}\r\n')
print(s.recv(buffer_size).decode('ascii'))

Reply:

{"MSG":"ORDER_SEND","RETCODE":10009,"DEAL":2015119247,"ORDER":2020570871,"VOLUME":0.10,"PRICE":1.064860,"BID":1.064830,"ASK":1.064860,"REQUEST_ID":3136973155,"RETCODE_EXTERNAL":0,"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}

Example 3: Stream actual EURUSD price from MT5 using Python

import socket
import sys
import json

buffer_size = 326582

s_cmd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_cmd.settimeout(3)     # 3 seconds timeout if we don't receive response from the API
s_cmd.connect(("127.0.0.1", 77)) # Command port

s_cmd.sendall(b'{"MSG": "TRACK_PRICES", "SYMBOLS": ["EURUSD"]}\r\n')
print(s_cmd.recv(buffer_size).decode('ascii'))

s_data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_data.connect(("127.0.0.1", 78)) # Data port for receiving prices

while True:
   print(s_data.recv(buffer_size).decode('ascii'))

Reply:

{"MSG":"TRACK_PRICES","SUCCESS":["EURUSD"],"ERROR_ID":0,"ERROR_DESCRIPTION":"The operation completed successfully"}

{"TIME":"2022.04.13 09:08:02","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18404}
{"TIME":"2022.04.13 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08385,"VOLUME":18405}
{"TIME":"2022.04.13 09:08:03","SYMBOL":"EURUSD","ASK":1.08386,"BID":1.08384,"VOLUME":18407}
{"TIME":"2022.04.13 09:08:04","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08380,"VOLUME":18408}
{"TIME":"2022.04.13 09:08:05","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08382,"VOLUME":18408}
{"TIME":"2022.04.13 09:08:05","SYMBOL":"EURUSD","ASK":1.08385,"BID":1.08382,"VOLUME":18410}
{"TIME":"2022.04.13 09:08:06","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18411}
{"TIME":"2022.04.13 09:08:06","SYMBOL":"EURUSD","ASK":1.08384,"BID":1.08381,"VOLUME":18411}
{"TIME":"2022.04.13 09:08:07","SYMBOL":"EURUSD","ASK":1.08383,"BID":1.08381,"VOLUME":18412}
...

Advanced Examples

Example 1: Get actual EURUSD price from MT5 (using JSON library) with Python

import socket
import sys
import json

buffer_size = 326582

def SendCommand(farg):
    dataToSend = json.dumps(farg) + "\r\n"
    s.send(dataToSend.encode('ascii'))
    return json.loads(s.recv(buffer_size).decode('ascii'))
    
host = "127.0.0.1"
port = 77                   # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) # 3 seconds timeout if API does not respond

s.connect((host, port))

JSONobject = {}
JSONobject['MSG'] = 'QUOTE'
JSONobject['SYMBOL'] = 'EURUSD' # Symbol is case sensitive

JSONresult = SendCommand(JSONobject)

print('RAW JSON message received:',JSONresult)
print('Symbol:',JSONresult['SYMBOL'])
print('Ask:',JSONresult['ASK'])
print('Bid:',JSONresult['BID'])

Reply:

RAW JSON message received: {'MSG': 'QUOTE', 'SYMBOL': 'EURUSD', 'ASK': 1.08308, 'BID': 1.08306, 'FLAGS': 6, 'TIME': '2022.04.13 09:18:32.0', 'VOLUME': 0, 'ERROR_ID': 0, 'ERROR_DESCRIPTION': 'The operation completed successfully'}

Symbol: EURUSD
Ask: 1.08308
Bid: 1.08306

Example 2: Stream OHLC data from MT5 (using JSON library) with Python

import socket
import sys
import json

buffer_size = 326582

def SendCommand(farg):
    dataToSend = json.dumps(farg) + "\r\n"
    s_cmd.send(dataToSend.encode('ascii'))
    return json.loads(s_cmd.recv(buffer_size).decode('ascii'))

s_cmd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_cmd.settimeout(3)
s_cmd.connect(("127.0.0.1", 77)) # Command port

s_data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_data.connect(("127.0.0.1", 78)) # Data port

JSONobject = {}
subJSONobject = {}
subJSONobject['SYMBOL'] = 'EURUSD'
subJSONobject['TIMEFRAME'] = 'PERIOD_M1'
subJSONobject['DEPTH'] = 1

JSONobject['MSG'] = 'TRACK_OHLC'
JSONobject['OHLC'] = [subJSONobject]

JSONresult = SendCommand(JSONobject)

print('RAW JSON message received:',JSONresult)

while True:
    dataReceived = s_data.recv(buffer_size).decode('ascii')
    #print('RAW data received:',dataReceived)

    JSONprice = json.loads(dataReceived)
    
    if JSONprice["MSG"] == "TRACK_OHLC":
    	print("Time:",JSONprice['OHLC'][0]['TIME'],"Symbol:",JSONprice['SYMBOL'],"Open:",JSONprice['OHLC'][0]['OPEN'],"Close:",JSONprice['OHLC'][0]['CLOSE'],"High:",JSONprice['OHLC'][0]['HIGH'],"Low:",JSONprice['OHLC'][0]['LOW'])

Reply:

RAW JSON message received: {'MSG': 'TRACK_OHLC', 'SUCCESS': ['EURUSD'], 'ERROR_ID': 0, 'ERROR_DESCRIPTION': 'The operation completed successfully'}

Time: 2022.04.13 09:48:00 Symbol: EURUSD Open: 1.08346 Close: 1.0835 High: 1.08356 Low: 1.08335
Time: 2022.04.13 09:49:00 Symbol: EURUSD Open: 1.08351 Close: 1.08352 High: 1.08353 Low: 1.08343
Time: 2022.04.13 09:50:00 Symbol: EURUSD Open: 1.08352 Close: 1.08346 High: 1.08356 Low: 1.08341
Time: 2022.04.13 09:51:00 Symbol: EURUSD Open: 1.08348 Close: 1.08341 High: 1.08353 Low: 1.08338
Time: 2022.04.13 09:52:00 Symbol: EURUSD Open: 1.08342 Close: 1.08327 High: 1.08343 Low: 1.08322
Time: 2022.04.13 09:53:00 Symbol: EURUSD Open: 1.08324 Close: 1.08321 High: 1.08329 Low: 1.08311
Time: 2022.04.13 09:54:00 Symbol: EURUSD Open: 1.08322 Close: 1.08344 High: 1.08345 Low: 1.08322
Time: 2022.04.13 09:55:00 Symbol: EURUSD Open: 1.08345 Close: 1.08357 High: 1.08359 Low: 1.08339

Example 3: Export Trade History from MT5 to a CSV file using Python

# Example 3 (Advanced) - Export Trade History from MT5 to a CSV file
# 
# PREREQUISITE: Install MTsocketAPI in your Metatrader 5 using the following link https://www.mtsocketapi.com/doc5/installation.html
#
# WARNING: All these source codes are only examples for testing purposes. 
# WARNING: We don’t provide any guarantee or responsibility about it. 
# WARNING: Use these examples at your own risk.

import socket
import sys
import json
import csv

buffer_size = 326582

def SendCommand(farg):
    dataToSend = json.dumps(farg) + "\r\n"
    s.send(dataToSend.encode('ascii'))
    return json.loads(s.recv(buffer_size).decode('ascii'))
    
host = "127.0.0.1"
port = 77                   # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) # 3 seconds timeout if API does not respond

s.connect((host, port))

JSONobject = {}
JSONobject['MSG'] = 'TRADE_HISTORY'
JSONobject['MODE'] = 'POSITIONS'
JSONobject['FROM_DATE'] = '2023/08/23 00:00:00'
JSONobject['TO_DATE'] = '2023/08/25 00:00:00'

JSONresult = SendCommand(JSONobject)

#print('RAW JSON message received:',JSONresult)

header = ['SYMBOL', 'MAGIC', 'TICKET', 'OPEN_TIME','CLOSE_TIME','PRICE_OPEN','PRICE_CLOSE','TYPE','LOTS','STOP_LOSS','TAKE_PROFIT','SWAP','COMMISSION','COMMENT','PROFIT']

f = open('History.csv', 'w')
writer = csv.writer(f)
writer.writerow(header)

for item in JSONresult['POSITIONS']:
    print('Exported order:',item['TICKET'])
    row = [item['SYMBOL'],item['MAGIC'],item['TICKET'],item['OPEN_TIME'],item['CLOSE_TIME'],item['PRICE_OPEN'],item['PRICE_CLOSE'],item['TYPE'],item['VOLUME'],item['SL'],item['TP'],item['SWAP'],item['COMMISSION'],item['COMMENT'],item['PROFIT']]
    writer.writerow(row)

f.close()

print('Exported successfully!')

Reply:

Exported order: 2295465108
Exported order: 2295467196
Exported order: 2295467197
Exported order: 2295532403
Exported successfully!

Have you found any bug or error? Please notify us.