Skip to content

Examples

The package includes a complete example for MetaTrader 5 and another for MetaTrader 4 in each language (see Getting started). The programs below show the essentials.

Connect, read prices and send an order

using MtSocketApi;

var client = new MT5WebClient("wss://web.metatrader.app/terminal",
    new MT5WebClientOptions { LicenseKey = "YOUR-LICENSE-KEY" });
await client.ConnectAsync();
await client.LoginAsync(111111, "mypass");

Account account = await client.AccountInfoAsync();
Console.WriteLine($"Balance: {account.Balance} {account.Currency}");

var symbols = await client.LoadSymbolsAsync();
SymbolEntry eurusd = symbols.Find(s => s.Name == "EURUSD")!;
client.TickReceived += (_, t) => Console.WriteLine($"EURUSD {t.Bid} / {t.Ask}");
await client.SubscribeAsync(eurusd);

TradeResult r = await client.OpenMarketOrderAsync(eurusd, Side.Buy, 0.01);
Console.WriteLine($"{r.Retcode} {r.RetcodeText} at {r.Price}");
from mtsocketapi import MT5WebClient, MT5WebClientOptions, Side

client = MT5WebClient("wss://web.metatrader.app/terminal",
                      MT5WebClientOptions(license_key="YOUR-LICENSE-KEY"))
client.connect()
client.login(111111, "mypass")

account = client.account_info()
print(f"Balance: {account.balance} {account.currency}")

eurusd = next(s for s in client.load_symbols() if s.name == "EURUSD")
client.on_tick = lambda t: print("EURUSD", t.bid, t.ask)
client.subscribe([eurusd])

r = client.open_market_order(eurusd, Side.BUY, 0.01)
print(r.retcode, r.retcode_text, "at", r.price)
import com.mtsocketapi.*;

MT5WebClient client = new MT5WebClient("wss://web.metatrader.app/terminal",
        new MT5WebClientOptions().licenseKey("YOUR-LICENSE-KEY"));
client.connect();
client.login(111111L, "mypass");

Account account = client.accountInfo();
System.out.println("Balance: " + account.getBalance() + " " + account.getCurrency());

SymbolEntry eurusd = client.loadSymbols().stream()
        .filter(s -> s.getName().equals("EURUSD")).findFirst().get();
client.setOnTick(t -> System.out.println("EURUSD " + t.getBid() + " / " + t.getAsk()));
client.subscribe(eurusd);

TradeResult r = client.openMarketOrder(eurusd, Side.BUY, 0.01);
System.out.println(r.getRetcode() + " " + r.getRetcodeText() + " at " + r.getPrice());
#include <mtsocketapi/mtsocketapi.hpp>
#include <iostream>
using namespace mtsocketapi;

int main() {
    MT5WebClientOptions options;
    options.license_key = "YOUR-LICENSE-KEY";
    MT5WebClient client("wss://web.metatrader.app/terminal", options);
    client.connect();
    client.login(111111, "mypass");

    Account account = client.account_info();
    std::cout << "Balance: " << account.balance << " " << account.currency << "\n";

    for (const SymbolEntry& s : client.load_symbols())
        if (s.name == "EURUSD") {
            client.subscribe({s});
            TradeResult r = client.open_market_order(s, Side::Buy, 0.01);
            std::cout << r.retcode << " " << r.retcode_text << " at " << r.price << "\n";
        }
}
use mtsocketapi::*;

fn main() -> Result<()> {
    let options = MT5WebClientOptions { license_key: Some("YOUR-LICENSE-KEY".into()), ..Default::default() };
    let client = MT5WebClient::new("wss://web.metatrader.app/terminal", options)?;
    client.connect()?;
    client.login(111111, "mypass")?;

    let account = client.account_info()?;
    println!("Balance: {} {}", account.balance, account.currency);

    let eurusd = client.load_symbols()?.into_iter().find(|s| s.name == "EURUSD").unwrap();
    client.on_tick(|t| println!("EURUSD {:?} / {:?}", t.bid, t.ask));
    client.subscribe(std::slice::from_ref(&eurusd))?;

    let r = client.open_market_order(&eurusd, Side::Buy, 0.01, None, None, "", None)?;
    println!("{} {} at {}", r.retcode, r.retcode_text, r.price);
    Ok(())
}

A rejected order is not an error: check the result code that the broker returns (retcode).

The same with MetaTrader 4

