MT4 grpc Client for Python example

Created with Sketch.

MT4 grpc Client for Python example

Table of Contents

Methods browser.

Ready to run example.

Proto file.

Python installation. Do not forget to install PIP python package manager.

Install grpcio-tools package:

pip install grpcio-tools

To run the code, you need to create an autogenerated libraries. You can find it in the repository, or generate it by yourself.

Grpc python libraries generation:

Once grpcio-tools is installed, you can get google protobuf python libraries form that package. Usually it is located in the python folder

Python\Python312\site-packages\google

Copy google folder to the project folder. It is needed for further library autogeneration.

Put mt4 proto file to the project folder. Or check if it exists in you project folder

Run libraries generator:

python -m grpc_tools.protoc --proto_path=.  --python_out=. --pyi_out=. --grpc_python_out=. ./mt4.proto

It gives you new libraries which describe service and classies for grpc API endpoints.

Use this files as source of grpc service stubs

Now, you can run the script.
Windows example:

"C:\Program Files\Python312\python.exe" "C:/Program Files/JetBrains/PyCharm 2023.2.4/plugins/python/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 63998 --file E:\MT4Repositories\grpc-proto\mt4\pythonExample\PythonGrpc.py

Script:

from mt4_pb2 import *
from mt4_pb2_grpc import *

channel = grpc.secure_channel('mt4grpc.mtapi.io:443', grpc.ssl_channel_credentials())
service = ServiceStub(channel)
mt4 = MT4Stub(channel)
trading = TradingStub(channel)
connection = ConnectionStub(channel)
streams = StreamsStub(channel)
subscriptions = SubscriptionsStub(channel)

req = ConnectRequest(
    user=500476959,
    password='ehj4bod',
    host="mt4-demo.roboforex.com",
    port=443)
res = connection.Connect(req)
if res.error.message:
    print(res.error)
    exit()
token = res.result
print(token)

req = AccountSummaryRequest(
    id=token)
res = mt4.AccountSummary(req)
if res.error.message:
    print(res.error)
    exit()
print(res.result)

req = SubscribeRequest(id=token, symbol="EURUSD")
res = subscriptions.Subscribe(req)
if res.error.message:
    print(res.error)
    exit()
print(res.result)

oQuote = streams.OnQuote(OnQuoteRequest(id=token))

while True:
    response = next(oQuote)
    print(response)

Leave a Reply

Your email address will not be published. Required fields are marked *