Multi-Modal Adaptive Trend-Following and Range Trading Strategy

EMA MACD ATR DCA TP SL
Created on: 2025-06-03 09:03:10 Modified on: 2025-06-03 09:03:10
Copy: 0 Number of hits: 297
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Multi-Modal Adaptive Trend-Following and Range Trading Strategy  Multi-Modal Adaptive Trend-Following and Range Trading Strategy

Overview

NOCTURNA v2.0 Shadow Engine is a highly sophisticated multi-modal adaptive trading system capable of automatically switching between different trading strategies based on market conditions. The system incorporates four primary trading modes: EVE (grid trading), LUCIFER (breakout trading), REAPER (reversal trading), and SENTINEL (trend following), equipped with intelligent risk management modules and adaptive trailing stop functions. The system can automatically identify market states and select the optimal trading strategy in various market environments such as ranging, trending, reversing, and breakout markets to maximize profit opportunities while controlling risk.

Strategy Principles

The core of NOCTURNA v2.0 lies in its market state identification and multi-modal adaptive switching mechanism:

  1. Market State Identification:

    • Ranging market detection: Comparing short-term changes in EMA50 with ATR (math.abs(ema50 - ema50[10]) < atr * 0.25)
    • Trending market detection: Based on the distance between EMA50 and EMA200, plus MACD indicators (math.abs(ema50 - ema200) > atr and macdLine > signalLine)
    • Reversal signal detection: EMA8 and EMA34 crossovers (ta.crossover(ema8, ema34) or ta.crossunder(ema8, ema34))
    • Breakout signal detection: Price crosses with EMA200 (ta.crossover(close, ema200) or ta.crossunder(close, ema200))
  2. Mode Switching Logic:

    • Ranging market activates EVE mode
    • Reversal signals activate REAPER mode
    • Trending market activates SENTINEL mode
    • Breakout signals activate LUCIFER mode
  3. Trading Logic for Each Mode:

    • EVE Mode: Establishes multi-layer grids around a base price for bidirectional trading with fixed spacing (gridSpacing) between each layer
    • LUCIFER Mode: Executes breakout trades based on price crosses with EMA50
    • REAPER Mode: Executes reversal trades based on EMA8 and EMA34 crossovers
    • SENTINEL Mode: Combines EMA50/200 with MACD indicators for trend direction trading
  4. Risk Management:

    • Volatility filter (volatilitySpike): Automatically blocks entries in high-volatility environments
    • Stop-loss settings: Dynamic stop-loss based on ATR (atr * atrMultSL)
    • Take-profit settings: Fixed percentage-based take-profit (tpTarget * close)
    • Trailing stop: Activates trailing stop after reaching a certain profit level (trailTrigger and trailOffset)

Strategy Advantages

  1. Strong Adaptability: The system automatically identifies market states and switches to the most appropriate trading mode without manual intervention, demonstrating exceptional adaptability.

  2. Comprehensive Market Coverage: Through four different trading modes, the system can address almost all market conditions, including ranging, trending, reversing, and key level breakouts.

  3. Compounding Effect of Grid Trading: The multi-layer grid trading in EVE mode can capture small fluctuations in ranging markets, achieving a compounding effect through frequent small profits.

  4. Multi-layered Risk Management: The strategy integrates multiple risk control mechanisms, including volatility filtering, fixed stop-losses, trailing stops, and automatic position management, effectively controlling risk per trade.

  5. Intelligent Trailing Stop: Automatically activates trailing stops after reaching preset profit levels, securing partial profits while giving prices sufficient breathing room to avoid premature exits during normal market fluctuations.

  6. Visual Interface: The built-in HUD panel displays the currently active trading mode and number of open grids in real-time, improving strategy monitoring and operational transparency.

  7. Alert System: Integrates both human-readable and JSON-formatted alerts, facilitating signal acquisition for manual traders and automated trading bots.

Strategy Risks

  1. Parameter Sensitivity: The strategy relies on multiple key parameters (such as EMA periods, grid spacing, ATR multiples) to determine market states and execute trades. Improper parameter settings may lead to frequent false signals or overtrading. The solution is to optimize parameters through backtesting and adjust parameters for different markets and timeframes.

  2. Mode Switching Delay: There may be delays in market state determination and mode switching, leading to the use of inappropriate strategies near turning points. This can be improved by introducing more early signal indicators or shortening the determination cycle.

  3. Grid Trading Trend Risk: Grid trading in EVE mode may continuously add positions in the losing direction during strong trend markets. Solutions include setting overall risk limits and trend filters, or pausing grid trading when clear trends are identified.

  4. Over-reliance on Technical Indicators: The strategy primarily relies on traditional technical indicators like EMA and MACD, which may fail under certain market conditions. It is recommended to integrate price-volume relationship analysis or market structure recognition algorithms to enhance judgment accuracy.

  5. System Complexity: The complexity of a multi-modal system increases the difficulty of code maintenance and strategy understanding, potentially making it challenging to respond quickly to abnormal situations in live trading. Comprehensive testing procedures and emergency handling mechanisms should be established.

