MQL5 examples: working code for MetaTrader 5
Answers to the questions MetaTrader 5 developers search for most, from opening an order to drawing on the chart. Each page has a short answer, a complete Expert Advisor or script that compiles in MetaEditor, and the pitfalls that make the obvious version fail.
19 examples
Orders and positions
Open, close, protect and size trades with CTrade, within the broker's price, volume and distance rules.
Market buy or sell with CTrade
CTrade::Buy · CTrade::Sell · CTrade::ResultRetcode
Close all positions
PositionsTotal · PositionGetTicket · CTrade::PositionClose
Pending orders with expiry
CTrade::BuyLimit · CTrade::BuyStop · CTrade::SellLimit
Move stop to break-even
CTrade::PositionModify · PositionGetDouble · HistorySelectByPosition
Partial close
CTrade::PositionClosePartial · ACCOUNT_MARGIN_MODE · HistorySelectByPosition
Normalize price and lot size
SYMBOL_TRADE_TICK_SIZE · SYMBOL_VOLUME_STEP · SYMBOL_VOLUME_MIN
Signals, timing and rules
When the EA acts: new bars, indicator values, sessions, timers and limits on how often it trades.
Detect a new bar
iTime · OnTick · iClose
Read iMA and iRSI values
iMA · iRSI · CopyBuffer
Read a custom indicator (iCustom)
iCustom · CopyBuffer · BarsCalculated
Moving average crossover EA
iMA · CopyBuffer · CTrade::Buy
Session and time filter
TimeCurrent · TimeTradeServer · TimeGMT
Limit trades per day
HistorySelect · HistoryDealGetTicket · DEAL_ENTRY
OnTimer
EventSetTimer · OnTimer · EventKillTimer
Chart, files, messages and testing
What the EA shows and sends: objects and panels on the chart, CSV files, alerts, webhooks and the Strategy Tester.
Draw lines, arrows and text
ObjectCreate · ObjectSetInteger · ObjectSetString
On-chart dashboard
OBJ_LABEL · OBJ_RECTANGLE_LABEL · ObjectSetString
Write trades to CSV
OnTradeTransaction · HistoryDealSelect · HistorySelectByPosition
Alerts and push notifications
Alert · PlaySound · SendNotification
WebRequest webhook (POST JSON)
WebRequest · StringToCharArray · CharArrayToString
Custom optimization criterion (OnTester)
OnTester · TesterStatistics · STAT_RECOVERY_FACTOR
How to run an example
Each page says whether its program is an Expert Advisor, which stays on its chart and reacts to every tick until you remove it, or a script, which runs once when you drop it on a chart.
- In MetaTrader 5, open File > Open Data Folder, then
MQL5/Expertsfor an Expert Advisor orMQL5/Scriptsfor a script, and save the downloaded.mq5file there. - Open it in MetaEditor and press F7 (Compile). The Errors tab should end with “0 errors, 0 warnings”.
- Back in the terminal, drag the program from the Navigator onto a chart. Programs that trade need the Algo Trading button on and “Allow Algo Trading” ticked in their settings.
- Start on a demo account. For an Expert Advisor, run it in the Strategy Tester first.
The full walk-through, with the usual problems and their fixes, is in how to install an Expert Advisor on MT5.
What every example does the same way
The programs are short, but they follow the rules that keep code working on real brokers, so you can lift a function into your own EA:
- Orders go through the standard library's
CTrade, and every result is checked withResultRetcode(): atruereturn only means the request was sent. - Prices are rounded to the symbol's tick size and volumes to its volume step, never to a fixed number of decimals.
- Stops are measured from the price a position closes at: the Bid for a buy, the Ask for a sell.
- Only positions with the program's symbol and magic number are touched, so manual trades and other EAs are left alone.
- Indicator handles are created once in
OnInit(), and signals are read on closed bars. - Anything that must survive a restart, such as the trades taken today or a partial close already done, is read from the server's deal history rather than kept in a variable.
Every program on these pages was compiled in MetaEditor 5 (build 6275) on November 12, 2026, with 0 errors and 0 warnings. A clean build shows that the code compiles, not that a strategy makes money: programs that send orders are marked, and belong on a demo account until you've tested them.
Need a whole Expert Advisor, not a snippet?
Describe your strategy in plain English and Edgoro's MT5 EA generator writes the complete MQL5 Expert Advisor, with the order handling, rounding and checks shown here, and compiles it in MetaEditor before you get it. Test it on a demo account: a clean build isn't proof that a strategy works.