Skip to content

MT5Sugar - Complete API ReferenceΒΆ

High-level convenience methods for MetaTrader 5 trading automation in C#

MT5Sugar extends MT5Service with convenient methods for:

  • 🎯 Risk-based position sizing (fixed dollar risk)
  • πŸ“Š Automatic volume and price normalization
  • πŸ”„ Bulk operations (close all positions, cancel all orders)
  • πŸ“ˆ DOM (Market Depth) - order book analysis
  • βœ… Pre-flight order validation and margin checking
  • πŸ“‰ P&L monitoring and position statistics

πŸ“– Important: How to Work with Streaming Subscriptions - Complete guide to real-time data streams


[01] πŸ”§ INFRASTRUCTUREΒΆ

Basic infrastructure for working with symbols

Method Description Documentation
EnsureSelected() Ensures symbol is selected and synchronized in MT5 β†’ Docs

[02] πŸ“Έ SNAPSHOTSΒΆ

Instant snapshots of account and symbol state

Method Description Documentation
GetAccountSnapshot() Complete account snapshot (balance, margin, equity) β†’ Docs
GetSymbolSnapshot() Complete symbol snapshot (prices, spread, limits) β†’ Docs

Data classes:

  • AccountSnapshot - account data structure
  • SymbolSnapshot - symbol data structure

[03] πŸ”’ NORMALIZATION & UTILSΒΆ

Utilities for price normalization and unit conversion

Method Description Documentation
GetPointAsync() Get point size for symbol β†’ Docs
GetDigitsAsync() Number of decimal places β†’ Docs
NormalizePriceAsync() Normalize price by TickSize β†’ Docs
PointsToPipsAsync() Convert points to pips β†’ Docs
GetSpreadPointsAsync() Current spread in points β†’ Docs

[04] πŸ“œ HISTORY HELPERSΒΆ

Retrieve order and position history with pagination

Method Description Documentation
OrdersHistoryLast() Closed orders history for N days β†’ Docs
PositionsHistoryPaged() Position history with pagination β†’ Docs

[05] 🌊 STREAMS HELPERS¢

Bounded streaming - reading ticks and trades with limits

Method Description Documentation
ReadTicks() Read N ticks or until timeout β†’ Docs
ReadTrades() Read N trade events or until timeout β†’ Docs

[06] πŸ’Ή TRADING β€” MARKET & PENDINGΒΆ

Placing and managing market and pending orders

Method Description Documentation
PlaceMarket() Place market order (BUY/SELL) β†’ Docs
PlacePending() Place pending order (Limit/Stop) β†’ Docs
ModifySlTpAsync() Modify SL/TP of existing order β†’ Docs
CloseByTicket() Close position by ticket β†’ Docs
CloseAll() Close all positions (with filters) β†’ Docs

[07] βš–οΈ VOLUME & PRICE UTILITIESΒΆ

Critical utilities for volume calculation and price operations

Method Description Documentation
CalcVolumeForRiskAsync() PRIMARY METHOD - calculate volume by risk β†’ Docs
GetVolumeLimitsAsync() Get Min/Max/Step for symbol volume β†’ Docs
NormalizeVolumeAsync() Normalize volume to broker limits β†’ Docs
GetTickValueAndSizeAsync() Get TickValue and TickSize β†’ Docs
PriceFromOffsetPointsAsync() Calculate price from point offset β†’ Docs

[08] πŸ“ PENDING HELPERS (BY POINTS)ΒΆ

Pending orders with point-based distance

Method Description Documentation
BuyLimitPoints() Buy Limit N points below Ask β†’ Docs
SellLimitPoints() Sell Limit N points above Bid β†’ Docs
BuyStopPoints() Buy Stop N points above Ask β†’ Docs
SellStopPoints() Sell Stop N points below Bid β†’ Docs

[09] πŸ’° MARKET BY RISKΒΆ

Market orders with fixed dollar risk

Method Description Documentation
BuyMarketByRisk() BUY with automatic volume calculation by risk β†’ Docs
SellMarketByRisk() SELL with automatic volume calculation by risk β†’ Docs

Example:

// Risk exactly $100 with 50-point SL
await svc.BuyMarketByRisk("EURUSD", stopPoints: 50, riskMoney: 100);


[10] 🧹 BULK CONVENIENCE¢

Bulk operations with orders and positions

Method Description Documentation
CancelAll() Cancel all pending orders β†’ Docs
CloseAllPositions() Close all market positions β†’ Docs
CloseAllPending() Close/cancel all pending orders β†’ Docs