The only change is the client: MT4WebClient with the name of the server, and MT4WebClientOptions.

using MtSocketApi;

var client = new MT4WebClient("MetaQuotes-Demo",
    new MT4WebClientOptions { LicenseKey = "YOUR-LICENSE-KEY" });
await client.ConnectAsync();
await client.LoginAsync(111111, "mypass");

Account account = await client.AccountInfoAsync();
Console.WriteLine($"Balance: {account.Balance} {account.Currency}");

var symbols = await client.LoadSymbolsAsync();
SymbolEntry eurusd = symbols.Find(s => s.Name == "EURUSD")!;
client.TickReceived += (_, t) => Console.WriteLine($"EURUSD {t.Bid} / {t.Ask}");
await client.SubscribeAsync(eurusd);

TradeResult r = await client.OpenMarketOrderAsync(eurusd, Side.Buy, 0.01);
Console.WriteLine($"{r.Retcode} {r.RetcodeText} at {r.Price}");
from mtsocketapi import MT4WebClient, MT4WebClientOptions, Side

client = MT4WebClient("MetaQuotes-Demo",
                      MT4WebClientOptions(license_key="YOUR-LICENSE-KEY"))
client.connect()
client.login(111111, "mypass")

account = client.account_info()
print(f"Balance: {account.balance} {account.currency}")

eurusd = next(s for s in client.load_symbols() if s.name == "EURUSD")
client.on_tick = lambda t: print("EURUSD", t.bid, t.ask)
client.subscribe([eurusd])

r = client.open_market_order(eurusd, Side.BUY, 0.01)
print(r.retcode, r.retcode_text, "at", r.price)
import com.mtsocketapi.*;

MT4WebClient client = new MT4WebClient("MetaQuotes-Demo",
        new MT4WebClientOptions().licenseKey("YOUR-LICENSE-KEY"));
client.connect();
client.login(111111L, "mypass");

Account account = client.accountInfo();
System.out.println("Balance: " + account.getBalance() + " " + account.getCurrency());

SymbolEntry eurusd = client.loadSymbols().stream()
        .filter(s -> s.getName().equals("EURUSD")).findFirst().get();
client.setOnTick(t -> System.out.println("EURUSD " + t.getBid() + " / " + t.getAsk()));
client.subscribe(eurusd);

TradeResult r = client.openMarketOrder(eurusd, Side.BUY, 0.01);
System.out.println(r.getRetcode() + " " + r.getRetcodeText() + " at " + r.getPrice());
#include <mtsocketapi/mtsocketapi.hpp>
#include <iostream>
using namespace mtsocketapi;

int main() {
    MT4WebClientOptions options;
    options.license_key = "YOUR-LICENSE-KEY";
    MT4WebClient client("MetaQuotes-Demo", options);
    client.connect();
    client.login(111111, "mypass");

    Account account = client.account_info();
    std::cout << "Balance: " << account.balance << " " << account.currency << "\n";

    for (const SymbolEntry& s : client.load_symbols())
        if (s.name == "EURUSD") {
            client.subscribe({s});
            TradeResult r = client.open_market_order(s, Side::Buy, 0.01);
            std::cout << r.retcode << " " << r.retcode_text << " at " << r.price << "\n";
        }
}
use mtsocketapi::*;

fn main() -> Result<()> {
    let options = MT4WebClientOptions { license_key: Some("YOUR-LICENSE-KEY".into()), ..Default::default() };
    let client = MT4WebClient::new("MetaQuotes-Demo", options)?;
    client.connect()?;
    client.login(111111, "mypass")?;

    let account = client.account_info()?;
    println!("Balance: {} {}", account.balance, account.currency);

    let eurusd = client.load_symbols()?.into_iter().find(|s| s.name == "EURUSD").unwrap();
    client.on_tick(|t| println!("EURUSD {:?} / {:?}", t.bid, t.ask));
    client.subscribe(std::slice::from_ref(&eurusd))?;

    let r = client.open_market_order(&eurusd, Side::Buy, 0.01, None, None, "")?;
    println!("{} {} at {}", r.retcode, r.retcode_text, r.price);
    Ok(())
}

MetaTrader 4 return codes are translated to the MetaTrader 5 codes (10009 = done), so the same checks work for both platforms; the original MT4 code is in the comment of the result.

Several accounts in one program

