Roze Quant Strategy Language Reference
Applies to: the Roze Quant desktop Strategy Editor, local runner, and local backtester
Source files:.mq5and.mqh
This document covers the language, events, and built-in APIs. For strategy design, risk, backtesting, and live practice, see the Strategy Development Guide.
1. What this language is
Strategies in this project are written in a source-compatible subset of MQL5. The syntax, common data types, event functions, and many standard functions follow MQL5, but the source is compiled and executed by the Roze Quant runtime. It does not require terminal64.exe, and it does not produce or run EX5 files.
This is not a complete MetaTrader 5 environment:
- only the language and API subset implemented and checked by the client can run;
.ex5binaries cannot run in the local runtime;.mq5/.mqhsource is required;- DLL imports, arbitrary external processes, direct HTTP, and socket access are blocked;
- quotes, accounts, positions, and orders come from the venue, API key, instrument, and portfolio bound in Roze Quant;
- backtests and live runs use the same source but have different market-event and fill models.
The result of Check/F7 in the target client version is authoritative. A feature appearing in the standard MQL5 documentation is not supported unless the Roze Quant checker accepts it.
2. Minimal runnable EA
#property version "1.00"
input double Lots = 1.0;
input int FastPeriod = 8;
input int SlowPeriod = 21;
CTrade trade;
int fastHandle = INVALID_HANDLE;
int slowHandle = INVALID_HANDLE;
int OnInit()
{
trade.SetExpertMagicNumber(20261124);
fastHandle = iMA(_Symbol, _Period, FastPeriod, 0, MODE_EMA, PRICE_CLOSE);
slowHandle = iMA(_Symbol, _Period, SlowPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
return INIT_FAILED;
return INIT_SUCCEEDED;
}
void OnTick()
{
double fast[2];
double slow[2];
if(CopyBuffer(fastHandle, 0, 0, 2, fast) != 2 ||
CopyBuffer(slowHandle, 0, 0, 2, slow) != 2)
return;
bool crossedUp = fast[1] <= slow[1] && fast[0] > slow[0];
if(crossedUp && !PositionSelect(_Symbol))
trade.Buy(Lots, _Symbol);
}
void OnDeinit(const int reason)
{
if(fastHandle != INVALID_HANDLE) IndicatorRelease(fastHandle);
if(slowHandle != INVALID_HANDLE) IndicatorRelease(slowHandle);
}
Workflow:
- Open Strategies → Strategy Editor and create or import an EA.
- Save all sources and run Check/F7. Fix every error.
- Select an instrument, period, date range, and inputs in the local backtester.
- Before live execution, select a venue, instrument, trading API key, and portfolio, then explicitly enable strategy trading calls.
- Validate signals, size, price, SL/TP, and logs in paper mode before using live mode.
3. Files, projects, and preprocessing
| Extension | Purpose |
|---|---|
.mq5 |
Main source for an EA, indicator, script, or library |
.mqh |
Reusable declarations, classes, functions, and constants |
.mqproj |
Optional native MetaEditor project manifest; not required by the local runtime |
.ex5 |
MetaTrader binary; not executable by the local runtime |
A local EA must define OnInit or OnTick. Implementing OnInit, OnTick, and OnDeinit is recommended.
#include "Risk.mqh"
#include <Trade/Trade.mqh>
Includes are expanded before checking and execution, and diagnostics are mapped back to the original file. Limits:
- include depth: 32;
- expanded project size: 4 MiB;
- cycles, missing files, and paths escaping the managed workspace are rejected.
Implemented directives include #define (object and function macros), #undef, #ifdef, #ifndef, #else, #endif, #include, #property, and managed #resource usage.
Built-in macros include __MQL5__, _RELEASE, __MQLBUILD__, __MQL5BUILD__, __CPU_ARCHITECTURE__, __DATE__, __DATETIME__, __FILE__, __LINE__, __FUNCTION__, __COUNTER__, and __RANDOM__.
#import of DLLs or external programs is not allowed. Do not use WebRequest or socket APIs to bypass the application data and audit boundary.
4. Lexical rules, types, and values
Both // line comments and /* ... */ block comments are supported. Identifiers are case-sensitive.
Language types include:
bool;char,short,int,long;uchar,ushort,uint,ulong;float,double;string,color,datetime,void;- user types declared with
enum,struct,class,interface,union, andtypedef.
int decimal = 42;
uint hex = 0x2A;
uint binary = 0b101010;
double ratio = 1.25;
bool enabled = true;
string label = "breakout";
char marker = 'A';
datetime started = D'2026.11.24 09:30:00';
color accent = C'30,144,255';
Integer literals accept common U/L suffixes. Do not rely on exact binary floating-point equality for prices; normalize against _Point and the instrument specification.
Static and dynamic arrays, multidimensional arrays, aggregate initialization, and structure member access are supported. CTrade arrays are not supported.
double closes[];
double window[20];
struct Signal
{
datetime time;
double price;
int direction;
};
Signal current = {0, 0.0, 0};
5. Declarations, inputs, and functions
Global and local variables, const, static, and extern declarations are implemented. State is retained for one strategy process and is never shared between strategy instances.
input group "Trading"
input double InpLots = 1.0;
input int InpMagic = 260001;
input bool InpEnableLong = true;
input string InpComment = "trend";
input and sinput values are read-only startup parameters that the client can override. Defaults must be compile-time expressions; calls such as TimeCurrent() are invalid as defaults.
Functions support overloads, default arguments, const, references, array parameters, function pointers, and the implemented template subset. Output arguments must be writable variables of the required type, not constants, inputs, or temporary expressions.
double Clamp(const double value, const double low, const double high)
{
return MathMax(low, MathMin(value, high));
}
void Load(double &output[], const int count = 100)
{
ArrayResize(output, count);
}
6. Expressions and control flow
Implemented operators include arithmetic, comparison, logical, bitwise, shifts, increment/decrement, compound assignment, casts, and the ternary operator. Implemented control flow includes if/else, switch, for, while, do/while, break, continue, and return. sizeof, offsetof, and typename are available in their implemented forms.
The runtime enforces instruction and call-depth limits. An infinite loop or uncontrolled recursion fails the current event. Keep OnTick short and avoid long Sleep calls.
7. Object-oriented subset
The parser and VM implement structures, classes, access control, single inheritance, virtual methods, overrides, constructors/destructors, static members, interfaces, the implemented class/function template subset, and new/delete pointer syntax.
class RiskModel
{
private:
double maximum;
public:
RiskModel(double value) : maximum(value) {}
double Limit() const { return maximum; }
};
Complex templates, pointer conversions, and inheritance edge cases must be verified with Check/F7. Prefer value types and small classes in strategy code.
8. Event model
8.1 EA events
| Event | Accepted signature | Purpose |
|---|---|---|
| Initialization | int OnInit() or void OnInit() |
Called once; a non-success result prevents startup |
| Quote | void OnTick() |
Called for a new quote on the bound instrument |
| Timer | void OnTimer() |
Requires EventSetTimer or EventSetMillisecondTimer |
| Chart | standard four-parameter OnChartEvent |
Local chart interaction |
| Trade change | void OnTrade() |
Called after order/fill/position state changes |
| Trade transaction | zero-parameter or standard three-parameter OnTradeTransaction |
Detailed transaction event |
| Roze receipt | void RozeOnTradeResult(string id, string status, double filled, double price) |
Project-specific execution receipt |
| Shutdown | void OnDeinit(const int reason) |
Stop, removal, or failure cleanup |
| Backtest score | double OnTester() |
Custom value returned at replay end |
The three parameters of OnTradeTransaction must be const references to MqlTradeTransaction, MqlTradeRequest, and MqlTradeResult.
Local EAs do not dispatch OnStart, OnBookEvent, OnTesterInit, OnTesterPass, OnTesterDeinit, or OnCalculate.
8.2 Custom indicator events
A custom indicator must implement the four- or ten-parameter MQL5 OnCalculate signature. It may also implement OnInit, OnTimer, OnChartEvent, and OnDeinit.
The streamed M1 snapshot does not supply tick_volume, real_volume, or spread in the ten-parameter form. Reading them is rejected. Indicator code cannot call trading APIs and does not receive OnTick, trade events, RozeOnTradeResult, or OnTester.
9. Market data and indicator APIs
Current context: _Symbol, _Period, _Point, and _Digits. Common queries include Symbol, Period, Digits, Point, SymbolInfoTick, the SymbolInfo* family, TimeCurrent, TimeTradeServer, TimeLocal, TimeGMT, PeriodSeconds, and time conversion functions.
Series functions include:
Bars,SeriesInfoInteger,iBarShift,iHighest,iLowest;iBars,iOpen,iHigh,iLow,iClose,iTime,iRealVolume;CopyOpen,CopyHigh,CopyLow,CopyClose,CopyTime,CopyRates,CopyRealVolume,CopySeries.
For live startup, the runner analyzes source and preloads required history: normally at least 256 bars and no more than 10,000 per interval. If a period or window cannot be resolved statically, the conservative limit is used. A strategy must wait when data is insufficient.
Use indicator handles with CopyBuffer, BarsCalculated, and IndicatorRelease. Accepted indicators include:
- trend:
iMA,iDEMA,iTEMA,iAMA,iFrAMA,iVIDyA,iADX,iADXWilder,iIchimoku,iSAR,iAlligator,iGator; - momentum:
iRSI,iMACD,iMomentum,iStochastic,iWPR,iCCI,iRVI,iOsMA,iDeMarker,iTriX; - volatility:
iATR,iBands,iStdDev,iEnvelopes; - volume/strength:
iOBV,iMFI,iVolumes,iForce,iAD,iAC,iAO,iBearsPower,iBullsPower,iBWMFI,iChaikin; - pattern:
iFractals; - project extensions:
RQDonchian,RQVWAP,RQROC,RQCMF; - custom indicators:
iCustom.
PlotIndexSet*, PlotIndexGetInteger, and IndicatorSet* are not local-EA APIs. Indicator drawing is validated separately inside the custom-indicator boundary.
10. Common standard functions
Implemented families include:
- arrays: size/range, resize/free, initialize/fill, sort/reverse, insert/remove/copy/compare/swap/search, min/max, and series orientation;
- mathematics: absolute value, roots/powers/logs, min/max/modulo, trigonometric and hyperbolic functions, rounding, finite-number checks, and
NormalizeDouble; - strings: length, append/concatenate, substring/search/compare/replace/split, case/trim, character-array conversions, and formatting;
- diagnostics:
Print,PrintFormat,Comment,Alert,GetLastError,ResetLastError,SetUserError; - files: open/read/write/seek/tell/size/flush/close, find/copy/move/delete, and managed folder operations;
- runtime:
IsStopped,Sleep,ExpertRemove,UninitializeReason, and timer counters; - chart objects: creation, implemented property access, coordinate conversion, and supported chart queries.
File APIs are sandboxed to the strategy asset/file roots. Absolute paths and .. traversal cannot access arbitrary local files.
11. Trading APIs and safety gate
Having a trading call in source does not authorize a live order. A live submission requires all of the following:
- live mode is selected;
- a valid venue, instrument, trading API key, and portfolio are selected;
- Allow strategy trading calls is enabled;
- the quote is fresh and the instrument specification is available;
- risk, account, and execution services accept the request.
When the switch is off, the strategy must not submit live orders. A rejection is reported through logs/receipts and must not cause an unlimited retry loop.
Supported CTrade groups:
- configuration:
SetExpertMagicNumber,SetAsyncMode,SetDeviationInPoints,SetTypeFilling,SetTypeFillingBySymbol; - execution:
Buy,Sell,PositionOpen,PositionClose; - implemented
Request*,Result*,Request(...), andResult(...)accessors.
OrderSend(request, result) and OrderCheck(request, result) are available through the structure interface. OrderSendAsync is explicitly unsupported.
Position queries include PositionsTotal, PositionSelect, PositionSelectByTicket, PositionGetSymbol, PositionGetTicket, and the PositionGet* family. In live mode they read the account selected by the API key. Only manage positions that can be attributed to the strategy by magic, comment, or runtime instance.
The upstream broker API may not preserve every MQL5 IOC or maximum-deviation semantic. The client validates what it can and reports constraints it cannot guarantee.
12. Backtest versus live execution
| Area | Local backtest | Local paper/live run |
|---|---|---|
| Market data | Downloaded, validated complete bars | Live quotes plus preloaded history |
| Tick model | Open → High → Low → Close for each bar | Actual received quote events |
| Time | Replay clock | Quote/execution service clock |
| Fills | Local spread/slippage model | Paper matcher or real execution service |
OnTester |
Supported | Not used as a live event |
| External state | Fixed replay input | Account, orders, fills, and positions change |
Offline replay requires complete, ordered, period-aligned bars with valid OHLC values. Futures may retain closed-session gaps; invalid gaps in other series are rejected. Backtest profit does not prove live performance. Handle latency, rejection, partial fills, disconnects, and recovery explicitly.
13. Diagnostics and debugging
Recommended sequence:
- save every
.mq5and.mqhfile; - run Check/F7 and fix lexical, syntax, type, event-signature, unknown-API, and unsupported-feature errors;
- use file/line/column diagnostics, including mapped
.mqherrors; - validate data boundaries and signals in local backtest;
- inspect
Print, execution receipts, and runner state in paper mode; - start live mode with minimum size and reconcile orders, fills, and positions.
| Diagnostic | Resolution |
|---|---|
unsupported MQL5 function |
Use a documented API or move the capability to an audited application service |
output requires a writable ... variable |
Pass a writable variable/array of the exact required type |
event ... requires ... parameters |
Correct the signature using section 8 |
a local strategy needs OnInit or OnTick |
Add an EA entry event |
unsupported directive |
Remove external imports; keep managed include/property/resource usage |
| Insufficient history | Wait/return and check the interval and indicator window |
| Trading call rejected | Check the gate, mode, API key, portfolio, specification, quote freshness, and risk log |
14. Production coding rules
- produce one traceable order intent per signal and prevent duplicate submission;
- identify ownership with magic/comment;
- normalize quantity, price, SL, and TP to the instrument specification;
- return on stale quotes, invalid handles, short
CopyBufferresults, or non-finite values; - never log API credentials or tokens;
- release handles and timers in
OnDeinit; - separate signal, risk, and execution logic into small functions;
- use closed bars when the rule requires confirmed signals and never use future data;
- rerun Check/F7 and critical backtests after every client upgrade.
15. Implementation sources and versioning
The implementation sources of truth are:
crates/quant-mql5: lexer, parser, preprocessor, VM, and indicator runtime;web/quant-user-web/src-tauri/src/mql5_local.rs: client validation, event, function, and trading boundaries;web/quant-user-web/src-tauri/src/bin/mql5-local-runner.rs: local execution behavior;web/quant-user-web/src-tauri/src/bin/mql5_backtest: offline replay behavior.
Any new language or API capability must update implementation, tests, and this guide together. Always re-check a strategy with the client version used for deployment; compiling in standard MetaEditor alone does not establish compatibility with this project.