MT4 Expert Advisor Source Code: Orders and Debugging
MT4 Expert Advisor source code is editable MQL4 code, usually an .mq4 file plus required .mqh includes. MetaEditor compiles it into an .ex4 program. This guide focuses on MT4 order handling, error checks and debugging. MT5 uses a different trade API; see the separate MT5 source-code guide for that platform.
Start with the files you actually have
An EX4 is not the original editable source. A settings file contains input values, not a strategy implementation. Before changing a project, record its source revision, includes, external libraries and licence. The official MQL4 CodeBase and GitHub can provide code to inspect, but the hosting platform alone does not establish security or performance.
For an example of a project deliberately supporting MT4 and MT5, inspect EA31337’s pinned MQ4 entry file. At commit 9b9bd38c4e49dd6916f4fe3936e50e97fca7a692 it includes the common MQ5-named implementation. This is a project-specific compatibility design, not evidence that arbitrary MQ5 code runs in MT4. Our repository guide identifies the required dependency tree. We have not compiled or traded that project for this article.
Use the actual MQL4 event handlers
Modern MQL4 supports handlers including OnInit(), OnDeinit(const int reason), OnTick(), OnTimer() and OnChartEvent(...). Initialisation and deinitialisation can happen again after parameter or chart changes. The handler’s name, return type and parameters must match the documented signature.
OnTrade() is not a documented native MQL4 event handler. A function with that name in an MT4 project may be an ordinary function or part of a framework; find its caller rather than assuming the terminal generates that event. Check the official MQL4 event list.
Read the MT4 order lifecycle
| Operation | MQL4 API | Important check |
|---|---|---|
| Open a market or pending order | OrderSend(...) | Returns an order ticket, or -1 on failure. Record the error. |
| Select an order to inspect | OrderSelect(...) | Verify the symbol, magic number and order type before managing it. |
| Change order parameters | OrderModify(...) | Check the boolean result and error; stop-distance restrictions can apply. |
| Close a market order | OrderClose(...) | Check volume, requested price, slippage and the returned result. |
| Delete a pending order | OrderDelete(...) | A pending order is not closed through the same operation as a market order. |
The official OrderSend reference documents its ticket result and errors including invalid prices, requotes and invalid stops. A rejected request is not an open trade. Retrying without checking state can create duplicate exposure after an ambiguous response.
Debug the failure instead of hiding it
- Compile the unchanged source first and save errors and warnings.
- Log the symbol, order type, volume, relevant prices and returned ticket or boolean result around a failing operation.
- Capture
GetLastError()promptly after a failed call; do not overwrite the useful error with unrelated operations. - Check broker symbol names, digits, volume step, minimum/maximum volume and stop constraints.
- Review loops that manage orders: filter by symbol and strategy identifier so unrelated trades are not changed.
- Test behaviour after a terminal restart or connection loss and reconcile the current orders before sending more.
For example, error 130 concerns invalid stops. The documentation also notes that a zero MODE_STOPLEVEL can still coexist with server-side dynamic restrictions. Removing stops to make an error disappear changes the strategy and its risk; it is not a completed fix.
Risk calculations require more than one percentage
Document how position size is derived from stop distance, tick value and the account currency. Handle rounding to the permitted lot step and specify what happens when the computed volume is below the minimum. Do not round risk upward silently or treat a default lot input as a risk calculation.
For any prop-firm programme, separately verify its platform support, automation permission, loss formula and reset timezone. A generic “5% daily” example is not a universal rule. Include commissions, floating positions and other strategies where the programme’s formula requires them. A stop or close request cannot guarantee that a loss threshold will never be crossed.
Keep test claims limited to the evidence
Record the source and terminal version, input file, symbol, timeframe, historical interval, modelling method, spread and costs with every tester report. Use data not used for parameter fitting, then examine execution behaviour on an authorised demo account. A modelling percentage alone is not proof of realistic fills, statistical significance or future reliability.
This article reports no compilation, backtest or forward result. JPTC’s own broker-statement figures are not tests of third-party MT4 source. JPTC hosts its separate JPTC Algo; customers install nothing, run nothing and need no VPS. The EA Hub has a separate product scope and is not a compatibility certificate for code found online.
FAQ
Can I modify an MT4 EA when I only have EX4?
The EX4 is compiled. Obtain the authorised MQ4 source and dependencies to make source-level changes.
Does MT4 call OnTrade automatically?
OnTrade is not a documented native MQL4 event handler. If it exists in a project, inspect how that project calls it.
Why can OrderSend fail with invalid stops?
Stop distances and prices must satisfy the server’s rules. Even a zero MODE_STOPLEVEL does not always rule out dynamic restrictions. Inspect the actual error and instrument settings.
Does a successful backtest prove this EA will pass an evaluation?
No. Historical simulation is limited by its data and execution assumptions, and a programme has separate current account rules. No pass or payout is established.
The JPTradingCapital Team develops automated trading software. Our research methodology explains the limits of source reviews and software checks.
Continue with the right technical guide
- MT5 GitHub: pinned repository and dependencies
- Forex GitHub: choose the platform first
- MT5 source code: events, indicators and trade results
Automated forex and gold trading
Runs on your own account at your own broker. We host and set it up, so there is nothing to install and no VPS. No profit share, no monthly fee.
See how it works