//@version=5
strategy(
     title="PIOLINK Composite Strategy (2H)", 
     shorttitle="PIOLINK Comp Strat", 
     overlay=true, 
     pyramiding=0, // 한 방향으로 하나의 포지션만 허용
     initial_capital=10000000, // 예시 초기 자본 (1천만원)
     default_qty_type=strategy.cash, // 주문 수량 대신 금액 기준으로
     default_qty_value=1000000, // 기본 주문 금액 (1백만원) - 아래에서 리스크 기반으로 재계산됨
     commission_type=strategy.commission.percent, 
     commission_value=0.075, // 한국 주식 수수료 예시 (증권사마다 다름)
     slippage=2 // KOSDAQ 변동성 고려한 슬리피지 (틱 단위)
)

// ─── Inputs ─────────────────────────────────────────────────────────────────
// Supertrend
st_atrPeriod = input.int(10, title="Supertrend ATR Period")
st_factor = input.float(2.0, title="Supertrend Factor")

// Bollinger Bands
bb_length = input.int(20, title="Bollinger Bands Length")
bb_mult = input.float(2.0, title="Bollinger Bands StdDev")

// Volume Filter
vol_maLength = input.int(20, title="Volume MA Length")

// Risk Management (ATR based)
atr_period_risk = input.int(10, title="ATR Period for SL/TP", tooltip="Supertrend ATR과 동일하게 설정하거나 별도 설정")
atr_stop_multiplier = input.float(1.0, title="ATR Stop Loss Multiplier")
atr_profit_multiplier = input.float(1.0, title="ATR Take Profit Multiplier")

// Position Sizing
account_risk_percent = input.float(0.4, title="Account Risk % per Trade", minval=0.1, maxval=5.0, step=0.1)

// ─── Indicator Calculations ───────────────────────────────────────────────
// Supertrend
[supertrend, direction] = ta.supertrend(st_factor, st_atrPeriod)
isSupertrendUp = direction < 0 // Supertrend가 상승 추세 (초록색)
isSupertrendDown = direction > 0 // Supertrend가 하락 추세 (빨간색)

// Bollinger Bands
bb_basis = ta.sma(close, bb_length)
bb_dev = bb_mult * ta.stdev(close, bb_length)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev

// Volume MA
vol_sma = ta.sma(volume, vol_maLength)

// ATR for Risk
atr_value = ta.atr(atr_period_risk)

// ─── Entry Conditions ─────────────────────────────────────────────────────
// Volume Gate
volumeGate = volume > vol_sma

// Long Conditions
long_breakout_current = close > bb_upper
long_breakout_previous = close[1] > bb_upper[1]
long_two_bar_confirm = long_breakout_current and long_breakout_previous

long_entry_condition = isSupertrendUp and long_two_bar_confirm and volumeGate and strategy.opentrades == 0

// Short Conditions
short_breakout_current = close < bb_lower
short_breakout_previous = close[1] < bb_lower[1]
short_two_bar_confirm = short_breakout_current and short_breakout_previous

short_entry_condition = isSupertrendDown and short_two_bar_confirm and volumeGate and strategy.opentrades == 0

// ─── Position Sizing Calculation ──────────────────────────────────────────
var float stop_loss_points = na // Declare with var to retain value across bars if needed for calculation logic
stop_loss_points := atr_value * atr_stop_multiplier // Assign using := for reassignable variables

var float risk_per_share = na
risk_per_share := stop_loss_points

var float account_risk_amount = na
account_risk_amount := (strategy.equity * account_risk_percent) / 100

var int position_size = na // position_size must be int
position_size := risk_per_share > 0 and not na(risk_per_share) ? math.floor(account_risk_amount / risk_per_share) : 0

// ─── Strategy Execution ───────────────────────────────────────────────────
// Long Entry
if (long_entry_condition and position_size > 0) // Check position_size directly
    strategy.entry("Long", strategy.long, qty=position_size) 

// Short Entry
if (short_entry_condition and position_size > 0) // Check position_size directly
    strategy.entry("Short", strategy.short, qty=position_size)

// ─── Stop Loss & Take Profit ──────────────────────────────────────────────
// For Long
if (strategy.position_size > 0)
    long_stop_price = strategy.position_avg_price - stop_loss_points
    long_profit_price = strategy.position_avg_price + (atr_value * atr_profit_multiplier)
    strategy.exit("Long SL/TP", from_entry="Long", stop=long_stop_price, limit=long_profit_price)

// For Short
if (strategy.position_size < 0)
    short_stop_price = strategy.position_avg_price + stop_loss_points
    short_profit_price = strategy.position_avg_price - (atr_value * atr_profit_multiplier)
    strategy.exit("Short SL/TP", from_entry="Short", stop=short_stop_price, limit=short_profit_price)

// ─── Plotting (Visual Confirmation) ───────────────────────────────────────
plot(bb_upper, "Upper BB", color=color.new(color.blue, 0))
plot(bb_lower, "Lower BB", color=color.new(color.blue, 0))
plot(bb_basis, "BB Basis", color=color.new(color.orange, 50))

// Supertrend (방향에 따라 색상 변경)
plot(supertrend, "Supertrend", color=isSupertrendUp ? color.green : color.red, linewidth=2)

// Entry signals on chart
plotshape(long_entry_condition, title="Long Signal", location=location.belowbar, color=color.new(color.green, 0), style=shape.triangleup, size=size.normal)
plotshape(short_entry_condition, title="Short Signal", location=location.abovebar, color=color.new(color.red, 0), style=shape.triangledown, size=size.normal)

// ─── Alerts ───────────────────────────────────────────────────────────────
alertcondition(long_entry_condition, title="PIOLINK Long Alert", message="PIOLINK ({{ticker}}) Long Signal @ {{close}}. Supertrend Green, BB Breakout (2-bar), Vol>SMA.")
alertcondition(short_entry_condition, title="PIOLINK Short Alert", message="PIOLINK ({{ticker}}) Short Signal @ {{close}}. Supertrend Red, BB Breakout (2-bar), Vol>SMA.")
---
Error at 2:446 Mismatched input 'end of line without line continuation' expecting ')'