MT5 Client gRPC example for C#

Created with Sketch.

MT5 Client gRPC example for C#

Table of Contents

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

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

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

using Grpc.Core;
using Grpc.Net.Client;
using Mt5Grpc;

var channel = GrpcChannel.ForAddress("https://mt5grpc.mtapi.io:443");
var connection = new Connection.ConnectionClient(channel);
var subscriptions = new Subscriptions.SubscriptionsClient(channel);
var service = new  Service.ServiceClient(channel);
var trading = new Trading.TradingClient(channel);
var mt5 = new MT5.MT5Client(channel);
var streams = new Streams.StreamsClient(channel);
var connectRequest = new ConnectRequest
{
    Host = "78.140.180.198",
    Password = "tecimil4",
    Port = 443,
    User = 62333850,
};
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 = mt5.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,
};
var cancellationSource = new CancellationTokenSource();
var quoteCount = 0;
try
{
    using var streamingCall = streams.OnQuote(onQuoteRequest, new CallOptions(cancellationToken: cancellationSource.Token));
    await foreach (var onQuoteReply in streamingCall.ResponseStream.ReadAllAsync())
    {
        Console.WriteLine(onQuoteReply);
        quoteCount++;
        if (quoteCount == 10)
            cancellationSource.Cancel();
    }
    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 *