Strategy vault / Trend following
Trend Following Strategy Based on Smoothed Deviation
This strategy utilizes the deviation between short-term high-low and short-term & long-term average cost to determine the trend. It aims to increase short-term sensitivity and reduce the cost of consolidation by…

Overview
This strategy utilizes the deviation between short-term high-low and short-term & long-term average cost to determine the trend. It aims to increase short-term sensitivity and reduce the cost of consolidation by enlarging the previous and subsequent smoothing average functions, so as to decrease small losses during consolidation while maintaining significant profits when trends emerge.
Strategy Principles
Calculate short-term cost: Use ta.highest and ta.lowest functions to calculate the highest and lowest prices of the recent shortTerm candles, and take the average as the short-term cost
Calculate long-term cost: Use ta.sma function to calculate the simple moving average of closing prices of recent longTerm candles as the long-term cost
Calculate deviation: Subtract long-term cost from short-term cost
Smooth deviation: Smooth the deviation to reduce misjudgements using ta.sma for simple moving average
Determine trend: If the smoothed deviation is greater than the threshold, judge it as an upward trend. If less than the negative threshold, judge it as a downward trend.
Entry and exit: Go long when tracing upward trend and go short when tracing downward trend.
Advantage Analysis
- Increase short-term sensitivity to quickly capture short-term opportunities
- Smoothing processing reduces probability of misjudgement
- Setting channel reduces unnecessary opening positions
- Following trends closely allows timely stop loss and profit taking
Risk Analysis
- Short-term focus can easily lead to being trapped, stop loss range needs to be appropriately enlarged
- Parameters require repeated testing, improper settings of short-term, long-term days and deviation smoothing parameters can lead to oversensitivity or slowness
- Channel amplitude needs to be reasonably set, too large or small can both lead to issues
- Likely to be trapped in repeated opening positions during volatile sideways markets
Risk Resolution:
- Appropriately enlarge stop loss range to avoid traps
- Optimize parameter settings to balance sensitivity and misjudgement rate
- Test and optimize channel parameters
- Add filtering conditions to avoid unnecessary opening positions during volatility
Optimization Directions
- Optimize short-term high-low points, such as calculating smoother short-term costs like PA or weighted averages
- Test different long-term cost calculation methods
- Try different deviation smoothing algorithms
- Optimize channel parameters
- Add opening filters like breakouts, surges in volume etc.
- Reversals Add reverse trading opportunities
Summary
Overall this is a very simple and direct trend following strategy. Compared to common indicators like moving averages, by calculating the deviation between short and long term costs, it can judge trend changes faster. Meanwhile, the smoothing processing also provides greater flexibility in parameter optimization, allowing sensitivity and misjudgement rates to be balanced by adjusting the smoothing parameters. In summary, this strategy has characteristics like agility, directness and high customizability. It is a promising strategy worth deeper exploration. By continuing to optimize parameters and adding auxiliary judgement conditions, there is potential to further enhance the strategy's performance.
Parameters
| Name | Default | What it controls |
|---|---|---|
| v_input_1 | 5 | Short Term |
| v_input_2 | 20 | Long Term |
| v_input_3 | 5 | Smoothing |
| v_input_4 | false | Threshold |
Source Pine Script
/*backtest
start: 2024-01-01 00:00:00
end: 2024-01-31 23:59:59
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dead0001ing1
//@version=5
strategy("Trend-Following Indicator", overlay=true)
// Set Parameters
shortTerm = input(5, "Short Term")
longTerm = input(20, "Long Term")
smooth = input(5, "Smoothing")
threshold = input(0, "Threshold")
// Calculate short-term cost
shortH = ta.highest(high, shortTerm)
shortL = ta.lowest(low, shortTerm)
shortCost = (shortH + shortL) / 2
// Calculate long-term cost
longCost = ta.sma(close, longTerm)
// Calculate average deviation
deviation = shortCost - longCost
// Smooth average deviation
smoothedDeviation = ta.sma(deviation, smooth)
// Determine trend
isTrendingUp = smoothedDeviation > threshold
isTrendingDown = smoothedDeviation < -threshold
// Display trend-following signals
plotshape(isTrendingUp, title="Trending Up", location=location.belowbar, color=color.green, style=shape.labelup, text="Up", size=size.small)
plotshape(isTrendingDown, title="Trending Down", location=location.abovebar, color=color.red, style=shape.labeldown, text="Down", size=size.small)
// Define entry and exit strategy
if isTrendingUp
strategy.entry("Long", strategy.long)
strategy.close("Long", when=isTrendingDown)
if isTrendingDown
strategy.entry("Short", strategy.short)
strategy.close("Short", when=isTrendingUp)
Published by ChaoZhang on the FMZ strategy square · last modified 2024-02-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/Trend-Following-Strategy-Based-on-Smoothed-Deviation.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
- ADX MA and EMA Long Only Trend Tracking StrategyPine Script · Trend following · 1d
- ATR and Moving Average Crossover Hybrid StrategyPine Script · Trend following · 1h
- Adaptive FVG Detection and MA Trend Trading Strategy with Dynamic ResistancePine Script · Trend following · 1d
- Adaptive Risk Management Strategy Based on Dynamic ATR and Moving Average CrossoverPine Script · Trend following · 2h
- Adaptive Trading Strategy Based on Stochastic RSI Dual Line CrossoverPine Script · Trend following · 4h
- Adaptive Volatility Based Trend Following Short Strategy with Time Delay and Stop Loss ProtectionPine Script · Trend following · 2m