Overview
The Multi-Modal Adaptive Grid Trailing Strategy is a highly intelligent quantitative trading system that integrates multiple trading modes and technical indicators, automatically switching to the optimal trading strategy based on market conditions. Developed on the NOCTURNA v2.0 framework, this strategy precisely identifies and adapts to different market environments by integrating EMA, MACD, and ATR indicators. The system includes four core trading modes: Lucifer (breakout hunter mode), Reaper (reversal scalping mode), Sentinel (macro trend mode), and EVE (range DCA harvesting mode). Each mode is designed for specific market conditions and is equipped with comprehensive risk management mechanisms, including stop-loss, take-profit, and trailing stop functionalities.
Strategy Principles
The core principle of this strategy is to identify market states through a combination of technical indicators and automatically switch to the optimal trading mode:
Market State Identification Mechanism:
- Range Market: When the 50EMA change is less than 0.25 times the ATR
- Trending Market: When the difference between 50EMA and 200EMA is greater than ATR, and the MACD line is above the signal line
- Reversal Market: When 8EMA and 34EMA cross
- Breakout Market: When price crosses the 200EMA
Mode Switching Logic:
- EVE Mode: Activated in range-bound markets
- REAPER Mode: Activated at market reversal points
- SENTINEL Mode: Activated in clearly trending markets
- LUCIFER Mode: Activated when price breaks through important levels
Trade Execution Mechanism:
- EVE Mode: Implements grid trading strategy, setting up long and short grids based on base price and grid spacing
- LUCIFER Mode: Opens positions when price breaks through 50EMA, using trailing stops
- REAPER Mode: Opens positions when 8EMA crosses 34EMA, using trailing stops
- SENTINEL Mode: Confirms trend direction using EMA and MACD before opening positions, with trailing stops
Risk Control System:
- Stop Loss: Dynamically calculated based on ATR
- Take Profit: Set as a percentage target
- Trailing Stop: Activated when price reaches trigger level, with offset to protect profits
Strategy Advantages
Strong Adaptability: The strategy intelligently identifies four different market states and automatically switches to the most suitable trading mode, maintaining competitiveness across various market environments.
Multi-dimensional Risk Management: By combining traditional stop-loss, percentage take-profit, and trailing stops, the strategy builds a multi-layered risk control system that both protects capital and maximizes trend profits.
Grid Trading Optimization: In range-bound markets, the EVE mode's grid trading design allows the system to automatically execute buy-low-sell-high, improving capital efficiency.
Volatility Filtering: The strategy has built-in volatility filtering mechanisms to avoid opening positions during abnormal volatility periods, effectively reducing false signals and risk exposure.
Visual Monitoring: Built-in intuitive visual dashboard displaying the currently active mode and number of open grids, facilitating real-time monitoring of strategy status.
Flexible Parameter Customization: The strategy offers rich parameter setting options, including grid spacing, maximum grid layers, ATR multiplier, take-profit targets, etc., allowing traders to optimize according to personal risk preferences and trading objectives.
Alert System Integration: Built-in human-readable and JSON format alert systems, supporting seamless integration with external automation systems and notification platforms.
Strategy Risks
Mode Switching Timing Risk: At market state transition points, the strategy may delay in identifying the new state, leading to temporary strategy mismatch. Solution: Add transition buffer periods or introduce machine learning algorithms to improve state identification accuracy.
Grid Accumulation Risk: In EVE mode, if the market moves in one direction for an extended period, multiple grid positions may accumulate, increasing capital usage and potential losses. Solution: Set grid quantity limits and implement automatic position closing mechanisms under extreme conditions.
Parameter Sensitivity: Multi-modal strategies are sensitive to parameter settings; inappropriate parameters may lead to overtrading or missed opportunities. Solution: Optimize parameters for different market environments through backtesting or implement adaptive parameter adjustment mechanisms.
Trailing Stop Risk: In highly volatile markets, trailing stops may be triggered by small fluctuations, causing premature exit from favorable trends. Solution: Dynamically adjust trailing stop trigger and offset parameters based on volatility.
Technical Indicator Lag: The EMA and MACD indicators the strategy relies on have inherent lag, potentially causing delayed reactions in rapidly changing markets. Solution: Integrate faster-responding indicators, such as price action patterns or Tick data-based indicators.
Systemic Risk Exposure: Under extreme market conditions, all modes may simultaneously fail, leading to systemic risk exposure. Solution: Implement global risk control switches to automatically reduce positions or pause trading under extreme market conditions.
Strategy Optimization Directions
Machine Learning Enhancement:
The current strategy uses fixed rules to identify market states. Machine learning algorithms, particularly supervised learning or reinforcement learning models, could be introduced to improve market state classification accuracy. This would enable more precise mode switching and trade execution, reducing false signals and unnecessary trades.Dynamic Parameter Adjustment:
Link key parameters such as grid spacing, ATR multiplier, and trailing stop settings to market volatility for dynamic adaptation. For example, automatically widen grid spacing in high-volatility environments and narrow it in low-volatility environments to adapt to different market conditions.Multi-timeframe Analysis:
Add multi-timeframe analysis functionality to allow the strategy to consider market structures at different time levels simultaneously, avoiding trading signals on smaller timeframes that contradict larger timeframe trends, thereby improving trade success rates.Capital Management Optimization:
The current strategy uses fixed proportion capital management. This could be improved to a dynamic capital management system based on volatility and win rates, increasing position size on high-confidence signals and reducing it on low-confidence signals to optimize capital efficiency.Sentiment Indicator Integration:
Consider integrating market sentiment indicators such as VIX, futures premium, fund flows, etc., as auxiliary factors for mode selection, enhancing the strategy's ability to perceive market sentiment changes, especially at major market turning points.Fundamental Triggers:
Introduce fundamental trigger mechanisms to allow the strategy to adjust sensitivity or temporarily switch modes before and after important economic data releases or corporate events, avoiding damage from violent fluctuations caused by significant fundamental events.Performance Optimization:
Optimize code performance, especially the loops and conditional judgments in the grid trading section, to reduce computational resource usage and improve strategy execution efficiency in high-frequency environments.
Summary
The Multi-Modal Adaptive Grid Trailing Strategy is a comprehensive quantitative trading system that combines multiple trading techniques and concepts. By intelligently identifying market states and automatically switching trading modes, it achieves adaptability to different market environments. Its four core trading modes (Lucifer, Reaper, Sentinel, and EVE) are designed for breakout, reversal, trend, and range markets respectively, complementing each other to form a complete trading system.
The most significant feature of this strategy is its adaptability and comprehensiveness. By integrating technical indicators such as EMA, MACD, and ATR, it builds an intelligent system capable of automatically adjusting strategy to adapt to changing market environments. Meanwhile, multi-layered risk management mechanisms and flexible parameter settings give it both the ability to capture market opportunities and effectively control risk exposure.
However, like any strategy, there is room for optimization. By introducing machine learning enhancements, dynamic parameter adjustments, multi-timeframe analysis, and more advanced capital management techniques, this strategy has the potential to further improve its stability and profitability. For traders seeking an all-in-one quantitative trading solution, this strategy provides a balanced, comprehensive, and intelligent trading framework suitable for long-term application across various market environments.
Strategy source code
/*backtest
start: 2024-06-03 00:00:00
end: 2025-06-02 00:00:00
period: 4h
basePeriod: 4h
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 = input.bool(true, "Use Stop Loss")
useTP = input.bool(true, "Use Take Profit")
useTrail = input.bool(true, "Use Trailing Stop")
trailTrigger = input.float(1.5, "Trail Trigger (%)") / 100
trailOffset = input.float(0.75, "Trail Offset (%)") / 100
manualMode = input.string("AUTO", title="Mode", options=["AUTO", "EVE", "LUCIFER", "REAPER", "SENTINEL"])
gridSpacing = input.float(0.015, "Grid Spacing")
maxLayers = input.int(4, "Max Grid Layers")
atrMultSL = input.float(1.5, "SL ATR Multiplier")
tpTarget = input.float(0.015, "TP Target (%)")
// === 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
activeMode := isRanging ? "EVE" :
isReversing ? "REAPER" :
isTrending ? "SENTINEL" :
isBreakout ? "LUCIFER" : "None"
// === GRID BASE PRICE (EVE) ===
var float basePrice = na
if na(basePrice) or activeMode != "EVE"
basePrice := close
var int openTrades = 0
openTrades := 0
// === TRAILING STOP FUNCTION ===
f_trailStop(side, id) =>
if useTrail
trigger = close * trailTrigger
offset = close * trailOffset
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)
// === EVE GRID MODE ===
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
// === 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")
// === VISUAL DASHBOARD ===
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, size=size.normal)
// === ALERTS – HUMAN
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 BOT FORMAT
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}}"}')
// === VISUALS
plot(ema50, title="EMA 50", color=color.gray)
Strategy parameters
The original address: Multi-Modal Adaptive Grid Trailing Strategy: Intelligent Trading System Integrating EMA, MACD and ATR
Great work! This strategy does a solid job combining EMA, MACD, and adaptive grid logic. I especially like how it adjusts dynamically based on market conditions — feels both practical and well thought out. Looking forward to seeing more like this!