[11] πŸ“Š MARKET DEPTH (DOM)ΒΆ

Level II market data - order book analysis

Method Description Documentation
SubscribeToMarketBookAsync() Subscribe to order book (returns IDisposable) β†’ Docs
GetMarketBookSnapshotAsync() Get order book snapshot β†’ Docs
GetBestBidAskFromBookAsync() Best Bid/Ask from order book β†’ Docs
CalculateLiquidityAtLevelAsync() Calculate liquidity at price level β†’ Docs

Data class:

  • MarketBookSubscription - subscription management

[12] βœ… ORDER VALIDATIONΒΆ

Pre-flight checks to prevent errors

Method Description Documentation
ValidateOrderAsync() Full order validation before sending β†’ Docs
CalculateBuyMarginAsync() Calculate margin for BUY order β†’ Docs
CalculateSellMarginAsync() Calculate margin for SELL order β†’ Docs
CheckMarginAvailabilityAsync() Check free margin sufficiency β†’ Docs

[13] ⏰ SESSION TIME¢

Trading and quote session information

Method Description Documentation
GetQuoteSessionAsync() Quote session time (when prices are visible) β†’ Docs
GetTradeSessionAsync() Trading session time (when trading is allowed) β†’ Docs

[14] πŸ“ˆ POSITION MONITORINGΒΆ

Monitoring and analyzing open positions

Method Description Documentation
GetProfitablePositionsAsync() Get all profitable positions β†’ Docs
GetLosingPositionsAsync() Get all losing positions β†’ Docs
GetTotalProfitLossAsync() Total P&L across all positions β†’ Docs
GetPositionCountAsync() Number of open positions β†’ Docs
GetPositionStatsBySymbolAsync() Position statistics by symbol β†’ Docs

🎯 Common Use Cases¢

Simple market orderΒΆ

// Buy 0.10 lots EURUSD
var result = await svc.PlaceMarket("EURUSD", 0.10, isBuy: true);
Console.WriteLine($"Order #{result.Order} at {result.Price:F5}");

Order with fixed risk ($100)ΒΆ

// Risk $100, stop 50 points, take 150 points
await svc.BuyMarketByRisk("EURUSD",
    stopPoints: 50,
    riskMoney: 100,
    tpPoints: 150);

Margin check before tradingΒΆ

var (hasEnough, free, required) = await svc.CheckMarginAvailabilityAsync(
    "EURUSD", volume: 1.0, isBuy: true);

if (hasEnough)
{
    await svc.PlaceMarket("EURUSD", 1.0, isBuy: true);
}
else
{
    Console.WriteLine($"Insufficient margin: need ${required}, have ${free}");
}

Emergency close on drawdownΒΆ

double totalPL = await svc.GetTotalProfitLossAsync();

if (totalPL < -500)
{
    Console.WriteLine("🚨 Drawdown $500 - closing all positions!");
    await svc.CloseAllPositions();
}

Order book (DOM) analysisΒΆ

using (await svc.SubscribeToMarketBookAsync("EURUSD"))
{
    var book = await svc.GetMarketBookSnapshotAsync("EURUSD");
    var (bestBid, bestAsk) = await svc.GetBestBidAskFromBookAsync("EURUSD");

    var liquidity = await svc.CalculateLiquidityAtLevelAsync(
        "EURUSD", bestBid, isBuy: true);

    Console.WriteLine($"Liquidity at {bestBid}: {liquidity} lots");
}


πŸ“¦ ArchitectureΒΆ

MT5Sugar (Extension Methods) ← You are here
    ↓ Risk-based trading, DOM, bulk operations
    ↓
MT5Service (Mid-level)
    ↓ Typed wrappers, snapshots, validation
    ↓
MT5Account (Low-level)
    ↓ Direct gRPC/Protobuf calls
    ↓
MetaTrader 5 Terminal

πŸ“ ConventionsΒΆ

  • All methods are asynchronous (async Task<T>)
  • Extend MT5Service class (extension methods)
  • Parameter timeoutSec - RPC operation timeout (default 10-20 sec)
  • Parameter ct - CancellationToken for operation cancellation
  • Prices are always absolute, not relative
  • Volumes are always in lots, not currency units
  • Points - minimum price increment
  • Pips - standard unit for traders (1 pip = 10 points for 5-digit)

πŸŽ‰ Ready to use!