# EURUSD and GBPUSD Mean Reversion

> EURUSD and GBPUSD Mean Reversion is a strategy that trades EURUSD and GBPUSD on 1-hour bars. It holds at most 2 open trades.

Source: https://algobarsx.com/docs/ex-05-pairs-mean-reversion/

```algobarsx
strategy "EURUSD and GBPUSD Mean Reversion"
    markets: EURUSD, GBPUSD
    bars: 1h
    max_open: 2

input lookback = 200
input entry_z = 2.0
input exit_z = 0.5

eur = bars(EURUSD)
gbp = bars(GBPUSD)
hedge = beta(returns(eur.close), returns(gbp.close), lookback)
z = zscore(log(eur.close / gbp.close), lookback)

when z > entry_z and trades.open(tag: "pair").len == 0:
    eur_size = size_for(EURUSD, risk: 0.5%, stop: atr(14, on: eur) * 3)
    sell market: EURUSD, size: eur_size, tag: "pair"
    buy market: GBPUSD, size: eur_size * hedge, tag: "pair"

when abs(z) < exit_z:
    close_all tag: "pair"
```
What this script says

EURUSD and GBPUSD Mean Reversion is a strategy that trades EURUSD and GBPUSD on 1-hour bars. It holds at most 2 open trades.

You can change 3 inputs: `lookback` (default 200), `entry_z` (default 2.0) and `exit_z` (default 0.5).

It calculates `eur` as EURUSD bars, `gbp` as GBPUSD bars, `hedge` as the beta of the returns of `eur.close` against the returns of `gbp.close` over `lookback` bars and `z` as the z-score of the logarithm of `eur.close` divided by `gbp.close` over `lookback` bars.

When `z` is above `entry_z` and the number of open trades tagged "pair" is 0, it sets `eur_size` to the size of EURUSD that risks 0.5% with a stop 3 × the 14-bar ATR of `eur` away; it also sells EURUSD at market, with a size of `eur_size` and tagged "pair"; it also buys GBPUSD at market, with a size of `eur_size` × `hedge` and tagged "pair".

When the absolute value of `z` is below `exit_z`, it closes all trades tagged "pair".