Strategy Optimization Directions

  1. Dynamic Parameter Adjustment: Currently, the strategy uses fixed parameters. It can be optimized to automatically adjust parameters based on market volatility, for example:

    • Increasing grid spacing and stop-loss ranges in high-volatility environments
    • Dynamically adjusting trailing stop trigger points and offsets based on historical volatility
    • Automatically adjusting EMA periods based on market cycle characteristics
  2. Multi-timeframe Analysis: Introduce multi-timeframe analysis to ensure trade direction aligns with larger timeframe trends, avoiding counter-trend trades. This can be achieved by analyzing EMA and MACD on higher timeframes.

  3. Market State Refinement: Further refine market states, such as distinguishing between strong and weak trends, regular ranging and contracting ranging markets, etc., and customize trading parameters for more specific market states.

  4. Price-Volume Integration: Integrate volume analysis into the strategy, especially in breakout trading (LUCIFER mode), by confirming whether breakouts are accompanied by increased trading volume to filter out false breakouts.

  5. Adaptive Position Sizing: Dynamically adjust position size based on market volatility, mode win rates, and current profit/loss status, increasing positions on high-confidence signals and reducing risk exposure in uncertain environments.

  6. Machine Learning Enhancement: Introduce machine learning algorithms to optimize mode selection and parameter adjustment, training models with historical data to predict which mode is most effective in the current market environment.

  7. Sentiment Indicator Integration: Incorporate market sentiment indicators (such as VIX or market-specific fear indices) to adjust strategy behavior or pause trading in extreme sentiment environments.

Summary

NOCTURNA v2.0 Shadow Engine is an innovative multi-modal adaptive trading system that provides specially optimized trading strategies for different market environments through intelligent market state recognition and strategy switching. It combines the advantages of grid trading, trend following, reversal trading, and breakout trading, while equipped with comprehensive risk management mechanisms including dynamic stop-losses, intelligent trailing stops, and volatility filtering.

The main advantages of this strategy lie in its comprehensive market coverage and adaptability, enabling consistent performance across different market environments. However, the system’s complexity and parameter sensitivity also present certain risks and optimization challenges. By introducing dynamic parameter adjustment, multi-timeframe analysis, more refined market state classification, and machine learning enhancements, this strategy has the potential to further improve its stability and profitability.

Ultimately, NOCTURNA v2.0 provides a powerful trading framework suitable for experienced traders to apply in live trading under appropriate risk management, or as a foundational template for developing more complex trading systems.

