Strategy vault / Trend following
EMA Crossover Strategy with Trailing Stop Loss
This strategy uses the crossover of a fast EMA (9-period) and slow EMA (21-period) as entry signals, and incorporates a trailing stop loss to lock in profits and avoid excessive drawdowns.

Overview
This strategy uses the crossover of a fast EMA (9-period) and slow EMA (21-period) as entry signals, and incorporates a trailing stop loss to lock in profits and avoid excessive drawdowns.
Strategy Logic
When the fast EMA crosses above the slow EMA from below, a buy signal is generated. When the fast EMA crosses below the slow EMA from above, a sell signal is triggered.
Once entered, the strategy tracks the highest high in real-time and triggers a trailing stop loss when the current price falls 2% below the highest high, locking in profits.
Advantage Analysis
- Utilizes EMA's trend following and signal generation ability to effectively capture medium-long term trends
- Trailing stop loss locks in most profits, avoiding entire gains being swallowed
- Adjustable EMA parameters cater to different market environments
- Clear buy and sell signal rules, easy to implement
Risk Analysis
- EMA has lagging, may miss short-term opportunities
- Improper trailing stop loss distance setting may prematurely stop loss or render it ineffective
- Parameter mismatch with market may cause excessive trading or insufficient signals
Risk Solutions:
- Choose appropriate EMA parameter combination
- Test and evaluate stop loss parameter
- Adjust parameters to match market volatility dynamics
Optimization Directions
- Dynamically adjust trailing stop distance based on market volatility and risk appetite
- Add other filters to reduce false signals
- Optimize EMA period parameters
- Incorporate trend indicators to avoid counter-trend trading
Conclusion
This strategy integrates the advantages of trend identification and risk control. Through parameter tuning and optimization, it can be adapted to different market types and trading instruments, and is worth further testing and practice.
Source Pine Script
/*backtest
start: 2023-12-12 00:00:00
end: 2023-12-19 00:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=4
strategy("EMA Crossover with Trailing Stop-Loss", overlay=true)
fastEMA = ema(close, 9)
slowEMA = ema(close, 21)
// Entry conditions
longCondition = crossover(fastEMA, slowEMA)
shortCondition = crossunder(fastEMA, slowEMA)
// Trailing stop-loss calculation
var float trailingStop = na
var float highestHigh = na
if (longCondition)
highestHigh := na
trailingStop := na
if (longCondition and high > highestHigh)
highestHigh := high
if (strategy.position_size > 0)
trailingStop := highestHigh * (1 - 0.02) // Adjust the trailing percentage as needed
// Execute trades
strategy.entry("Long", strategy.long, when=longCondition)
strategy.entry("Short", strategy.short, when=shortCondition)
// Apply trailing stop-loss to long positions
strategy.exit("Long", from_entry="Long", loss=trailingStop)
// Plot EMAs and Trailing Stop-Loss
plot(fastEMA, color=color.green, title="Fast EMA")
plot(slowEMA, color=color.red, title="Slow EMA")
plot(trailingStop, color=color.orange, title="Trailing Stop-Loss", linewidth=2)
Published by ChaoZhang on the FMZ strategy square · last modified 2023-12-20. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.
Build this with AgenKit
A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/EMA-Crossover-Strategy-with-Trailing-Stop-Loss.md- npx agenkit install engineering-kit in your project
- Paste the command into your agent and approve each phase
- Get tests, backtest, risk controls and a paper-trading switch
Understand it first
Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.
Related specs
- 200 EMA VWAP MFI Trend Following StrategyPine Script · Trend following · 1d
- 4 EMA Trend StrategyPine Script · Trend following · 1d
- ADX MA and EMA Long Only Trend Tracking StrategyPine Script · Trend following · 1d
- ATR Dynamic Trend Following and EMA Crossover Trading StrategyPine Script · Trend following · 1d
- ATR and Moving Average Crossover Hybrid StrategyPine Script · Trend following · 1h
- ATR and T3 Moving Average StrategyPine Script · Trend following · 5m