Loading…

Pair Trading EA

The hedge ratio is a rolling average of close(A)/close(B) over InpHedgeLookback bars, not a regression beta - simpler, and good enough for symbols that already track closely, such as major pairs or correlated indices. It is recomputed every bar so the two legs stay sized for a dollar-neutral spread as prices drift apart. The spread itself, close(A) minus the ratio times close(B), is converted to a z-score against its own InpZLookback-bar mean and standard deviation. A trade opens once the z-score clears InpEntryZ in either direction and closes once it reverts inside InpExitZ, or, if the spread keeps diverging instead of reverting, once it reaches InpStopZ - the stop is a spread event, not a price stop on either leg individually, because a price-based stop on one leg alone would ignore what the other leg is doing. Leg B's lot size is not just leg A's lots times the ratio: it is rescaled again by each symbol's money-per-point, built from MODE_TICKVALUE and MODE_TICKSIZE on both symbols. Skipping that step would size the pair correctly only when both legs happen to share a contract size and quote currency, which is not guaranteed even for two forex majors. If one leg opens and the other's OrderSend then fails, the EA closes the leg that did open rather than leaving a single, unhedged directional bet running under a pairs-trading label. Notes and limitations - The hedge ratio is a simple rolling price ratio, not a cointegration or regression estimate. It works for pairs that already move together; it will not discover a hedge relationship that is not visibly there. - No correlation check gates entry - if InpSymbolB is a poor match for the chart symbol, the z-score is still computed and traded on. Choose the pair deliberately. - One position per leg at a time, tracked by InpMagicNumber. It manages only its own trades, never trades opened manually or by another EA. - Signals are evaluated once per closed bar on the chart symbol's timeframe, not on every tick. - Requires AutoTrading enabled (checked via ACCOUNT_TRADE_ALLOWED / ACCOUNT_TRADE_EXPERT / TERMINAL_TRADE_ALLOWED on MQL5, IsTradeAllowed() on MQL4); if trading is disabled the EA logs it and skips new entries, but still manages and can close an existing pair.

Expert advisor · MT4 · v1.0 · Free

About Pair Trading EA

Pair Trading EA is an expert advisor (trading robot) for MetaTrader 4 based on ATR. It can hold buy and sell positions at the same time (hedging) and can size trades from your balance and risk percent. It has 14 settings, such as Symbol b, Hedge lookback and Z lookback. MQL source code included.

Files in the download: PairTradingEa.ex4, PairTradingEa.mq4, PairTradingEa.txt.

Trading robots can lose money. Check every setting and test on a demo account before using real funds.

Settings

SettingDefaultWhat it does
Symbol bGBPUSDSecond leg symbol (chart symbol is the first leg)
Hedge lookback20Bars used to average the A/B price ratio
Z lookback60Bars used to compute the spread mean and std dev
Entry z2.0Spread z-score that opens a trade
Exit z0.5Spread z-score that closes a trade (reversion target)
Stop z4.0Spread z-score that closes a trade as a stop (kept diverging)
Atr period14ATR period, used only to size leg A by risk
Use risk sizingfalseSize leg A by percent risk instead of a fixed lot
Risk percent1.0Percent of equity risked per trade, when risk sizing is on
Fixed lots a0.10Leg A lot size when risk sizing is off, or as a fallback
Magic number20260705Magic number for both legs of this pair
Slippage pips3Slippage tolerance, in pips
Max retries5Attempts per trade action before giving up
Retry wait ms500Pause between attempts, milliseconds

How to install

  1. Download the ZIP from your PolyMaria library and unzip it.
  2. In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Experts.
  3. Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
  4. Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
  5. Drag the expert advisor from the Navigator onto a chart, check the settings, allow Algo/Auto Trading and press OK.
  6. Test it first on a demo account or in the Strategy Tester.

Download the PDF guide

Tags: Hedging · Risk & Lot Size · ATR · MT4 Expert Advisor · MQL4 Source Code

Expert advisors (EA) for MT4 & MT5 · PolyMaria