# Regression Spread

> Regression Spread is a strategy that trades AUDUSD and NZDUSD on 1-hour bars. It holds at most 2 open trades.

Source: https://algobarsx.com/docs/ex-37-regression-spread/

```algobarsx
strategy "Regression Spread"
    markets: AUDUSD, NZDUSD
    bars: 1h
    max_open: 2

input lookback = 250
input entry_z = 2.2

aud = bars(AUDUSD)
nzd = bars(NZDUSD)
model = ols(aud.close, [nzd.close], lookback)
z = zscore(model.residual, lookback)
fit_ok = model.r_squared > 0.6
flat = trades.open(tag: "spread").len == 0

when fit_ok and z > entry_z and flat:
    sell market: AUDUSD, risk: 0.5%, stop: atr(14, on: aud) * 3, tag: "spread"
    buy market: NZDUSD, risk: 0.5%, stop: atr(14, on: nzd) * 3, tag: "spread"

when fit_ok and z < -entry_z and flat:
    buy market: AUDUSD, risk: 0.5%, stop: atr(14, on: aud) * 3, tag: "spread"
    sell market: NZDUSD, risk: 0.5%, stop: atr(14, on: nzd) * 3, tag: "spread"

when abs(z) < 0.25 or not fit_ok:
    close_all tag: "spread"
```
What this script says

Regression Spread is a strategy that trades AUDUSD and NZDUSD on 1-hour bars. It holds at most 2 open trades.

You can change 2 inputs: `lookback` (default 250) and `entry_z` (default 2.2).

It calculates `aud` as AUDUSD bars, `nzd` as NZDUSD bars, `model` as the ols (target `aud.close`, factors `nzd.close`, length `lookback`), `z` as the z-score of `model.residual` over `lookback` bars, `fit_ok` as whether `model.r_squared` is above 0.6 and `flat` as whether the number of open trades tagged "spread" is 0.

When `fit_ok` and `z` is above `entry_z` and `flat`, it sells AUDUSD at market, risking 0.5% of the balance, with a stop 3 × the 14-bar ATR of `aud` from the entry and tagged "spread"; it also buys NZDUSD at market, risking 0.5% of the balance, with a stop 3 × the 14-bar ATR of `nzd` from the entry and tagged "spread".

When `fit_ok` and `z` is below -`entry_z` and `flat`, it buys AUDUSD at market, risking 0.5% of the balance, with a stop 3 × the 14-bar ATR of `aud` from the entry and tagged "spread"; it also sells NZDUSD at market, risking 0.5% of the balance, with a stop 3 × the 14-bar ATR of `nzd` from the entry and tagged "spread".

When the absolute value of `z` is below 0.25 or not `fit_ok`, it closes all trades tagged "spread".
