OrderCheck HOW
Example from file: examples/demos/lowlevel/02_trading_operations.goΒΆ
The
OrderCheck()method performs a safe preliminary validation of an order before sending it. It allows you to verify that the order parameters are correct and that the account has sufficient funds to open it.
π§© Code exampleΒΆ
fmt.Println("\n3.1. OrderCheck() - Validate order parameters")
// The filling mode must be one the symbol allows (SYMBOL_FILLING_MODE flags: 1 = FOK, 2 = IOC);
// with a mode the symbol does not allow, the check fails.
typeFilling := pb.MRPC_ENUM_ORDER_TYPE_FILLING_ORDER_FILLING_RETURN
fillingData, err := account.SymbolInfoInteger(ctx, &pb.SymbolInfoIntegerRequest{
Symbol: cfg.TestSymbol,
Type: pb.SymbolInfoIntegerProperty_SYMBOL_FILLING_MODE,
})
if err == nil {
if fillingData.Value&1 != 0 {
typeFilling = pb.MRPC_ENUM_ORDER_TYPE_FILLING_ORDER_FILLING_FOK
} else if fillingData.Value&2 != 0 {
typeFilling = pb.MRPC_ENUM_ORDER_TYPE_FILLING_ORDER_FILLING_IOC
}
}
orderCheckReq := &pb.OrderCheckRequest{
MqlTradeRequest: &pb.MrpcMqlTradeRequest{
Action: pb.MRPC_ENUM_TRADE_REQUEST_ACTIONS_TRADE_ACTION_DEAL,
Symbol: cfg.TestSymbol,
Volume: cfg.TestVolume,
OrderType: pb.ENUM_ORDER_TYPE_TF_ORDER_TYPE_TF_BUY,
Price: tickData.Ask,
StopLoss: 0.0,
TakeProfit: 0.0,
Deviation: 10,
TypeFilling: typeFilling, // a filling mode the symbol allows
TypeTime: pb.MRPC_ENUM_ORDER_TYPE_TIME_ORDER_TIME_GTC,
Comment: "OrderCheck validation",
},
}
checkData, err := account.OrderCheck(ctx, orderCheckReq)
if err != nil {
fmt.Println(" β OrderCheck FAILED")
fmt.Printf(" Error: %v\n", err)
} else if checkData != nil && checkData.MqlTradeCheckResult != nil {
result := checkData.MqlTradeCheckResult
fmt.Println(" β
OrderCheck SUCCESS!")
fmt.Printf(" Return Code: %d\n", result.ReturnedCode)
fmt.Printf(" Comment: %s\n", result.Comment)
fmt.Printf(" Required Margin: %.2f\n", result.Margin)
fmt.Printf(" Balance After: %.2f\n", result.BalanceAfterDeal)
fmt.Printf(" Equity After: %.2f\n", result.EquityAfterDeal)
fmt.Printf(" Free Margin After: %.2f\n", result.FreeMargin)
fmt.Printf(" Margin Level: %.2f%%\n\n", result.MarginLevel)
// OrderCheck returns 0 on successful validation (unlike OrderSend which returns 10009)
if result.ReturnedCode == 0 {
fmt.Println(" β Order validation PASSED β safe to proceed with OrderSend()")
} else {
// Use helper from errors.go to get human-readable error description
fmt.Printf(" β οΈ Validation failed: %s (code: %d)\n",
mt5.GetRetCodeMessage(uint32(result.ReturnedCode)),
result.ReturnedCode)
}
}
π’ Detailed Code ExplanationΒΆ
1οΈ. Form the Request StructureΒΆ
A request object is created, containing the MqlTradeRequest structure β a complete description of the order, as if it were actually being sent to MetaTrader.
Key fields:
Actionβ trade action type (TRADE_ACTION_DEALβ execute immediately);Symbolβ instrument (cfg.TestSymbolfromconfig.json);Volumeβ order volume;OrderTypeβ direction (BUYorSELL);Priceβ opening price;Deviationβ allowable price deviation in points;TypeFillingβ execution mode. It must be one the symbol allows: the demo readsSYMBOL_FILLING_MODE(flags 1 =FOKFill-Or-Kill, 2 =IOCImmediate-Or-Cancel) and picks an allowed one. A mode the symbol does not allow makes the check fail (e.g.IOCon a FOK-only symbol:ERR_TRADE_SEND_FAILED);TypeTimeβ order lifetime (GTCβ Good Till Cancelled).
2οΈ. Send Validation RequestΒΆ
The gateway passes the request to MetaTrader, which validates the order for correctness and returns the result β without actually opening a position.
3οΈ. Process the ResultΒΆ
If there is an error (err != nil), the check did not pass (MetaTrader's OrderCheck failed, e.g. not enough money or invalid stops) or the call itself failed; the error (*mt5.ApiError) carries the trade return code and its description.
If a result is received, the validation fields are displayed:
result := checkData.MqlTradeCheckResult
fmt.Printf(" Required Margin: %.2f\n", result.Margin)
fmt.Printf(" Free Margin After: %.2f\n", result.FreeMargin)
fmt.Printf(" Margin Level: %.2f%%\n", result.MarginLevel)
- Margin β how much margin will be required for the trade;
- FreeMargin β how much free margin will remain after opening;
- MarginLevel β margin level as a percentage.
4οΈ. Interpret the ResultΒΆ
// OrderCheck returns 0 on successful validation (unlike OrderSend which returns 10009)
if result.ReturnedCode == 0 {
fmt.Println(" β Order validation PASSED β safe to proceed with OrderSend()")
} else {
// Use helper from errors.go to get human-readable error description
fmt.Printf(" β οΈ Validation failed: %s (code: %d)\n",
mt5.GetRetCodeMessage(uint32(result.ReturnedCode)),
result.ReturnedCode)
}
Important: OrderCheck uses different success code than trading operations
- OrderCheck success:
ReturnedCode == 0means validation passed - Trading operations success:
ReturnedCode == 10009(checked withmt5.IsRetCodeSuccess())
Why use mt5.GetRetCodeMessage() for errors?
- Automatic Error Descriptions: Instead of just showing a number, get human-readable messages for common validation errors:
TRADE_RETCODE_INVALID_VOLUME- Volume doesn't meet broker requirementsTRADE_RETCODE_NO_MONEY- Insufficient funds for the tradeTRADE_RETCODE_INVALID_STOPS- SL/TP levels violate broker rulesTRADE_RETCODE_INVALID_PRICE- Price out of valid range- Consistency: Same error handling pattern used across all trading operations
- Centralized: All 40+ error codes defined in
package/Helpers/errors.go
If ReturnedCode == 0 β the order passed validation and it's safe to proceed with OrderSend().
Any other value indicates a validation error that should be fixed before attempting to send the order.
π¦ What the Server ReturnsΒΆ
message OrderCheckData {
MrpcMqlTradeCheckResult MqlTradeCheckResult = 1;
}
message MrpcMqlTradeCheckResult {
uint32 ReturnedCode = 1;
double BalanceAfterDeal = 2;
double EquityAfterDeal = 3;
double Profit = 4;
double Margin = 5;
double FreeMargin = 6;
double MarginLevel = 7;
string Comment = 8;
}
π‘ Example OutputΒΆ
β
OrderCheck SUCCESS!
Return Code: 0
Comment: Done
Required Margin: 120.50
Balance After: 9879.50
Equity After: 9879.50
Free Margin After: 9759.00
Margin Level: 1120.75%
β Order validation PASSED β safe to proceed with OrderSend()
π§ What It's Used ForΒΆ
The OrderCheck() method is used for:
- validating order correctness before sending;
- assessing future account state after the trade;
- protection from errors and broker rejections;
- safe testing of strategies and robots.
π¬ In Simple TermsΒΆ
OrderCheck()is a "rehearsal" before a trade. It checks whether an order with the specified parameters can be opened, and how balance, margin, and equity will change after the trade. If everything is correct (code0) β you can safely proceed withOrderSend().