Example output
Here is a Pine Script implementation of the requested adaptive trading strategy for TradingView. The script dynamically switches between a trend-following and a mean-reversion strategy based on ATR thresholds, with all the requested features included.
```pinescript
//@version=5
strategy("Adaptive Hybrid Strategy: Trend-Following & Mean-Reversion", overlay=true, shorttitle="Hybrid Strategy", default_qty_type=strategy.percent_of_equity, default_qty_value=1)
// Inputs
atrLength = input.int(14, title="ATR Length")
atrThreshold = input.float(2.0, title="ATR Threshold", tooltip="Threshold to switch between Trend-Following and Mean-Reversion modes")
maFastLength = input.int(9, title="Trend MA Fast Length")
maSlowLength = input.int(21, title="Trend MA Slow Length")
bollingerLength = input.int(20, title="Bollinger Band Length")
bollingerMult = input.float(2.0, title="Bollinger Band Multiplier")
stopLossPct = input.float(1.0, title="Stop Loss (%)")
takeProfitPct = input.float(2.0, title="Take Profit (%)")
enableAlerts = input.bool(true, title="Enable Alerts")
// Calculate Indicators
atr = ta.atr(atrLength)
maFast = ta.sma(close, maFastLength)
maSlow = ta.sma(close, maSlowLength)
[bbUpper, bbLower] = ta.bb(close, bollingerLength, bollingerMult)
// Determine Strategy Mode
strategyMode = atr > atrThreshold ? "Trend-Following" : "Mean-Reversion"
// Dynamic Chart Annotations
var label modeLabel = na
if (na(modeLabel) or barstate.isnew)
label.delete(modeLabel)
modeLabel := label.new(x=bar_index, y=high, text=strategyMode, style=label.style_label_down, color=color.new(color.blue, 80))
// Logic for Trend-Following Strategy
longTrend = ta.crossover(maFast, maSlow)
shortTrend = ta.crossunder(maFast, maSlow)
// Logic for Mean-Reversion Strategy
longRevert = close < bbLower
shortRevert = close > bbUpper
// Execute Trades Based on Current Mode
if (strategyMode == "Trend-Following")
if (longTrend)
strategy.entry("Long Trend", strategy.long)
if (shortTrend)
strategy.entry("Short Trend", strategy.short)
else if (strategyMode == "Mean-Reversion")
if (longRevert)
strategy.entry("Long Revert", strategy.long)
if (shortRevert)
strategy.entry("Short Revert", strategy.short)
// Set Stop Loss and Take Profit
if (strategy.position_size > 0)
strategy.exit("Take Profit/Stop Loss", from_entry="Long Trend",
profit=takeProfitPct * strategy.position_avg_price / 100,
loss=stopLossPct * strategy.position_avg_price / 100)
if (strategy.position_size < 0)
strategy.exit("Take Profit/Stop Loss", from_entry="Short Trend",
profit=takeProfitPct * math.abs(strategy.position_avg_price) / 100,
loss=stopLossPct * math.abs(strategy.position_avg_price) / 100)
// Alerts
if (enableAlerts)
if (barstate.isnew and strategyMode == "Trend-Following")
alert("Switched to Trend-Following Mode", alert.freq_once_per_bar)
if (barstate.isnew and strategyMode == "Mean-Reversion")
alert("Switched to Mean-Reversion Mode", alert.freq_once_per_bar)
if (strategy.opentrades > 0)
alert("Trade Executed: " + str.tostring(strategy.opentrades), alert.freq_once_per_bar)
// Backtesting Annotations
plotshape(series=longTrend, style=shape.labelup, location=location.belowbar, color=color.green, size=size.small, title="Long Entry - Trend")
plotshape(series=shortTrend, style=shape.labeldown, location=location.abovebar, color=color.red, size=size.small, title="Short Entry - Trend")
plotshape(series=longRevert, style=shape.labelup, location=location.belowbar, color=color.blue, size=size.small, title="Long Entry - Revert")
plotshape(series=shortRevert, style=shape.labeldown, location=location.abovebar, color=color.orange, size=size.small, title="Short Entry - Revert")
```
### Explanation of Key Features:
1. **Hybrid Strategy Logic**:
- Uses ATR to switch between two modes: `Trend-Following` (when ATR is high) and `Mean-Reversion` (when ATR is low).
- Trend-Following logic is based on Moving Average (MA) crossovers.
- Mean-Reversion logic is based on Bollinger Band bounces.
2. **Dynamic Annotations**:
- Displays the active strategy mode (`Trend-Following` or `Mean-Reversion`) on the chart.
3. **Trade Management**:
- Configurable stop-loss and take-profit levels adjust dynamically based on the active strategy.
4. **Alerts**:
- Alerts notify users when the mode changes or trades are executed.
5. **Backtesting Features**:
- Trade signals are visually marked on the chart for analysis.
- Backtesting uses built-in `strategy` functions for accurate performance evaluation.
6. **Modular and Well-Commented**:
- Code is organized into modular sections with clear comments for each part of the strategy.
Feel free to test and refine this script in TradingView! Let me know if you need any additional customizations or optimizations.