TrendFollowingBot
A pragmatic trend-following strategy that pairs an EMA trend filter with two complementary entry patterns:
- a crossback into the trend (price crosses the EMA and the very next bar opens on the trend side), and
- a volatility-scaled breakout away from the EMA (the current open is beyond the EMA by k × ATR).
Stops, trailing logic, and position sizing come from your configured ExitStrategy (e.g., ATR-trailing), so this bot focuses purely on when to enter. Signals are read from the previous closed bar, and orders are placed at the current bar open to avoid look-ahead.
Overview
- What it does: Uses an EMA to define trend and ATR to demand “enough distance” before entering.
- Two entry modes:
- Crossback confirms that price actually crossed the EMA and opened on the trend side.
- ATR breakout requires the open to be at least
k × ATRbeyond the EMA (defaultk = 1.5).
- Risk first: Exits and sizing are handled by your exit module (e.g., ATR-trailing, fixed-ratio).
- Timing: Compute on bar t-1; place at the open of bar t (no look-ahead).
- Use cases: Clean template for experimenting with EMA spans, ATR multipliers, and different exit policies.
How it works (at a glance)
Let:
ema_prev= EMA value on the previous (closed) barprev_close= previous bar’s closeentry_open= current bar open (execution price)atr_prev= previous bar’s ATRk=breakout_atr_mult(default 1.5)
1) Crossback into trend
- Long:
prev_close ≤ ema_prevandentry_open > ema_prev→ buy - Short:
prev_close ≥ ema_prevandentry_open < ema_prev→ sell
2) EMA ± (k × ATR) breakout
- Long:
entry_open > ema_prev + k × atr_prev→ buy - Short:
entry_open < ema_prev − k × atr_prev→ sell
If neither rule fires, the bot stays flat for that bar.
Key parameters
| Parameter | Default | Description |
|---|---|---|
trend_ema_span | 50 | EMA length for the trend filter (expects a column like ema_50). |
breakout_atr_mult | 1.5 | ATR multiplier for the EMA-distance breakout threshold. |
Open the notebook
View Notebook →