MQL5 Programming Reference โ Your EA Development Cheat Sheet
Quick answer: MQL5 is the language used to build MT5 Expert Advisors. For most EAs, you will repeatedly use event handlers (OnInit/OnTick), indicator handles + CopyBuffer, and trade execution via OrderSend with MqlTradeRequest/MqlTradeResult.
If you only need the essentials right now:
- Indicator workflow: create handle -> check
BarsCalculated->CopyBuffer - Trade workflow: build
MqlTradeRequest->OrderSend-> inspectretcode - Core data:
_Symbol,_Point,_Digits,ENUM_TIMEFRAMES
When building Expert Advisors, you need a quick, accurate reference โ not a long tutorial. This page distills the official MQL5 documentation into a practical cheat sheet: data types, operators, indicators, OrderSend, and essential concepts. Bookmark it and jump to the section you need.
All examples follow MetaQuotes Language 5 syntax and are ready to adapt for your EAs.
Data Types โ What You Use Every Day
MQL5 uses C++-like types. Per MQL5 Data Types:
| Type | Use For | Example |
|---|---|---|
int | Whole numbers (counts, periods) | int period = 14; |
double | Prices, volumes, indicator values | double price = 1.0850; |
string | Symbol names, comments | string sym = _Symbol; |
bool | True/false flags | bool canTrade = true; |
datetime | Timestamps | datetime t = TimeCurrent(); |
long, ulong | Tickets, magic numbers | ulong ticket = 12345; |
Example โ Common variable declarations in an EA:
input int InpPeriod = 14; // RSI period
input double InpLotSize = 0.1; // Lot size
input int InpMagic = 12345; // Magic number
double askPrice;
double rsiBuffer[];
int maHandle = INVALID_HANDLE;
Operators and Loops โ Control Flow
From MQL5 Operators: if, for, while, switch, break, continue.
Example โ Iterate over positions and close by magic:
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket <= 0) continue;
if(PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
// ... close position logic
}
Arrays โ Dynamic and Series
Arrays hold OHLC, indicator buffers, and custom data. Use ArraySetAsSeries(array, true) so index 0 = current bar.
Example โ Copy MA values with CopyBuffer:
double maBuffer[];
ArraySetAsSeries(maBuffer, true);
int copied = CopyBuffer(maHandle, 0, 0, 3, maBuffer);
if(copied > 0)
double maNow = maBuffer[0]; // MA value on current bar
Technical Indicators โ Handle + CopyBuffer
Per MQL5 Technical Indicators: Create a handle in OnInit(), then use CopyBuffer() to read values.
iMA โ Moving Average
int iMA(string symbol, ENUM_TIMEFRAMES period, int ma_period, int ma_shift, ENUM_MA_METHOD method, ENUM_APPLIED_PRICE applied_price);
Example โ 20-period EMA on Close:
maHandle = iMA(_Symbol, PERIOD_CURRENT, 20, 0, MODE_EMA, PRICE_CLOSE);
if(maHandle == INVALID_HANDLE) return(INIT_FAILED);
// In OnTick: CopyBuffer(maHandle, 0, 0, 1, maBuffer);
iRSI โ Relative Strength Index
int iRSI(string symbol, ENUM_TIMEFRAMES period, int ma_period, ENUM_APPLIED_PRICE applied_price);
Example โ 14-period RSI:
rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, 14, PRICE_CLOSE);
// CopyBuffer(rsiHandle, 0, 0, 1, rsiBuffer); โ RSI at index 0
iATR, iMACD, iBands, iStochastic
Same pattern: handle = iATR(...), then CopyBuffer(handle, buffer_num, ...). Buffer index depends on the indicator (e.g. MACD has 3 buffers: main, signal, histogram).
CopyBuffer โ Get Indicator Data
From CopyBuffer:
int CopyBuffer(int indicator_handle, int buffer_num, int start_pos, int count, double buffer[]);
Returns the number of copied elements or -1 on error. Position 0 = current bar when using ArraySetAsSeries(buffer, true).
OrderSend โ Execute Trades
OrderSend() sends trade requests. You fill MqlTradeRequest and receive the result in MqlTradeResult.
Key MqlTradeRequest fields:
| Field | Purpose |
|---|---|
action | TRADE_ACTION_DEAL, TRADE_ACTION_PENDING, TRADE_ACTION_SLTP, etc. |
symbol | Trading symbol |
volume | Lot size |
price | Execution price (Ask for Buy, Bid for Sell) |
sl, tp | Stop Loss, Take Profit |
type | ORDER_TYPE_BUY, ORDER_TYPE_SELL |
deviation | Max slippage in points |
magic | EA identifier |
Example โ Open a Buy market order:
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = 0.1;
request.type = ORDER_TYPE_BUY;
request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
request.deviation = 10;
request.magic = 12345;
if(OrderSend(request, result))
Print("Order sent. Deal: ", result.deal);
else
Print("OrderSend failed: ", GetLastError());
Order vs Deal vs Position
From MQL5 Trade Functions:
- Order โ Instruction to the broker (market or pending)
- Deal โ Executed buy/sell
- Position โ Open obligation (contracts held)
Use PositionsTotal(), PositionGetTicket(i), PositionGetDouble(POSITION_VOLUME) etc. to work with open positions. Use OrdersTotal() and OrderGetTicket(i) for pending orders.
Timeframes โ ENUM_TIMEFRAMES
Per Chart Timeframes:
| Constant | Description |
|---|---|
| PERIOD_M1 | 1 minute |
| PERIOD_M5 | 5 minutes |
| PERIOD_M15 | 15 minutes |
| PERIOD_H1 | 1 hour |
| PERIOD_H4 | 4 hours |
| PERIOD_D1 | 1 day |
| PERIOD_W1 | 1 week |
| PERIOD_MN1 | 1 month |
| PERIOD_CURRENT | Chart timeframe |
Use PERIOD_CURRENT or 0 in indicator functions for the current chart.
Predefined Variables
| Variable | Meaning |
|---|---|
_Symbol | Current chart symbol |
_Point | Point size |
_Digits | Number of decimal places |
_Period | Current timeframe enum |
Quick Reference โ Functions You'll Use Often
| Function | Purpose |
|---|---|
SymbolInfoDouble(sym, SYMBOL_ASK) | Current Ask |
SymbolInfoDouble(sym, SYMBOL_BID) | Current Bid |
NormalizeDouble(price, digits) | Round price for order |
OrderCheck(request) | Validate before OrderSend |
BarsCalculated(handle) | Check if indicator is ready |
IndicatorRelease(handle) | Free indicator in OnDeinit |
Next Steps โ Build Your First EA
Use this reference while coding. In the next tutorial, Build Your First EA, you'll combine these elements into a Moving Average crossover EA with real entry/exit rules.
Bonus Tip: Prefer a visual shortcut? Try AlfaTactix Strategy Builder free โ the same no-code tool professional traders use to design strategies visually and export production-ready MQL5. Add indicators (iMA, iRSI, CopyBuffer logic), entry rules, and risk management with a visual interface โ then generate clean code you can refine in MetaEditor. Prototype in minutes, not hours.