Each client is one connection, and a program can keep as many clients as it needs: copy trading, hedging, monitoring or account management. Several live accounts at the same time need the Unlimited plan.

using MtSocketApi;

const string Key = "YOUR-LICENSE-KEY";   // Unlimited plan
var accounts = new[] {
    ("wss://web.metatrader.app/terminal", 111111L, "pass1"),
    ("wss://web.metatrader.app/terminal", 222222L, "pass2"),
    ("wss://web.metatrader.app/terminal", 333333L, "pass3"),
};

var clients = new List<MT5WebClient>();
foreach (var (url, login, password) in accounts)
{
    var c = new MT5WebClient(url, new MT5WebClientOptions { LicenseKey = Key });
    await c.ConnectAsync();
    await c.LoginAsync(login, password);
    clients.Add(c);
}

foreach (var c in clients)                   // one program, three live accounts
{
    Account a = await c.AccountInfoAsync();
    Console.WriteLine($"{a.Name} {a.Balance} {a.Currency}");
}
from mtsocketapi import MT5WebClient, MT5WebClientOptions

KEY = "YOUR-LICENSE-KEY"   # Unlimited plan
accounts = [("wss://web.metatrader.app/terminal", 111111, "pass1"),
            ("wss://web.metatrader.app/terminal", 222222, "pass2"),
            ("wss://web.metatrader.app/terminal", 333333, "pass3")]

clients = []
for url, login, password in accounts:
    c = MT5WebClient(url, MT5WebClientOptions(license_key=KEY))
    c.connect()
    c.login(login, password)
    clients.append(c)

for c in clients:                     # one program, three live accounts
    a = c.account_info()
    print(a.name, a.balance, a.currency)
import com.mtsocketapi.*;
import java.util.*;

String key = "YOUR-LICENSE-KEY";   // Unlimited plan
String url = "wss://web.metatrader.app/terminal";
long[] logins = { 111111L, 222222L, 333333L };
String[] passwords = { "pass1", "pass2", "pass3" };

List<MT5WebClient> clients = new ArrayList<>();
for (int i = 0; i < logins.length; i++) {
    MT5WebClient c = new MT5WebClient(url, new MT5WebClientOptions().licenseKey(key));
    c.connect();
    c.login(logins[i], passwords[i]);
    clients.add(c);
}

for (MT5WebClient c : clients) {      // one program, three live accounts
    Account a = c.accountInfo();
    System.out.println(a.getName() + " " + a.getBalance() + " " + a.getCurrency());
}
#include <mtsocketapi/mtsocketapi.hpp>
#include <iostream>
#include <memory>
#include <vector>
using namespace mtsocketapi;

int main() {
    struct Login { std::string url; std::int64_t login; std::string password; };
    std::vector<Login> accounts = {
        {"wss://web.metatrader.app/terminal", 111111, "pass1"},
        {"wss://web.metatrader.app/terminal", 222222, "pass2"},
        {"wss://web.metatrader.app/terminal", 333333, "pass3"},
    };
    MT5WebClientOptions options;
    options.license_key = "YOUR-LICENSE-KEY";   // Unlimited plan

    std::vector<std::unique_ptr<MT5WebClient>> clients;
    for (const auto& acc : accounts) {
        auto c = std::make_unique<MT5WebClient>(acc.url, options);
        c->connect();
        c->login(acc.login, acc.password);
        clients.push_back(std::move(c));
    }

    for (auto& c : clients) {         // one program, three live accounts
        Account a = c->account_info();
        std::cout << a.name << " " << a.balance << " " << a.currency << "\n";
    }
}
use mtsocketapi::*;

fn main() -> Result<()> {
    let accounts = [
        ("wss://web.metatrader.app/terminal", 111111, "pass1"),
        ("wss://web.metatrader.app/terminal", 222222, "pass2"),
        ("wss://web.metatrader.app/terminal", 333333, "pass3"),
    ];

    let mut clients = Vec::new();
    for (url, login, password) in accounts {
        let options = MT5WebClientOptions { license_key: Some("YOUR-LICENSE-KEY".into()), ..Default::default() }; // Unlimited plan
        let c = MT5WebClient::new(url, options)?;
        c.connect()?;
        c.login(login, password)?;
        clients.push(c);
    }

    for c in &clients {               // one program, three live accounts
        let a = c.account_info()?;
        println!("{} {} {}", a.name, a.balance, a.currency);
    }
    Ok(())
}