On this page
Back to tutorials

MQL5 Reference for MT5: iMA, iRSI, CopyBuffer, OrderSend

Your go-to MQL5 cheat sheet: data types, operators, loops, arrays, technical indicators, OrderSend, risk management, multi-timeframe logic, and market filters. Based on official docs.

๐Ÿ“– 28 min read

๐Ÿ“ 5,500 words

๐Ÿท๏ธ MQL5 & Expert Advisors

Share this article:

Want to build a no-code strategy right now?

Create your free account in seconds and start building immediately.


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 -> inspect retcode
  • 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:

TypeUse ForExample
intWhole numbers (counts, periods)int period = 14;
doublePrices, volumes, indicator valuesdouble price = 1.0850;
stringSymbol names, commentsstring sym = _Symbol;
boolTrue/false flagsbool canTrade = true;
datetimeTimestampsdatetime t = TimeCurrent();
long, ulongTickets, magic numbersulong 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:

FieldPurpose
actionTRADE_ACTION_DEAL, TRADE_ACTION_PENDING, TRADE_ACTION_SLTP, etc.
symbolTrading symbol
volumeLot size
priceExecution price (Ask for Buy, Bid for Sell)
sl, tpStop Loss, Take Profit
typeORDER_TYPE_BUY, ORDER_TYPE_SELL
deviationMax slippage in points
magicEA 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:

ConstantDescription
PERIOD_M11 minute
PERIOD_M55 minutes
PERIOD_M1515 minutes
PERIOD_H11 hour
PERIOD_H44 hours
PERIOD_D11 day
PERIOD_W11 week
PERIOD_MN11 month
PERIOD_CURRENTChart timeframe

Use PERIOD_CURRENT or 0 in indicator functions for the current chart.


Predefined Variables

VariableMeaning
_SymbolCurrent chart symbol
_PointPoint size
_DigitsNumber of decimal places
_PeriodCurrent timeframe enum

Quick Reference โ€” Functions You'll Use Often

FunctionPurpose
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.

Build your no-code trading strategy now โ€” free

Create your account and start building a complete no-code strategy right now. Add indicators, filters, and risk rules, then export MQL5 in minutes.

Frequently Asked Questions

MQL5 (MetaQuotes Language 5) is an object-oriented high-level programming language for writing Expert Advisors, custom indicators, and scripts for MetaTrader 5. It is based on C++ syntax. The official reference is at mql5.com/en/docs.

An order is an instruction to the broker (market or pending). A deal is the execution of a buy/sell. A position is the resulting obligation โ€” the number of contracts held. One order can result in multiple deals; a position is created when a deal opens it.

Create an indicator handle with iMA(), iRSI(), etc. in OnInit(). Use CopyBuffer(handle, buffer_num, start_pos, count, array[]) to copy values into your array. Check BarsCalculated(handle) before copying.

MqlTradeRequest holds the trade parameters (action, symbol, volume, price, sl, tp, etc.). MqlTradeResult receives the server response (retcode, deal, order). Pass both to OrderSend(request, result).

PERIOD_M1, M5, M15, M30, H1, H4, D1, W1, MN1. Use PERIOD_CURRENT for the chart timeframe. Pass 0 or PERIOD_CURRENT to indicator functions for the current symbol/timeframe.

The official MQL5 Reference is at mql5.com/en/docs. In MetaEditor, use Help โ€” MQL5 Reference for offline access. It covers all functions, constants, and data types.

Build your no-code strategy now โ€” free

Create Free Account