Strategy vault / Trend following
Dual EMA Crossover Strategy 431966
This strategy generates trading signals based on the crossover and crossunder of fast and slow EMA lines, belonging to trend following strategies. It buys when the fast EMA crosses over the slow EMA, and sells when…

Overview
This strategy generates trading signals based on the crossover and crossunder of fast and slow EMA lines, belonging to trend following strategies. It buys when the fast EMA crosses over the slow EMA, and sells when the fast EMA crosses under the slow EMA, implementing a simple trend tracking strategy.
Strategy Logic
The core logic of this strategy mainly includes the following parts:
Calculate fast and slow EMAs: Use ta.ema() to calculate fast EMA of length fastInput and slow EMA of length slowInput.
Set backtest time range: Use useDateFilter to set whether to filter backtest time range, and use backtestStartDate and backtestEndDate to set start and end time.
Generate trading signals: Use ta.crossover() and ta.crossunder() to compare fast and slow EMAs, generating buy signals when fast EMA crosses over slow EMA, and sell signals when fast EMA crosses under slow EMA.
Handle orders outside time range: Cancel unfilled orders outside backtest time range, and flatten all positions.
Plot EMA lines: Plot fast and slow EMA lines on the chart.
Advantage Analysis
This is a very simple trend following strategy, with the following advantages:
Simple logic, easy to understand and implement.
EMA smooths price data and reduces noise trading.
Customizable EMA periods, adaptable to different market environments.
Flexible backtest time range for testing specific time periods.
Optimizable entry and exit conditions, can be combined with other indicators.
Risk Analysis
This strategy also has some risks:
Dual EMA strategy is crude, unable to adapt flexibly to market changes.
Risk of frequent trading and repeated trading.
Improper EMA parameters may cause wrong trading signals.
Unreasonable backtest time range may lead to overfitting.
Risk of unavoidable drawdown and losses.
Risks can be managed through parameter optimization, filtering fluctuations, stop loss, etc.
Optimization Directions
This strategy can be optimized in the following aspects:
Optimize EMA periods to find the best parameter combination.
Add other indicators for filtering unnecessary trades.
Add stop loss to control single trade loss.
Incorporate trend, volatility filters to reduce trading frequency.
Test different products to find the best fit.
Use slippage, commission for more realistic backtest.
Summary
In summary, this is a very simple dual EMA crossover strategy with clear logic by comparing fast and slow EMAs. The advantage is simple implementation, but it also has issues like frequent trading, overfitting. Next step is to improve on parameter optimization, risk management for a more robust strategy.
Parameters
| Name | Default | What it controls |
|---|---|---|
| v_input_1 | 10 | Fast EMA |
| v_input_2 | 21 | Slow EMA |
| v_input_bool_1 | true | (?Backtest Time Period)Filter Date Range of Backtest |
| v_input_3 | timestamp(1 Jan 2018) | Start Date |
| v_input_4 | timestamp(7 Sep 2023) | End Date |
Source Pine Script
/*backtest
start: 2022-11-06 00:00:00
end: 2023-11-12 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=5
strategy("MollyETF_EMA_Crossover", overlay = true, initial_capital = 100000, default_qty_value=100, default_qty_type=strategy.percent_of_equity)
fastInput = input( 10, "Fast EMA")
slowInput = input( 21, "Slow EMA")
// Calculate two moving averages with different lengths.
float fastMA = ta.ema(close, fastInput)
float slowMA = ta.ema(close, slowInput)
// STEP 1. Create inputs that configure the backtest's date range
useDateFilter = input.bool(true, title="Filter Date Range of Backtest",
group="Backtest Time Period")
backtestStartDate = input(timestamp("1 Jan 2018"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
backtestEndDate = input(timestamp("7 Sep 2023"),
title="End Date", group="Backtest Time Period",
tooltip="This end date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
// STEP 2. See if current bar falls inside the date range
inTradeWindow = true
// STEP 3. Include the date filter with the entry order conditions
// Enter a long position when `fastMA` crosses over `slowMA`.
if inTradeWindow and ta.crossover(fastMA, slowMA)
strategy.entry("buy", strategy.long)
// Enter a short position when `fastMA` crosses under `slowMA`.
if inTradeWindow and ta.crossunder(fastMA, slowMA)
strategy.close_all(comment="sell")
// STEP 4. With the backtest date range over, exit all open
// trades and cancel all unfilled pending orders
if not inTradeWindow and inTradeWindow[1]
strategy.cancel_all()
strategy.close_all(comment="Date Range Exit")
// Plot the moving averages.
plot(fastMA, "Fast MA", color.aqua)
plot(slowMA, "Slow MA", color.orange)
Published by ChaoZhang on the FMZ strategy square · last modified 2023-11-13. 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/Dual-EMA-Crossover-Strategy-431966.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