Strategies KB.ZH
Strategies

双均线动态趋势跟踪与智能风控策略-Dynamic-Dual-SMA-Trend-Following-Strategy-with-Smart-Risk-Management

ChaoZhang · PineScript · Risk and Position Sizing · 2024-11-29 11:06:38

All strategies →
Trigger
Sizing
—

No English write-up in the source (no author description).

Read the Chinese version →

Source code (61 lines)
/*backtest
start: 2019-12-23 08:00:00
end: 2024-11-27 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("SMA Buy/Sell Strategy with Significant Slope", overlay=true)

// Parametri configurabili
smaPeriod = input.int(20, title="SMA Period", minval=1)
initialTPPercent = input.float(5.0, title="Initial Take Profit (%)", minval=0.1)  // Take Profit iniziale (ambizioso)
trailingSLPercent = input.float(1.0, title="Trailing Stop Loss (%)", minval=0.1) // Percentuale di trailing SL
slopeThreshold = input.float(0.05, title="Slope Threshold (%)", minval=0.01)    // Soglia minima di pendenza significativa

// SMA calcolate su HIGH e LOW
smaHigh = ta.sma(high, smaPeriod)
smaLow = ta.sma(low, smaPeriod)

// Funzioni per pendenza significativa
isSignificantSlope(sma, threshold) =>
    math.abs(sma - sma[5]) / sma[5] > threshold / 100

slopePositive(sma) =>
    sma > sma[1] and isSignificantSlope(sma, slopeThreshold)

slopeNegative(sma) =>
    sma < sma[1] and isSignificantSlope(sma, slopeThreshold)

// Condizioni di BUY e SELL
buyCondition = close > smaHigh and low < smaHigh and close[1] < smaHigh and slopePositive(smaHigh)
sellCondition = close < smaLow and high > smaLow and close[1] > smaLow and slopeNegative(smaLow)

// Plot delle SMA
plot(smaHigh, color=color.green, linewidth=2, title="SMA 20 High")
plot(smaLow, color=color.red, linewidth=2, title="SMA 20 Low")

// Gestione TP/SL dinamici
longInitialTP = strategy.position_avg_price * (1 + initialTPPercent / 100)
shortInitialTP = strategy.position_avg_price * (1 - initialTPPercent / 100)

// Trailing SL dinamico
longTrailingSL = close * (1 - trailingSLPercent / 100)
shortTrailingSL = close * (1 + trailingSLPercent / 100)

// Chiusura di posizioni attive su segnali opposti
if strategy.position_size > 0 and sellCondition
    strategy.close("Buy", comment="Close Long on Sell Signal")
if strategy.position_size < 0 and buyCondition
    strategy.close("Sell", comment="Close Short on Buy Signal")

// Apertura di nuove posizioni con TP iniziale e Trailing SL
if buyCondition
    strategy.entry("Buy", strategy.long, comment="Open Long")
    strategy.exit("Long TP/Trailing SL", from_entry="Buy", limit=longInitialTP, stop=longTrailingSL)

if sellCondition
    strategy.entry("Sell", strategy.short, comment="Open Short")
    strategy.exit("Short TP/Trailing SL", from_entry="Sell", limit=shortInitialTP, stop=shortTrailingSL)