Strategy source code
/*backtest
start: 2025-02-01 00:00:00
end: 2025-06-02 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=5
strategy("NOCTURNA v2.0 – Shadow Engine: Trail Edition", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=2)

// === USER SETTINGS ===
useSL      = true
useTP      = true
useTrail   = true
trailTrigger = 1.5 // % before trail starts
trailOffset  = 0.75 // % trail distance

manualMode = input.string("AUTO", title="Mode", options=["AUTO", "EVE", "LUCIFER", "REAPER", "SENTINEL"])
gridSpacing = 0.015
maxLayers = 4
atrMultSL = 1.5
tpTarget = 0.015

// === INDICATORS ===
ema8   = ta.ema(close, 8)
ema34  = ta.ema(close, 34)
ema50  = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
atr    = ta.atr(14)
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)
volatilitySpike = math.abs(close - open) > 3 * atr

// === AUTO MODE LOGIC ===
isRanging   = math.abs(ema50 - ema50[10]) < atr * 0.25
isTrending  = math.abs(ema50 - ema200) > atr and macdLine > signalLine
isReversing = ta.crossover(ema8, ema34) or ta.crossunder(ema8, ema34)
isBreakout  = ta.crossover(close, ema200) or ta.crossunder(close, ema200)

var string activeMode = "None"
if manualMode != "AUTO"
    activeMode := manualMode
else
    if isRanging
        activeMode := "EVE"
    else if isReversing
        activeMode := "REAPER"
    else if isTrending
        activeMode := "SENTINEL"
    else if isBreakout
        activeMode := "LUCIFER"

// === BASE FOR GRID ===
var float basePrice = na
if na(basePrice) or activeMode != "EVE"
    basePrice := close

var int openTrades = 0
openTrades := 0

// === GRID (EVE) ===
for i = 1 to maxLayers
    longLevel = basePrice * (1 - gridSpacing * i)
    shortLevel = basePrice * (1 + gridSpacing * i)

    if activeMode == "EVE" and not volatilitySpike
        if close <= longLevel
            id = "EVE L" + str.tostring(i)
            strategy.entry(id, strategy.long)
            sl = close - atrMultSL * atr
            tp = useTP ? close + tpTarget * close : na
            strategy.exit("TP/SL " + id, from_entry=id, stop=useSL ? sl : na, limit=tp)
            openTrades += 1

        if close >= shortLevel
            id = "EVE S" + str.tostring(i)
            strategy.entry(id, strategy.short)
            sl = close + atrMultSL * atr
            tp = useTP ? close - tpTarget * close : na
            strategy.exit("TP/SL " + id, from_entry=id, stop=useSL ? sl : na, limit=tp)
            openTrades += 1

// === TRAILING STOP FUNCTION ===
f_trailStop(side, id) =>
    if useTrail
        trigger = close * (trailTrigger / 100)
        offset  = close * (trailOffset / 100)
        if side == "long"
            strategy.exit("Trail " + id, from_entry=id, trail_price=trigger, trail_offset=offset)
        else
            strategy.exit("Trail " + id, from_entry=id, trail_price=trigger, trail_offset=offset)

// === LUCIFER MODE ===
if activeMode == "LUCIFER" and not volatilitySpike
    if ta.crossover(close, ema50)
        strategy.entry("Lucifer Long", strategy.long)
        f_trailStop("long", "Lucifer Long")
    if ta.crossunder(close, ema50)
        strategy.entry("Lucifer Short", strategy.short)
        f_trailStop("short", "Lucifer Short")

// === REAPER MODE ===
if activeMode == "REAPER" and not volatilitySpike
    if ta.crossover(ema8, ema34)
        strategy.entry("Reaper Long", strategy.long)
        f_trailStop("long", "Reaper Long")
    if ta.crossunder(ema8, ema34)
        strategy.entry("Reaper Short", strategy.short)
        f_trailStop("short", "Reaper Short")

// === SENTINEL MODE ===
if activeMode == "SENTINEL" and not volatilitySpike
    if ema50 > ema200 and macdLine > signalLine
        strategy.entry("Sentinel Long", strategy.long)
        f_trailStop("long", "Sentinel Long")
    if ema50 < ema200 and macdLine < signalLine
        strategy.entry("Sentinel Short", strategy.short)
        f_trailStop("short", "Sentinel Short")

// === DASHBOARD PANEL ===
var label panel = na
label.delete(panel)
panel := label.new(bar_index, high,
  "NOCTURNA v2.0\nMode: " + activeMode + "\nOpen Grids: " + str.tostring(openTrades),
  style=label.style_label_left, textcolor=color.white, color=color.black)

// === ALERTS – Human Readable
alertcondition(activeMode == "EVE", title="EVE Signal", message="🕊️ NOCTURNA: EVE Grid")
alertcondition(activeMode == "LUCIFER", title="Lucifer Signal", message="🔥 NOCTURNA: LUCIFER Breakout")
alertcondition(activeMode == "REAPER", title="Reaper Signal", message="☠️ NOCTURNA: REAPER Reversal")
alertcondition(activeMode == "SENTINEL", title="Sentinel Signal", message="🛡️ NOCTURNA: SENTINEL Trend")

// === ALERTS – JSON for Bots
alertcondition(activeMode == "EVE", title="JSON EVE", message='{"mode":"EVE","ticker":"{{ticker}}","price":"{{close}}"}')
alertcondition(activeMode == "LUCIFER", title="JSON LUCIFER", message='{"mode":"LUCIFER","ticker":"{{ticker}}","price":"{{close}}"}')
alertcondition(activeMode == "REAPER", title="JSON REAPER", message='{"mode":"REAPER","ticker":"{{ticker}}","price":"{{close}}"}')
alertcondition(activeMode == "SENTINEL", title="JSON SENTINEL", message='{"mode":"SENTINEL","ticker":"{{ticker}}","price":"{{close}}"}')

// === VISUAL PLOT
plot(ema50, title="EMA 50", color=color.gray)