Strategy vault / Trend following
Trend Following Strategy with Dynamic Stops
This strategy generates trading signals when price crosses EMA and uses ATR as a dynamic stop loss to manage risks.

Overview
This strategy generates trading signals when price crosses EMA and uses ATR as a dynamic stop loss to manage risks.
How It Works
The key logic is:
Calculate ATR as the stop loss line, ATR value determines stop distance nLoss
Price source is close price by default, use Heikin Ashi close if Heikin Ashi option h is enabled
xATRTrailingStop tracks dynamic stop loss line based on price comparison with previous stop
Position pos is 1 for long when price crosses above stop loss line, -1 for short when crosses below, else 0
EMA crossover signals, above EMA is buy signal, below is sell signal
Enter trades on buy/sell signals, exit on opposite signals
Color bars based on position, mark signals and stop loss lines
This strategy follows trends with dynamic stops based on ATR. It can identify trends and manage risks effectively.
Advantages
The advantages are:
ATR-based dynamic stop adapts to market volatility
EMA filter reduces false signals from noise
Optional Heikin Ashi filters noise and identifies trend
Clear long/short position avoids whipsaws from trailing stopOrder translation result:
Visual aids like lines, labels and coloring
Simple and easy to understand logic for modifying
Customizable ATR period and multiplier for different markets
In summary, by combining trend following and dynamic stops, this strategy can catch trends and manage risks well for swing trading.
Risks
There are some risks to consider:
EMA signals may lag missing short-term moves
Frequent stop loss triggers possible in choppy markets
No consideration of costs like commissions
Lack of position sizing control
Performance depends on parameter tuning
Risk of whipsaws in ranging markets
Requires monitoring and intervention
Risks can be reduced by optimizing parameters, adding filters, sizing positions properly, monitoring performance, and intervening when necessary.
Optimization
Some ways to improve the strategy:
Adjust ATR parameters for different markets
Test other moving averages to filter signals
Add trend filter indicators for higher probability
Implement position sizing limits
Add entry conditions like volume, distance from MA
Incorporate costs like commissions into stops
Optimize entry and exit timing with more signals
Introduce profit taking or trailing stops
Automated parameter optimization
By combining more techniques for entries, exits, filters, and parameter tuning, the strategy can be further robustified.
Conclusion
This strategy combines dynamic stops and trend following nicely. With effective stops, smooth trend tracking, ease of use, and customizability, it is suitable for swing trading trends. But proper risk management, monitoring, and parameter tuning is required. When applied well on trending markets, good results can be achieved. Overall it provides a simple and practical approach to combining trend trading and risk management.
Parameters
| Name | Default | What it controls |
|---|---|---|
| v_input_1 | true | Key Vaule. 'This changes the sensitivity' |
| v_input_2 | 10 | ATR Period |
| v_input_3 | false | Signals from Heikin Ashi Candles |
Source Pine Script
/*backtest
start: 2022-10-25 00:00:00
end: 2023-10-31 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=4
strategy(title="UT Bot Strategy", overlay = true)
//CREDITS to HPotter for the orginal code. The guy trying to sell this as his own is a scammer lol.
// Inputs
a = input(1, title = "Key Vaule. 'This changes the sensitivity'")
c = input(10, title = "ATR Period")
h = input(false, title = "Signals from Heikin Ashi Candles")
xATR = atr(c)
nLoss = a * xATR
src = h ? security(heikinashi(syminfo.tickerid), timeframe.period, close, lookahead = false) : close
xATRTrailingStop = 0.0
xATRTrailingStop := iff(src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), src - nLoss),
iff(src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), src + nLoss),
iff(src > nz(xATRTrailingStop[1], 0), src - nLoss, src + nLoss)))
pos = 0
pos := iff(src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0), 1,
iff(src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0)))
xcolor = pos == -1 ? color.red: pos == 1 ? color.green : color.blue
ema = ema(src,1)
above = crossover(ema, xATRTrailingStop)
below = crossover(xATRTrailingStop, ema)
buy = src > xATRTrailingStop and above
sell = src < xATRTrailingStop and below
barbuy = src > xATRTrailingStop
barsell = src < xATRTrailingStop
plotshape(buy, title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(sell, title = "Sell", text = 'Sell', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
barcolor(barbuy ? color.green : na)
barcolor(barsell ? color.red : na)
strategy.entry("long", true, when = buy)
strategy.entry("short", false, when = sell)Published by ChaoZhang on the FMZ strategy square · last modified 2023-11-01. 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/Trend-Following-Strategy-with-Dynamic-Stops.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
- ATR Dynamic Trend Following and EMA Crossover Trading StrategyPine Script · Trend following · 1d
- Dual EMA Filtered ATR Adaptive Trend Following StrategyPine Script · Trend following · 1h
- ATR RSI Enhanced Trend Following Trading SystemPine Script · Trend following
- DPO EMA Trend Crossover Quantitative Strategy ResearchPine Script · Trend following · 1d
- Dynamic ATR Trailing Stop with EMA Cross Combination StrategyPine Script · Trend following · 2h
- Dynamic Moving Average Tracking Strategy 433137Pine Script · Trend following · 1d