Strategy vault / Trend following
EMA Cross Trend Following Strategy with SMA Stop Loss and Re Entry Mechanism
This strategy is a trend-following trading system that combines Exponential Moving Averages (EMA) and Simple Moving Averages (SMA). It generates trading signals based on the crossover of EMA50 and EMA150, uses SMA150…

Overview
This strategy is a trend-following trading system that combines Exponential Moving Averages (EMA) and Simple Moving Averages (SMA). It generates trading signals based on the crossover of EMA50 and EMA150, uses SMA150 as a stop-loss line, and includes a re-entry mechanism after stop-loss. This design enables both medium to long-term trend capture and effective risk control.
Strategy Principles
The core logic includes several key elements:
- Entry signals: Long positions are triggered when EMA50 crosses above EMA150; short positions when EMA50 crosses below EMA150.
- Stop-loss mechanism: Positions are closed when price falls below SMA150.
- Re-entry mechanism: After a stop-loss, re-entry long positions are triggered when price breaks above EMA150; short positions when EMA50 crosses below EMA150 again.
- Trade execution: The strategy executes trades within a specified time range, considering 0.1% commission and 3 pips slippage.
Strategy Advantages
- Strong trend-following capability: Effectively captures market trends using different period moving average combinations.
- Comprehensive risk control: Clear stop-loss conditions prevent excessive losses.
- Flexible re-entry mechanism: Allows re-entry when market conditions improve, increasing profit opportunities.
- Reasonable parameter settings: EMA50 and EMA150 periods balance sensitivity and stability.
- Considers actual trading costs: Includes commission and slippage factors, closer to real trading environment.
Strategy Risks
- Choppy market risk: May generate frequent false breakout signals in sideways markets.
- Lag risk: Moving averages have inherent lag, potentially missing optimal entry points.
- Re-entry risk: Consecutive stop-losses may occur in highly volatile markets.
- Money management risk: Strategy lacks specific position sizing rules.
- Market environment dependence: Strategy performance may vary significantly across different market cycles.
Optimization Directions
- Incorporate volatility indicators: Add ATR or Bollinger Bands to adjust stop-loss positions adaptively.
- Improve position management: Implement volatility-based dynamic position sizing system.
- Optimize re-entry conditions: Combine with oscillators like RSI to improve re-entry signal accuracy.
- Add market environment filters: Include trend strength indicators to reduce trading frequency in low-trend markets.
- Develop adaptive parameters: Dynamically adjust moving average periods based on market volatility.
Summary
This is a well-designed trend-following strategy that captures trends through moving average crossovers and includes comprehensive risk control mechanisms. Its main strengths lie in systematic trend-following capability and risk management design, but market environment impact needs consideration in practical application. The strategy has potential for further improvement through the suggested optimization directions.
Source Pine Script
/*backtest
start: 2024-02-22 00:00:00
end: 2025-02-19 08:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Binance","currency":"SOL_USDT"}]
*/
//@version=6
strategy("EMA 50 and EMA 150 with SMA150 Stop-loss and Re-Entry #ganges", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=3)
// EMA and SMA Calculations
ema50 = ta.ema(close, 50)
ema150 = ta.ema(close, 150)
sma150 = ta.sma(close, 150)
// Conditions for Buy, Sell, and Stop-Loss
ema50CrossAboveEMA150 = ta.crossover(ema50, ema150) // Buy signal
ema50CrossBelowEMA150 = ta.crossunder(ema50, ema150) // Sell signal
priceCrossAboveEMA150 = ta.crossover(close, ema150) // Price crosses EMA 150 from below
priceCloseBelowSMA150 = close < sma150 // Stop-loss for long positions
// Track stop-loss hit state
var bool stopLossHit = false
// Strategy Logic
// Buy Logic: EMA 50 crosses EMA 150 from below
if ema50CrossAboveEMA150
strategy.entry("Buy Signal", strategy.long, qty=1)
stopLossHit := false // Reset stop-loss state when a new buy position is opened
// Sell Logic: EMA 50 crosses EMA 150 from above
if ema50CrossBelowEMA150
strategy.entry("Sell Signal", strategy.short, qty=1)
stopLossHit := false // Reset stop-loss state when a new sell position is opened
// Stop-Loss for Long Positions: Close if price falls below SMA 150
if strategy.position_size > 0 and priceCloseBelowSMA150
strategy.close("Buy Signal")
stopLossHit := true // Mark stop-loss hit
// Re-Entry Logic After Stop-Loss
if stopLossHit
if priceCrossAboveEMA150 // Re-buy logic: PRICE crosses EMA 150 from below
strategy.entry("Re-Buy Signal", strategy.long, qty=1)
stopLossHit := false // Reset stop-loss state after re-entry
if ema50CrossBelowEMA150 // Re-sell logic: EMA 50 crosses EMA 150 from above
strategy.entry("Re-Sell Signal", strategy.short, qty=1)
stopLossHit := false // Reset stop-loss state after re-entry
// Plot EMA and SMA Lines
plot(ema50, color=color.blue, title="EMA 50")
plot(ema150, color=color.red, title="EMA 150")
plot(sma150, color=color.orange, title="SMA 150")
// // Calculate Recent All-Time High
// highestHigh = ta.highest(high, 500) // Lookback period of 500 bars
// percentageFall = ((highestHigh - close) / highestHigh) * 100
// // Display Percentage Fall on the Most Recent Candle Only
// isLastBar = bar_index == ta.max(bar_index)
// if isLastBar
// labelText = str.tostring(percentageFall, "#.##") + "% Fall from ATH"
// labelPosition = high + ta.atr(14) * 2 // Positioning label above the candle
// label.new(bar_index, labelPosition, labelText, color=color.red, textcolor=color.white, size=size.small, style=label.style_label_down)
Published by ianzeng123 on the FMZ strategy square · last modified 2025-02-27. 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-Cross-Trend-Following-Strategy-with-SMA-Stop-Loss-and-Re-Entry-Mechanism.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
- Bollinger Bands and RSI Trend Following StrategyPine Script · Trend following · 1h
- EMA and RSI Trend Trading StrategyPine Script · Trend following · 1d
- Moving Average Crossover Strategy 430371Pine Script · Trend following · 1h
- Triple SuperTrend Quantitative Trading StrategyPine Script · Trend following · 1d
- Dual directional Trailing Stop Moving Average Trend StrategyPine Script · Trend following · 1m
- Trend Following Strategy Based on Multiple IndicatorsPine Script · Trend following · 2h