Overview
MetaTrader development at scale — managing multiple Expert Advisors, maintaining a library of custom indicators, supporting a team of developers working on the same codebase — requires more than individual MQL4 and MQL5 files. It requires shared libraries of reusable components that implement the trading functions, utility operations, and platform interactions that every piece of MetaTrader software needs, implemented once to a production standard and used consistently across every EA, indicator, and script that depends on them.
Reusable MQL code is usually shared as include files (.mqh) that are compiled into each program. Compiled libraries — the .ex4 and .ex5 files that MetaTrader loads at runtime — are useful when the source must stay hidden, but they can only export functions, not classes. An order management library that every EA uses rather than each EA implementing its own order placement code. A risk management library that provides the position sizing calculations, the drawdown monitoring, and the portfolio exposure aggregation that every strategy requires. A utility library that provides string formatting, date arithmetic, file I/O, and the other utility functions that appear repeatedly across MetaTrader programs.
Libraries eliminate the code duplication that occurs when each MetaTrader program reimplements the same operations independently — the maintenance overhead of updating the same logic in multiple places when broker behaviour changes, the quality inconsistency when different implementations handle the same operation differently, and the testing burden of validating the same functionality repeatedly across different programs.
We build custom MetaTrader libraries for trading firms and developers who need production-quality reusable MQL4 and MQL5 components — order management libraries, risk management libraries, indicator utility libraries, data access libraries, integration libraries, and the modular architecture components that professional MetaTrader development requires.
What MetaTrader Library Development Covers
Order management libraries. The most commonly reimplemented and most frequently broken component in MetaTrader development — the code that places, modifies, and closes orders reliably across the range of broker behaviours and market conditions that live trading produces.
A production-quality order management library abstracts the MT4 or MT5 order execution API behind a clean interface that EA and script code uses without needing to implement the error handling, the retry logic, the requote management, or the broker-specific adaptations that reliable order placement requires. The library handles it.
MT4 order management library components: order placement with automatic retry on transient errors (ERR_REQUOTE, ERR_PRICE_CHANGED, ERR_OFF_QUOTES), error classification that distinguishes retryable errors from permanent rejections, price refresh logic that fetches a new Ask or Bid price before retry, stop loss and take profit validation against the broker's minimum stop distance, and the return value handling that confirms success and provides actionable failure information to the calling code.
MT5 order management library components: MqlTradeRequest structure construction for each order type (market orders, pending orders, stop loss modification, position closure), OrderSend() result code interpretation, deal and order history access, and the CTrade wrapper extensions that add the retry logic and validation that the standard CTrade class does not provide.
Position query functions: getting the current position for a specific magic number and symbol, getting all positions matching a criteria, calculating the net position in lots, getting the aggregate open P&L across positions matching a filter. Functions that the rest of the EA code uses without needing to iterate OrdersTotal() and OrderSelect() directly.
Risk management libraries. The position sizing calculations, drawdown monitoring, and exposure management functions that every trading EA requires — implemented once with the precision and edge case handling that risk calculations demand.
Position size calculation: the function that takes account equity, risk percentage, entry price, stop loss price, and symbol specifications (tick value, tick size, minimum lot, lot step) and returns the correctly sized position in lots that achieves the target risk percentage. The calculation that handles the currency conversions when the account currency differs from the quote currency, the lot step rounding that produces a valid lot size within the broker's constraints, and the maximum lot size capping that respects the broker's and account's position size limits.
Drawdown calculation: daily drawdown from the session's opening equity, total drawdown from the account's peak equity, and the peak equity tracking that the drawdown calculation depends on. The drawdown functions that prop firm compliance EAs use to enforce the firm's specific drawdown rules.
Portfolio exposure calculation: aggregate open lots by symbol, aggregate open lots by direction across symbols, correlation-adjusted exposure estimation, margin utilisation calculation. The exposure query functions that portfolio-level risk management uses to assess the current risk profile before adding new positions.
Risk limit enforcement: the functions that return whether a new trade is within the configured risk limits — checking whether opening the specified position would exceed the maximum concurrent positions, the maximum aggregate lots, or the maximum drawdown before the position is opened.
Technical indicator utility libraries. Common indicator calculations implemented as library functions that EAs and custom indicators call rather than reimplementing — moving average calculations, ATR calculation, pivot point calculation, support and resistance identification, and the statistical functions that technical analysis uses.
Indicator value access utilities: functions that read indicator values from the standard library indicators or from custom indicators, handling the iCustom() call construction and buffer index management that indicator value access requires. The wrapper functions that make indicator value access cleaner in EA code than repeated iCustom() calls with magic number buffer indices.
Multi-timeframe utilities: functions that fetch indicator values from non-chart timeframes, handling the timeframe synchronisation and the MT4/MT5 differences in how multi-timeframe data access works.
Data access and storage libraries. The file I/O, database access, and data formatting functions that MetaTrader programs use to persist data, log trades, exchange data with external systems, and format output for display or transmission.
CSV file reading and writing: parsing incoming signal files, writing trade logs, exporting historical data — implemented with the correct file path handling for the MetaTrader sandbox, the correct file opening modes, and the error handling for file access failures.
Trade journal library: the functions that log every trade event — entry, modification, exit, rejection — to a persistent file or database with the timestamp, the market context, and the trade parameters that post-trade analysis requires. A consistent trade journal format used by every EA in the operation rather than each EA implementing its own logging approach.
Data serialisation: JSON and CSV serialisation of trade data and EA state for transmission to external systems via file bridge. The serialisation functions that format MetaTrader data structures for consumption by Python or C# processes running alongside the MetaTrader platform.
Communication and integration libraries. The components that connect MetaTrader to external systems — signal sources, monitoring platforms, portfolio management systems, and the external infrastructure that professional trading operations use alongside MetaTrader.
File bridge library: the standardised file format and access pattern for data exchange between MetaTrader and external processes. Signal files written by an external process in a defined format read by the signal reader library functions. Trade event files written by the EA trade journal library read by an external process that imports them into a database or monitoring system.
DLL bridge interface: the MQL function declarations that expose external DLL functions to MQL code, and the calling conventions that ensure MQL4/MQL5 and C++ data types are passed correctly across the DLL boundary. The interface layer that makes DLL-based external connectivity accessible to EA and indicator code without requiring each program to define its own DLL interface.
Named pipe and socket utilities for MT4/MT5 programs that communicate in real time with external processes on the same machine or network — implemented with the connection management and reconnection logic that production inter-process communication requires.
MetaTrader 5 specific libraries. Some components build on MQL5-only features such as its trade classes, Generic collections and event model.
Strategy base class library: a base class that defines the interface for strategy signal generation — the OnSignal() method that returns entry/exit signals, the OnManage() method that applies position management logic to open positions — allowing multiple strategy implementations to share a common EA framework that handles order execution and risk management through the base class interface.
Event handling library: the MQL5 event infrastructure that allows library components to raise events that consuming code subscribes to — the trade event that fires when a position is opened or closed, the signal event that fires when entry conditions are met, the risk event that fires when a risk threshold is approached.
Collection utilities: building on the templated collections in MQL5's Generic library, such as CArrayList and CHashMap, for typed lists and maps — a list of position objects, a map from symbol to strategy state.
Library Architecture Principles
Single responsibility. Each library module has a defined scope — the order management library manages orders, the risk library calculates risk metrics, the data library handles persistence. Libraries that combine unrelated functionality become difficult to maintain and create unnecessary dependencies between the EA code that uses them. Single-responsibility libraries can be updated and tested independently.
Defensive implementation. Library functions called by EA code cannot assume that their inputs are valid. Defensive implementation validates all inputs, handles null pointers, checks array bounds, and returns well-defined values for error conditions rather than crashing or silently producing incorrect results. EA code that calls a library function and gets a well-defined error return can decide how to respond. EA code that calls a library function that crashes on invalid input has a problem that is difficult to diagnose.
MT4/MT5 compatibility. Where the same functionality is needed on both platforms, the library provides a consistent interface with platform-specific implementations — compiler directives that select the MT4 or MT5 implementation of the same function based on which platform is compiling the code. EA code written against the library interface compiles for both MT4 and MT5 without changes to the EA code.
Performance awareness. Library functions called on every tick must be efficient — O(1) or O(n) with small n, without unnecessary memory allocation, without redundant broker API calls that add latency. The risk calculation that runs on every tick to check whether a new trade is within limits must be fast enough that it does not degrade platform responsiveness. Library design that caches broker information (account equity, symbol specifications) where appropriate and refreshes only when needed reduces the per-tick overhead of library function calls.
Version management. Shared code needs versioning. Include files are compiled into each EA, so an update means recompiling and redeploying the EAs that use it; compiled .ex4/.ex5 libraries are loaded at runtime, so an update reaches every EA, which is convenient but requires a stable interface. Either way, version control tracks which EA runs which version.
Testing and Quality Assurance
MetaTrader libraries deployed in production trading must be correct — the risk calculation that returns the wrong lot size, the order management function that silently fails to place an order, or the drawdown calculation that underestimates the current drawdown are all failures with direct financial consequences.
Unit testing approach for MQL4/MQL5. MQL does not have a standard unit testing framework, but the testing pattern of calling each library function with known inputs and asserting the expected output can be implemented as a test EA that runs in the Strategy Tester and logs pass/fail results. Library functions that are critical to correct trading operation — position size calculation, drawdown calculation, order placement — are tested with the range of inputs that production use will produce, including the edge cases (zero stop distance, maximum lot size, account in a different currency from the instrument) that reveal incorrect implementation.
Integration testing. Library components tested as a unit may interact incorrectly when used together. Integration testing that runs representative EA scenarios — opening positions, modifying stops, hitting drawdown limits, recovery after reconnection — validates that the library components work correctly together in the combinations that production use requires.
Broker compatibility testing. Order management library functions tested against multiple broker configurations — instant execution and market execution brokers, brokers with different minimum stop distances, brokers with different lot step constraints — to confirm that the library handles the range of broker behaviours it will encounter.
Technologies Used
- MQL4 — MT4 library implementation (.ex4 compiled library files)
- MQL5 — MT5 library implementation (.ex5 compiled library files) with full object-oriented architecture
- MQL5 Standard Library and Generic collections — CTrade, CObject, CArrayList, CHashMap and other standard components as foundations for custom library extensions
- C++ / C# — DLL library development for MQL integration via DLL bridge
- Python — external test harness and library integration testing tools
- MetaTrader Strategy Tester — library function testing in controlled historical simulation environment
- Version control — library versioning and dependency management across multiple dependent EAs and indicators
The Case for Shared Libraries Over Duplicated Code
Every trading firm and every serious MetaTrader developer who maintains multiple Expert Advisors eventually reaches the point where the same code exists in multiple files — the same order placement logic copied between five EAs, each copy accumulating its own bug fixes and improvements while the others remain on older versions. When a broker changes their execution model and the order placement logic needs to update, updating five copies creates five opportunities for the update to be applied inconsistently.
Shared libraries solve this problem at the cost of upfront investment in building them correctly. The order placement logic exists once, maintained in one place, used by every EA that needs it. When it needs to change, it changes once. The quality and correctness of the library code benefits every program that uses it rather than being bounded by the quality of each individual EA's implementation.
For trading operations running multiple strategies across multiple accounts, the investment in well-built shared libraries is the infrastructure that makes the codebase maintainable at scale.
Frequently Asked Questions
Library or include file?
Most reusable MQL code is shared as include files (.mqh) that are compiled into each program. A compiled .ex4/.ex5 library is useful when the source must stay hidden, but it can only export functions, not classes.
How is library code tested?
With test EAs in the Strategy Tester that call each function with known inputs, including edge cases such as an account in a different currency, and with integration tests on demo accounts at different brokers.
Can one library serve both MT4 and MT5?
Yes. With conditional compilation the interface stays the same and only the platform-specific parts differ, so EA code does not need to change.
Who owns the library code?
You do, with code ownership arranged by contract.
Who owns the code?
Ownership of the source code is set out in the contract, and the code can be fully yours, including documentation and tests.
See also MT4 to MT5 migration, MQL5 development and MetaTrader integration.
Build Once, Use Everywhere
Order handling, risk calculation, logging and integrations written once to production standard and shared by every expert advisor, indicator and script, so a fix or broker change is made in one place.