//@version=5 strategy("Cross-Exchange Statistical Arbitrage Strategy", overlay=false, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100) // Inputs secondarySymbol = input.symbol("BINANCE:BTCUSDT", "Secondary Reference Symbol") lookback = input.int(20, "Lookback Period for Z-Score", minval=5) threshold = input.float(2.0, "Z-Score Entry Threshold", minval=0.5, step=0.1) exitThreshold = input.float(0.0, "Z-Score Exit Threshold", step=0.1) // Fetch secondary asset close price pricePrimary = close priceSecondary = request.security(secondarySymbol, timeframe.period, close) // Calculate Spread & Z-Score spread = pricePrimary - priceSecondary spreadSMA = ta.sma(spread, lookback) spreadStd = ta.stdev(spread, lookback) zScore = spreadStd != 0.0 ? (spread - spreadSMA) / spreadStd : 0.0 // Plots plot(zScore, "Spread Z-Score", color=color.blue) hline(threshold, "Upper Threshold", color=color.red, linestyle=hline.style_dashed) hline(-threshold, "Lower Threshold", color=color.green, linestyle=hline.style_dashed) hline(exitThreshold, "Mean Reversion Level", color=color.gray, linestyle=hline.style_dotted) // Trading Conditions longCondition = ta.crossover(zScore, -threshold) shortCondition = ta.crossunder(zScore, threshold) exitLongCondition = zScore >= exitThreshold exitShortCondition = zScore <= exitThreshold // Strategy Execution if (longCondition) strategy.entry("Arb_Long", strategy.long) if (shortCondition) strategy.entry("Arb_Short", strategy.short) if (strategy.position_size > 0 and exitLongCondition) strategy.close("Arb_Long") if (strategy.position_size < 0 and exitShortCondition) strategy.close("Arb_Short")