Optimized Zhaocaijinbao strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fzj20020403

////@version=5
//@version=5
strategy("Optimized Zhaocaijinbao", overlay=true, margin_long=100, margin_short=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Define two moving averages
ma6 = ta.sma(close, 6)
ma35 = ta.sma(close, 35)

// Define buy and sell signal lines
buyLine = ta.ema(close, 2)
sellSlope = (close - close[8]) / 8
sellLine = sellSlope * 1 + ta.sma(close, 8)

// Define volume indicator
volumeEMA = ta.ema(volume, 20)

// Define weekly slope factor
weeklyMa = ta.sma(close, 50)
weeklySlope = (weeklyMa - weeklyMa[4]) / 4 > 0

// Generate buy and sell signals
buySignal = ta.crossover(buyLine, sellLine) and close > ma35 and volume > volumeEMA and weeklySlope
sellSignal = ta.crossunder(sellLine, buyLine)

// Define dynamic position sizing factor
equity = strategy.equity
maxPositionSize = equity * input.float(title='Max Position Size (%)', defval=0.01, minval=0.001, maxval=0.5, step=0.001)
riskFactor = input.float(title='Risk Factor', defval=2.0, minval=0.1, maxval=10.0, step=0.1)
atr = ta.atr(14)
positionSize = maxPositionSize * riskFactor / atr

// Define position status
var inPosition = false

// Define buy and sell conditions
buyCondition = buySignal and not inPosition
sellCondition = sellSignal and inPosition

// Perform buy and sell operations
if (buyCondition)
    strategy.entry("Long", strategy.long, qty=positionSize)
    inPosition := true
if (sellCondition)
    strategy.close("Long")
    inPosition := false

// Draw vertical line markers for buy and sell signals
plotshape(buyCondition, style=shape.arrowdown, location=location.belowbar, color=color.green, size=size.small)
plotshape(sellCondition, style=shape.arrowup, location=location.abovebar, color=color.red, size=size.small)

// Draw two moving averages
plot(ma6, color=color.blue)
plot(ma35, color=color.orange)

// Draw volume indicator line
plot(volumeEMA, color=color.yellow)

// Define stop loss and take profit
stopLoss = strategy.position_avg_price * 0.5
takeProfit = strategy.position_avg_price * 1.25

if inPosition
    strategy.exit("Long Stop Loss", "Long", stop=stopLoss)
    strategy.exit("Long Take Profit", "Long", limit=takeProfit)

