MT4 Client gRPC example for C#

MT4 Client gRPC example for C#

Methods browser:
https://mtapi.online/grpcdocs/mt4protoinfo.html

Ready to run project:
https://git.mtapi.io/root/grpc-proto/-/archive/main/grpc-proto-main.zip?path=mt4/csharpExample

Proto file:
https://git.mtapi.io/root/grpc-proto/-/raw/main/mt4/protos/mt4.proto?inline=false

var channel = GrpcChannel.ForAddress("https://mt4grpc.mtapi.io:443");
var connection = new Connection.ConnectionClient(channel);
var subscriptions = new Subscriptions.SubscriptionsClient(channel);
var service = new  Service.ServiceClient(channel);
var tarding = new Trading.TradingClient(channel);
var mt4 = new MT4.MT4Client(channel);
var streams = new Streams.StreamsClient(channel);
var connectRequest = new ConnectRequest
{
    Host = "mt4-demo.roboforex.com",
    Password = "ehj4bod",
    Port = 443,
    User = 500476959,
};
var reply = connection.Connect(connectRequest);
if(reply.Error != null)
    throw new Exception(reply.Error.Message);
Console.WriteLine("Connect response: " + reply);
var id = reply.Result;
var summaryReq = new AccountSummaryRequest()
{
    Id = id
};
var summaryReply = mt4.AccountSummary(summaryReq);
if (summaryReply.Error != null)
    throw new Exception(summaryReply.Error.Message);
Console.WriteLine("AccountBalance: " + summaryReply.Result.Balance);

var subscribeRequest = new SubscribeRequest
{
    Id = id,
    Interval = 0,
    Symbol = "EURUSD",
};
var subscribeReply = subscriptions.Subscribe(subscribeRequest);
if (subscribeReply.Error != null)
    throw new Exception(subscribeReply.Error.Message);
Console.WriteLine("Subscribe response: " + subscribeReply);

var onQuoteRequest = new OnQuoteRequest
{
    Id = id,
};
try
{
    using var streamingCall = streams.OnQuote(onQuoteRequest);
    await foreach (var onQuoteReply in streamingCall.ResponseStream.ReadAllAsync())
    {
        Console.WriteLine(onQuoteReply);
    }
    Console.WriteLine("Stream completed.");
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
    Console.WriteLine("Stream cancelled.");
}
channel.ShutdownAsync().Wait();

Leave a Reply

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