State Machine Momentum

State Machine Momentum is a strategy that trades EURUSD on 15-minute bars. It holds at most 1 open trade and stops for the day after losing 2%.

tables and dashboardsstatefunctions and types

state-machine-momentum.abx
1strategy "State Machine Momentum"
2market: EURUSD
3bars: 15m
4max_open: 1
5max_daily_loss: 2%
6
7enum Phase: waiting, armed, in_trade, cooling
8
9state phase = Phase.waiting
10state armed_at = 0
11state entries = 0
12state exit_prices: map<string, price> = []
13
14action fn enter(reason: string) -> bool:
15buy risk: 0.5%, stop: 1.5 * atr(14), target: 2R, tag: reason
16return true
17
18match phase:
19Phase.waiting:
20if rsi(close, 14) < 35:
21phase = Phase.armed
22armed_at = bar.index
23Phase.armed:
24if crosses_above(rsi(close, 14), 40):
25phase = Phase.in_trade
26elif bar.index - armed_at > 20:
27phase = Phase.waiting
28Phase.in_trade:
29if trades.open().len == 0 and bar.index - armed_at > 1:
30phase = Phase.cooling
31armed_at = bar.index
32Phase.cooling:
33if bar.index - armed_at > 10:
34phase = Phase.waiting
35
36when starts(phase == Phase.in_trade):
37enter("state machine")
38entries += 1
39
40on exit(trade):
41exit_prices.set(trade.tag, trade.exit_price)
42
43dashboard position: top_left, rows: [["Phase", "{phase}"], ["Entries", "{entries}"]]
What this script says

State Machine Momentum is a strategy that trades EURUSD on 15-minute bars. It holds at most 1 open trade and stops for the day after losing 2%.

It defines the action enter(reason), which returns true or false.

It remembers phase, armed_at, entries and exit_prices from one bar to the next.

When phase is in trade becomes true, it runs enter and adds 1 to entries.

When a trade closes, it works out exit_prices.set(trade.tag, trade.exit_price).

On each bar, it checks phase: for waiting it checks whether the 14-bar RSI is below 35 and, if so, sets phase to armed and sets armed_at to the bar number; for armed it checks whether the 14-bar RSI crosses above 40 and, if so, sets phase to in trade; otherwise, if the bar number minus armed_at is above 20, sets phase to waiting; for in trade it checks whether the number of open trades is 0 and the bar number minus armed_at is above 1 and, if so, sets phase to cooling and sets armed_at to the bar number; for cooling it checks whether the bar number minus armed_at is above 10 and, if so, sets phase to waiting.

On the chart, it shows a dashboard.

Try this in the Terminal. AlgoBars is free: $0 a month, no card needed.

Create my free account