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
Navigation by RegionΒΆ
[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 structureSymbolSnapshot- 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");
}
π Related DocumentationΒΆ
- MT5Account Documentation - Low-level RPC methods
- MT5Service Documentation - Mid-level service layer
- MT5Sugar (this document) - High-level convenience methods
π¦ 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
MT5Serviceclass (extension methods) - Parameter
timeoutSec- RPC operation timeout (default 10-20 sec) - Parameter
ct-CancellationTokenfor 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!