Strategy vault / Trend following
EMA Oscillator Trend Following Strategy
This strategy uses the EMA indicator to identify price trends and combines standard deviation to calculate buy and sell signals for trend following trading. The main idea is to compute the difference between the…

Overview
This strategy uses the EMA indicator to identify price trends and combines standard deviation to calculate buy and sell signals for trend following trading. The main idea is to compute the difference between the close price and EMA, set a threshold to trigger orders.
Strategy Logic
The strategy first calculates the difference v between close price and EMA of length ema_length. Then it calculates the standard deviation dev of v over ema_length periods. Next it determines the direction coefficient k, with k=1 for long and k=-1 for short. The buy signal threshold dev_limit is calculated by k * dev * factor limit. When v crosses over dev_limit, a buy signal is triggered. The exit signal is when v crosses 0.
The strategy provides two modes:
Buy short, go long when v crosses below negative dev_limit, to follow a downtrend.
Buy long, go long when v crosses above positive dev_limit, to follow an uptrend.
In summary, the strategy dynamically calculates the standard deviation of the difference between price and EMA to set the threshold and follows trends. The factor controls the sensitivity of buy signals. ema_length determines the EMA period. The buy mode controls the order direction.
Advantage Analysis
The advantages of this strategy include:
EMA identifies trend direction well by smoothing prices.
Dynamic threshold based on standard deviation adapts better than fixed thresholds.
Two buy modes allow following uptrend or downtrend.
The factor provides flexibility in tuning buy sensitivity. ema_length allows EMA period optimization.
The logic is simple and easy to understand and modify.
Position sizing can be configured flexibly for aggressive trend following.
Risk Analysis
The risks of the strategy:
EMA has lag and may miss trend turning points.
It relies on parameter optimization. Improper settings lead to insufficient sensitivity or oversensitivity.
Trend following risks larger losses when trend reverses.
Frequent long/short switches increase trading frequency.
Frequent signals in ranging markets increase costs.
To address the risks, consider adding stop loss, optimizing parameters, adding filters to avoid overtrading, etc.
Optimization Directions
The strategy can be optimized by:
Testing different EMA periods to find the optimal length.
Testing different factor values to find the best sensitivity.
Optimizing position sizing strategies, e.g. pyramiding.
Adding filters to avoid wrong trades in choppy markets.
Incorporating stop loss to control single trade loss.
Optimizing parameters separately for the two buy modes.
Researching trend reversal signals to stop trend following.
Conclusion
The strategy identifies trends with EMA and generates dynamic threshold orders to follow trends. The logic is simple and clear. Position sizing can be aggressive for trend chasing. It has risks that need to be addressed through parameter optimization and stop loss. It serves as a good example to learn indicator combination and parameter tuning.
Parameters
| Name | Default | What it controls |
|---|---|---|
| v_input_int_1 | 200 | Period |
| v_input_float_1 | 1.7 | Factor |
| v_input_string_1 | 0 | Model: Buy on enter to OverSell | Buy on enter to OverBuy |
Source Pine Script
/*backtest
start: 2023-10-06 00:00:00
end: 2023-11-05 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Azzrael
// Based on EMA and EMA Oscilator https://www.tradingview.com/script/qM9wm0PW-EMA-Oscilator-Azzrael/
// (EMA - close) + Std Dev + Factor = detecting oversell/overbuy
// Long only!
// Pyramiding - sometimes, depends on ...
// There 2 enter strategies in one script
// 1 - Classic, buy on entering to OverSell zone (more profitable ~> 70%)
// 2 - Crazy, buy on entering to OverBuy zone (catching trend and pyramiding, more net profit)
// Exit - crossing zero of (EMA - close)
//@version=5
strategy("STR:EMA Oscilator [Azzrael]", overlay=false,
margin_long=100,
margin_short=100,
currency=currency.USD,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
pyramiding=3)
entry_name="Buy"
ema_length = input.int(200, "Period", minval=2, step=10)
limit = input.float(1.7, "Factor", minval=1, step=0.1, maxval=10)
dno = input.string(defval="Buy on enter to OverSell", title="Model", options=["Buy on enter to OverSell", "Buy on enter to OverBuy"]) == "Buy on enter to OverSell"
v = close - ta.ema(close, ema_length)
dev = ta.stdev(v, ema_length)
k = dno ? -1 : 1
dev_limit = k*dev*limit
cond_long = dno ? ta.crossunder(v, dev_limit) : ta.crossover(v, dev_limit)
cond_close = ta.cross(v, 0)
// dev visualization
sig_col = (dno and v <= dev_limit) or (not dno and v >= dev_limit) ? color.green : color.new(color.blue, 80)
plot(dev_limit, color=color.green)
plot(k*dev, color=color.new(color.blue, 60))
plot(v, color=sig_col )
hline(0)
// Make love not war
strategy.entry(entry_name, strategy.long, when=cond_long)
strategy.close(entry_name, when=cond_close)
Published by ChaoZhang on the FMZ strategy square · last modified 2023-11-06. 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-Oscillator-Trend-Following-Strategy.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