Strategies KB.ZH
Strategies

基于双均线和交易量的趋势突破交易策略-Trend-Breakout-Trading-Strategy-Based-on-Dual-Moving-Averages-and-Volume

ChaoZhang · PineScript · Trend Following · 2025-02-18 13:38:51

All strategies →

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

Read the Chinese version →

Source code (61 lines)
/*backtest
start: 2024-02-18 00:00:00
end: 2025-02-17 00:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("MA Crossover with Volume (Long Only) + Stop Loss", overlay=true)

// Input settings for Moving Averages
shortMaLength = input.int(9, title="Short MA Length", minval=1)
longMaLength = input.int(21, title="Long MA Length", minval=1)

// Input settings for Volume
volumeMaLength = input.int(20, title="Volume MA Length", minval=1)
volumeThresholdMultiplier = input.float(1.5, title="Volume Multiplier (x times the average)", step=0.1)

// Input settings for Stop Loss
stopLossPercent = input.float(2.0, title="Stop Loss (%)", minval=0.1, step=0.1) / 100  // Stop loss in percentage

// Calculating Moving Averages
shortMa = ta.sma(close, shortMaLength)
longMa = ta.sma(close, longMaLength)

// Calculating Volume Metrics
volumeMa = ta.sma(volume, volumeMaLength)  // Average volume
isVolumeAboveAverage = volume > (volumeMa * volumeThresholdMultiplier)  // Volume above threshold
isVolumeIncreasing = volume > volume[1]  // Volume increasing compared to the previous bar

// Plotting Moving Averages
plot(shortMa, color=color.blue, title="Short MA")
plot(longMa, color=color.orange, title="Long MA")

// Buy Condition with Volume
longCondition = ta.crossover(shortMa, longMa) and isVolumeAboveAverage and isVolumeIncreasing
exitCondition = ta.crossunder(shortMa, longMa)  // Exit when the MAs cross downward

// Calculate Stop Loss Level
var float entryPrice = na  // Variable to store entry price
if (strategy.position_size > 0 and na(entryPrice))  // Update entry price only when entering a new trade
    entryPrice := strategy.position_avg_price

stopLossLevel = entryPrice * (1 - stopLossPercent)  // Stop-loss level based on entry price

// Strategy Entry (Long Only)
if (longCondition)
    strategy.entry("Long", strategy.long)

// Close position on Stop Loss or Exit Condition
if (strategy.position_size > 0)
    if (low < stopLossLevel)  // If the price drops below the stop-loss level
        strategy.close("Long", comment="Stop Loss Hit")

if (exitCondition)
    strategy.close("Long", comment="Exit Signal Hit")

// Debugging Plots
plot(volumeMa, color=color.purple, title="Volume MA", style=plot.style_area, transp=80)
hline(0, "Zero Line", color=color.gray)