Trend Following Algorithm Development
Trend following is one of the longest-lived trading strategies: follow the trend until it ends. Difference from momentum: momentum predicts continuation based on past returns, trend following simply follows current move using technical indicators.
Trend Identification
Moving Average crossover: classic. EMA(9) crosses EMA(21) from bottom up → uptrend, enter long. Reverse → downtrend, enter short or exit.
Dual Moving Average System: two moving averages (fast + slow). Position held while fast > slow.
Triple MA system: three MAs (fast, medium, slow). Bullish signal: fast > medium > slow.
Donchian Channel: channel from N-period high (upper) and low (lower). Upper boundary breakout = long entry. Classic Turtle Traders Richard Dennis approach.
Parameters and Optimization
Typical parameters for crypto market (require optimization):
| Strategy | Fast MA | Slow MA | Timeframe |
|---|---|---|---|
| Short-term | EMA 9 | EMA 21 | 1h–4h |
| Mid-term | EMA 21 | EMA 55 | 4h–1D |
| Long-term | SMA 50 | SMA 200 | 1D |
| Donchian | N=20 (entry) | N=10 (exit) | 1D |
Position Sizing via ATR
Position size determined through ATR (Average True Range) instead of fixed capital %:
def calculate_position_size(capital, entry_price, atr, risk_pct=0.01):
risk_amount = capital * risk_pct
stop_distance = 2 * atr
qty = risk_amount / stop_distance
return qty
This guarantees equal monetary risk per trade regardless of asset volatility.
Trailing Stop
Trend following without trailing stop is not trend following. Position held while trend continues, closed when it ends:
- ATR trailing stop: stop moves up N × ATR below highest reached price
- Chandelier Exit: 3×ATR from N-period maximum
- MA trailing: exit if close below EMA(21)
Pyramiding
Adding to profitable positions as trend continues — key turtle trading technique. On each next ATR move in trend direction, add position (smaller size). Maximum 4 additions.
Requirement: each addition only if current total position is profitable.
Entry Filters
To avoid trading in weak trend:
- ADX > 20 before entry
- Volume above average on breakout
- Volatility not extremely high (ATR < 2× average — don't trade during market panic)
Backtesting
Trend following systems work well on long-term tests, but have significant drawdown periods. Key metrics: MAR Ratio (CAGR / Max Drawdown), Calmar Ratio, profitable trade percentage (usually low, 30–40%, but winners larger than losers).
Stack: Python, pandas, CCXT, PostgreSQL. System runs in real time, checking conditions on each candle close of selected timeframe. Support for multiple instruments simultaneously with portfolio correlation control.







