
다중 시간 프레임 제로 지연 트렌드 신호 거래 전략은 전통적인 이동 평균의 지연을 줄이고 더 빠른 정확한 트렌드 식별 신호를 제공하기 위해 만들어진 제로 지연 지수 이동 평균 ((ZLEMA) 에 기반한 정량 거래 시스템입니다. 이 전략은 트렌드 변화를 식별하기 위해 변동성 통로를 결합하는 것뿐만 아니라 위험 회귀, 출장 수익 목표 출장, ATR 기반의 중지 및 중지 손실, 동적 추적 중지 손실 및 모든 라인을 통과하는 등 다양한 유연한 출구 메커니즘을 통합합니다. 중장기 거래에 특히 적합합니다. 전략은 단독 또는 양방향 거래를 위해 구성 할 수 있으며, 제로 라인 재출장 옵션을 제공하여 거래 시스템의 적응력과 위험 관리 능력을 크게 향상시킵니다.
이 전략의 핵심 원칙은 0 지연 지수 이동 평균 ((ZLEMA) 에 기반을 두고 있으며, 이는 가격 데이터 지연을 제거하거나 줄임으로써 이동 평균의 반응 속도를 향상시키는 기술 지표이다. 구체적으로 구현하는 단계는 다음과 같다:
제로 지연 계산전략: 먼저 ZLEMA를 계산합니다.zlema = ta.ema(src + (src - src[lag]), length)그 중 하나는lag길이의 절반을 기반으로 계산된 것으로, 이 방법은 전통적인 EMA에서의 지연을 효과적으로 줄여준다.
트렌드 식별 메커니즘:
zlemaUpTrend그리고zlemaDownTrend변수 구현다양한 입학 조건:
통합 동적 출전 시스템:
다중 시간 프레임의 제로 지연 경향 신호 거래 전략은 상당한 장점이 있습니다:
신호 지연을 줄인다: ZLEMA 기술을 통해, 전통적인 이동 평균의 지연을 줄이고, 트렌드 식별을 더 일찍 가능하게 하고, 트렌드 시작점을 더 일찍 잡을 수 있다.
포괄적 인 위험 관리 시스템여러 계층의 위험 제어 장치를 통합하여 고정 중지, ATR 동적 중지, 추적 중지에서 손해 균형 중지까지 다양한 시장 환경에 대한 완벽한 보호를 제공합니다.
유연한 거래방향 선택다중 전략 또는 양방향 거래 전략으로 구성할 수 있으며, 다양한 시장 선호와 규제 환경에 적합합니다.
재입학제도: ZLEMA 제로 라인 재입장 기능을 통해, 강한 트렌드에서 단기 회귀 후 재입장을 허용하여 트렌드 수익을 극대화한다.
다원화 탈퇴 전략: 다양한 시장 상황에 맞게 여러 가지 탈퇴 옵션을 제공하여 수익 목표를 통해 수익을 고정시킬 수 있으며, 스톱 손실을 추적하여 수익을 달릴 수 있습니다.
시각적 도움말: 트렌드 그림자, 스톱로스 라인, 스톱 라인 및 트렌드 표시기 등의 시각적 요소를 통해 거래 신호와 위험 관리 위치를 직관적으로 표시한다.
상세한 성과 통계: 통합 거래 통계 표, 승률, 순이익, 최대 인출과 같은 주요 지표를 표시하여 전략을 평가하고 최적화 할 수 있습니다.
이 전략은 합리적으로 설계되었지만, 몇 가지 잠재적인 위험은 여전히 주의해야 합니다.
매개변수 민감도: ZLEMA 길이와 ATR 곱하기 등 핵심 매개 변수가 전략 성능에 중요한 영향을 미치며, 부적절한 설정으로 신호가 너무 많거나 너무 적을 수 있다.
시장의 위조 신호: 명확한 추세가 없는 불안정한 시장에서, 빈번한 잘못된 신호가 발생하여 연속적인 손실이 발생할 수 있다.
추세 반전 위험이 전략은 여러 가지 탈퇴 메커니즘을 설계했지만, 급격한 추세 전환으로 인해 탈퇴하기 전에 큰 손실을 입을 수 있습니다.
과도한 적합성의 위험: 여러 변수들의 조합은 역사적 데이터에 대한 과도한 적합성을 초래할 수 있으며, 미래 시장 환경에서는 좋지 않은 성능을 나타낼 수 있다.
긴 주기 신호는 드물다.: 더 긴 ZLEMA 길이를 사용할 때, 전략은 거래 신호를 적게 생성하여 자금 사용 효율성에 영향을 미칠 수 있습니다.
폭을 막는 도전ATR 기반의 정지는 높은 변동성 시장에서 너무 넓어져 단일 손실이 너무 커질 수 있으며, 낮은 변동성 시장에서는 너무 좁아져 자주 유발 될 수 있습니다.
이러한 위험을 완화하기 위한 방법은: 엄격한 변수 회수와 전향 검증, 시장 상태 지표와 결합한 불안한 시장에서 거래를 피하는, 엄격한 자금 관리 규칙을 적용하는, 시장 변화에 적응하기 위해 전략 변수를 정기적으로 재 최적화하는 등이다.
이 전략에는 다음과 같은 방향으로 더 많은 최적화 공간이 있습니다.
동적 변수는 스스로 적응합니다.시장의 변동성에 따라 ZLEMA의 길이를 자동으로 조정하고 ATR의 배수를 자동으로 조정하는 자율 적응 메커니즘을 개발하여 다양한 시장 환경에 대한 전략의 적응성을 향상시킵니다.
시장 상태 필터: 시장 상태 지표 (ADX, 변동성 지표와 같은) 를 도입하고, 유리한 시장 조건에서만 거래하고, 비효율적 인 흔들리는 시장에서 자주 거래하는 것을 피하십시오.
다중 시간 프레임 확인더 높은 시간 프레임의 트렌드 방향과 결합하여, 큰 트렌드 방향이 일치하는 경우에만 참가하여 성공률을 높여라.
거래량 확인: 거래량 지표를 통합하여 보조 확인으로, 예를 들어 거래량이 증가했을 때만 트렌드 변화 신호를 확인한다.
기계 학습 최적화: 기계 학습 알고리즘을 사용하여 최적의 변수 조합과 진입 시기를 찾고, 특히 어떤 신호가 더 성공할 수 있는지 예측하는 모델을 훈련 할 수 있습니다.
계절과 시간 필터: 거래 시간 및 달력 필터를 추가하여 효율적이지 않거나 위험성이 높은 거래 시간을 피하십시오.
관련 자산 연관 분석: 관련 자산의 연관성 분석을 도입하여, 여러 자산 동향 확인 시 신호 신뢰성을 강화한다.
이러한 최적화 방향은 전략의 안정성과 수익성을 높일 뿐만 아니라 위험을 줄여서 다양한 시장 환경과 개인 위험 선호도에 더 적합하게 만듭니다.
다중 시간 프레임 제로 지연 트렌드 신호 거래 전략은 제로 지연 지수 이동 평균 (ZLEMA) 기술과 변동성 통로를 통해 신속하고 정확한 트렌드 식별을 가능하게 하는 포괄적이고 유연한 정량 거래 시스템이며, 다층의 동적 위험 관리 장치와 결합하여 자금 안전을 보호한다. 이 전략은 트렌드의 초기 입문 기회를 포착할 수 있고, 트렌드 개발에 있어서 재입문 메커니즘을 통해 수익을 극대화할 수 있으며, 동시에 다양한 시장 환경에 적응한 탈퇴 전략을 제공합니다.
전략의 주요 장점은 신호 지연을 줄이고, 포괄적 인 위험 관리 시스템과 유연한 거래 구성 옵션을 제공하는 것입니다. 그러나 사용자는 파라미터 민감성, 변동 시장의 가짜 신호 및 과도한 조화와 같은 잠재적인 위험에 주의해야합니다. 시장 상태 필터링, 다중 시간 프레임 확인 및 동적 파라미터 자조와 같은 최적화 방향을 통해 전략 성능을 더욱 향상시킬 수 있습니다.
기술 지표에 기반한 양적 거래 시스템으로서, 이 전략은 특히 중기 및 장기적인 트렌드 거래에 적합하며, 다양한 금융 시장에 적용된다. 그러나, 모든 전략은 개인의 거래 목표, 위험 용인 능력 및 시장 선호에 따라 개인화 조정이 필요하며, 엄격한 자금 관리 원칙과 결합하여 실제 거래에 적용된다.
//@version=6
// Quant Trading Pro www.quanttradingpro.com
// #1 Strategy Optimizer on the chrome extension store Quant Trading Strategy Optimizer
strategy(title="Quant Trading Zero Lag Trend Signals (MTF) Strategy", shorttitle="QT0️⃣Zero Lag Signals Strategy", overlay=true,
commission_type=strategy.commission.percent,
commission_value=0.1,
slippage=3,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100,
initial_capital=1000,
margin_long=0,
margin_short=0)
// === INPUT PARAMETERS ===
// 📌 1️⃣ Main Calculations
length = input.int(70, title="Length", minval=70, maxval=7000)
mult = input.float(1.2, "Band Multiplier", group="Main Calculations")
// === 📊 Trade Data Toggles ===
showFloatingTable = input.bool(true, "Show Floating Stats Table?", group="Trade Data")
showTradeLog = input.bool(false, "Show Trade Log Labels on Chart?", group="Trade Data")
enableCSVExport = input.bool(false, "Enable CSV Export", group="Trade Data")
// 📌 ZLEMA Trend Confirmation for Entries
useZlemaTrendConfirm = input.bool(false, "Use ZLEMA Trend Confirmation for entry?", group="Entry Conditions")
reEnterOnLongTrend = input.bool(false, "Re-Enter on Long Trend continuation", group="Entry Conditions")
// 📌 2️⃣ Short Trades
allowShortTrades = input.bool(false, "Allow Short Trades?", group="Short Trades")
// 📌 Performance Settings
useProfitTarget = input.bool(false, "Use Profit Target?", group="Performance Settings")
profitTargetRR = input.float(2.0, "Profit Target (Risk-Reward Ratio)", group="Performance Settings")
// 📌 4️⃣ Dynamic TP/SL (Each Setting with Its Parameters Directly Below)
useATRStopTP = input.bool(false, "Use ATR-Based Stop-Loss & Take-Profit?", group="Dynamic TP/SL")
atrLength = input.int(14, "ATR Length", group="Dynamic TP/SL")
atrMultiplier = input.float(1.5, "Stop-Loss ATR Multiplier", group="Dynamic TP/SL")
profitATRMultiplier = input.float(2.5, "Profit Target ATR Multiplier", group="Dynamic TP/SL")
useTrailingStop = input.bool(false, "Use ATR Trailing Stop?", group="Dynamic TP/SL")
trailStopMultiplier = input.float(1.5, "Trailing Stop ATR Multiplier", group="Dynamic TP/SL")
useBreakEven = input.bool(false, "Use Break-Even Stop-Loss?", group="Dynamic TP/SL")
breakEvenRR = input.float(1.5, "Move SL to Break-Even After RR", group="Dynamic TP/SL")
useTrendExit = input.bool(false, "Use Trend-Based Take Profit (EMA Exit)?", group="Dynamic TP/SL")
emaExitLength = input.int(9, "EMA Exit Length", group="Dynamic TP/SL")
// 📌 Debug Options
showZlemaDebug = input.bool(false, "Show ZLEMA Trend Debug?", group="Debug")
// ============================================================
// === 1️⃣ CALCULATIONS (Indicators, Trend, ATR, Stop/TP) ===
// ============================================================
src = close
lag = math.floor((length - 1) / 2)
zlema = ta.ema(src + (src - src[lag]), length)
volatility = ta.highest(ta.atr(length), length * 3) * mult
var trend = 0
if ta.crossover(close, zlema + volatility)
trend := 1
if ta.crossunder(close, zlema - volatility)
trend := -1
atrValue = ta.atr(atrLength)
emaExit = ta.ema(close, emaExitLength)
var float stopLossLongLevel = na
var float profitTargetLongLevel = na
var float stopLossShortLevel = na
var float profitTargetShortLevel = na
var int lastEntryBarIndex = na
var float lastEntryPrice = na
// ✅ Corrected ZLEMA DownTrend Logic: Ensure ZLEMA has decreased for 5 consecutive bars
// ✅ ZLEMA Increasing for 5 Bars → Bullish Trend (Green Triangle Up at the Bottom)
zlemaUpTrend = zlema > zlema[1] and zlema[1] > zlema[2] and zlema[2] > zlema[3] and zlema[3] > zlema[4]
// ✅ ZLEMA Decreasing for 5 Bars → Bearish Trend (Red Triangle Down at the Top)
zlemaDownTrend = zlema < zlema[1] and zlema[1] < zlema[2] and zlema[2] < zlema[3] and zlema[3] < zlema[4]
if ta.crossover(trend, 0) // Long Entry
stopLossLongLevel := useATRStopTP ? close - (atrValue * atrMultiplier) : zlema - volatility
profitTargetLongLevel := useProfitTarget ? (close + ((close - stopLossLongLevel) * profitTargetRR)) : na
if ta.crossunder(trend, 0) // Short Entry
stopLossShortLevel := useATRStopTP ? close + (atrValue * atrMultiplier) : zlema + volatility
profitTargetShortLevel := useProfitTarget ? (close - ((stopLossShortLevel - close) * profitTargetRR)) : na
// ATR-Based Stop-Loss Levels for Trade Exits
var float atrStopLossLong = na
var float atrStopLossShort = na
if useATRStopTP
if strategy.position_size > 0 // Long Position
atrStopLossLong := na(atrStopLossLong) or strategy.position_size[1] == 0 ? close - (atrValue * atrMultiplier) : math.max(nz(atrStopLossLong[1]), close - (atrValue * atrMultiplier)) // Prevents SL from decreasing
if strategy.position_size < 0 // Short Position
atrStopLossShort := na(atrStopLossShort) or strategy.position_size[1] == 0 ? close + (atrValue * atrMultiplier) : math.min(nz(atrStopLossShort[1]), close + (atrValue * atrMultiplier)) // Prevents SL from increasing
// ATR-Based Take-Profit Levels
var float atrTakeProfitLong = na
var float atrTakeProfitShort = na
if useATRStopTP
if strategy.position_size > 0 // Long Position
atrTakeProfitLong := strategy.position_avg_price + (atrValue * profitATRMultiplier) // Dynamic TP Based on ATR
if strategy.position_size < 0 // Short Position
atrTakeProfitShort := strategy.position_avg_price - (atrValue * profitATRMultiplier) // Dynamic TP Based on ATR
// ATR Trailing Stop Levels for Trade Exits and Visualization
var float trailStopLongLine = na
var float trailStopShortLine = na
if useTrailingStop
if strategy.position_size > 0 // Long Position
trailStopLongLine := na(trailStopLongLine) or strategy.position_size[1] == 0 ? close - (atrValue * trailStopMultiplier) :
math.max(nz(trailStopLongLine[1]), close - (atrValue * trailStopMultiplier))
if strategy.position_size < 0 // Short Position
trailStopShortLine := na(trailStopShortLine) or strategy.position_size[1] == 0 ? close + (atrValue * trailStopMultiplier) :
math.min(nz(trailStopShortLine[1]), close + (atrValue * trailStopMultiplier))
// ============================================================
// === 2️⃣ ENTRY & EXIT LOGIC (Conditions for Trading) ===
// ============================================================
// ✅ Entry Conditions for Long Trades
longCondition = ta.crossover(trend, 0) and close > zlema + volatility
canEnterLong = strategy.position_size == 0 or strategy.position_size[1] < 0 // Allows long entry right after short exit
if useZlemaTrendConfirm
longCondition := longCondition and zlemaUpTrend // Ensure ZLEMA Uptrend is true for long entries
// 🔥 Enforce that `longCondition` CANNOT be true if `zlemaUpTrend` is false
if useZlemaTrendConfirm and not zlemaUpTrend
longCondition := false
// ✅ Entry Conditions for Short Trades
shortCondition = allowShortTrades and ta.crossunder(trend, 0) and close < zlema - volatility
canEnterShort = strategy.position_size == 0 or strategy.position_size[1] > 0 // Allows short entry right after long exit
if useZlemaTrendConfirm
shortCondition := shortCondition and zlemaDownTrend // Ensure ZLEMA Downtrend is true for short entries
// ✅ Long Re-Entry Condition: ZLEMA is green, position is flat, price closed below and now above ZLEMA
reEntryLongCondition = reEnterOnLongTrend and
trend == 1 and
trend[1] == 1 and // ✅ Previous bar must also be in bullish trend (prevents triggering on trend change)
strategy.position_size == 0 and
close[1] < zlema[1] and
close > zlema
// ✅ Debugging: Display `longCondition` and `zlemaUpTrend` values only if the checkbox is checked
if showZlemaDebug and ta.crossover(trend, 0)
label.new(x=bar_index, y=low,
text="LongCondition: " + str.tostring(longCondition) +
"\nZLEMA UpTrend: " + str.tostring(zlemaUpTrend),
color=color.white, textcolor=color.black, size=size.small, style=label.style_label_down)
// ============================================================
// === 3️⃣ TRADE EXECUTIONS (Entries, ATR SL/TP, Trailing Stop, Trend Exit) ===
// ============================================================
// 📌 Entry Conditions
if (canEnterLong and longCondition) or reEntryLongCondition
lastEntryBarIndex := bar_index
lastEntryPrice := close
// 🛠️ Reset all SL/TP levels on Long Entry or Re-Entry
if reEntryLongCondition
// Trend-Based SL/TP
stopLossLongLevel := useATRStopTP ? na : zlema - volatility
profitTargetLongLevel := useProfitTarget and not useATRStopTP ? (close + ((close - stopLossLongLevel) * profitTargetRR)) : na
// ATR-Based SL/TP
atrStopLossLong := useATRStopTP ? close - (atrValue * atrMultiplier) : na
atrTakeProfitLong := useATRStopTP ? close + (atrValue * profitATRMultiplier) : na
// Trailing Stop
trailStopLongLine := useTrailingStop ? close - (atrValue * trailStopMultiplier) : na
strategy.entry(id="Long", direction=strategy.long, comment=reEntryLongCondition ? "Re-Entry Long" : "Bullish Trend Change")
if canEnterShort and shortCondition
lastEntryBarIndex := bar_index
lastEntryPrice := close
strategy.entry(id="Short", direction=strategy.short, comment="Bearish Trend Change")
// 📌 ATR-Based Stop-Loss Exits (Ensures SL Always Triggers Correctly)
if useATRStopTP and strategy.position_size > 0
if low <= atrStopLossLong
strategy.close("Long", comment="ATR SL Hit - Long")
if useATRStopTP and strategy.position_size < 0
if high >= atrStopLossShort
strategy.close("Short", comment="ATR SL Hit - Short")
// 📌 ATR-Based Stop-Loss & Take-Profit Exits (Ensures TP Always Executes)
if useATRStopTP and strategy.position_size > 0 and high >= atrTakeProfitLong
strategy.close("Long", comment="ATR TP Hit - Long")
if useATRStopTP and strategy.position_size < 0 and low <= atrTakeProfitShort
strategy.close("Short", comment="ATR TP Hit - Short")
// 📌 Profit Target Exits (Ensures TP Always Executes Independently)
if useProfitTarget and strategy.position_size > 0 and high >= profitTargetLongLevel
strategy.close("Long", comment="Profit Target Hit - Long")
if useProfitTarget and strategy.position_size < 0 and low <= profitTargetShortLevel
strategy.close("Short", comment="Profit Target Hit - Short")
// 📌 Stop-Loss for Profit Target Trades (Ensures Stop-Loss Works with TP)
if useProfitTarget and strategy.position_size > 0 and low <= stopLossLongLevel
strategy.close("Long", comment="Stop-Loss Hit - Long")
if useProfitTarget and strategy.position_size < 0 and high >= stopLossShortLevel
strategy.close("Short", comment="Stop-Loss Hit - Short")
// 📌 ATR Trailing Stop Loss (Ensures It Works Alongside Other Exits)
if useTrailingStop and strategy.position_size > 0 and low <= trailStopLongLine
strategy.close("Long", comment="Trailing Stop Hit - Long")
if useTrailingStop and strategy.position_size < 0 and high >= trailStopShortLine
strategy.close("Short", comment="Trailing Stop Hit - Short")
// 📌 Trend-Based Exit (Closes Position When Trend Reverses)
if strategy.position_size > 0 and ta.crossunder(trend, 0)
strategy.close("Long", comment="Trend Change to Bearish")
if strategy.position_size < 0 and ta.crossover(trend, 0)
strategy.close("Short", comment="Trend Change to Bullish")
// 📌 Break-Even Stop-Loss (Adjusts Stop to Entry Price at Set Risk-Reward Ratio)
if useBreakEven and strategy.position_size > 0 and high >= strategy.position_avg_price + (strategy.position_avg_price - atrStopLossLong) * breakEvenRR
atrStopLossLong := strategy.position_avg_price
if useBreakEven and strategy.position_size < 0 and low <= strategy.position_avg_price - (atrStopLossShort - strategy.position_avg_price) * breakEvenRR
atrStopLossShort := strategy.position_avg_price
// 📌 EMA Exit (Closes Position if Price Crosses EMA)
if useTrendExit and strategy.position_size > 0 and low < emaExit
strategy.close("Long", comment="Exit on EMA")
if useTrendExit and strategy.position_size < 0 and high > emaExit
strategy.close("Short", comment="Exit on EMA")
// ============================================================
// === 4️⃣ VISUALIZATIONS (Trend Shading, Stop-Loss, TP, ATR TS) ===
// ============================================================
// 🟢🔴 Restore Bullish/Bearish Trend Shading
zlemaColor = trend == 1 ? color.new(#00ffbb, 70) : color.new(#ff1100, 70)
m = plot(series=zlema, title="Zero Lag Basis", linewidth=2, color=zlemaColor)
upper = plot(zlema + volatility, style=plot.style_linebr, color=color.new(#ff1100, 90), title="Upper Deviation Band")
lower = plot(zlema - volatility, style=plot.style_linebr, color=color.new(#00ffbb, 90), title="Lower Deviation Band")
fill(plot1=m, plot2=upper, color=(trend == -1 ? color.new(#ff1100, 80) : na), title="Bearish Fill")
fill(plot1=m, plot2=lower, color=(trend == 1 ? color.new(#00ffbb, 80) : na), title="Bullish Fill")
// ✅ Plot a lime green TriangleUp at the bottom when ZLEMA has been going UP for 5 bars
plotshape(series=zlemaUpTrend ? low - ta.atr(5) * 0.5 : na,
location=location.bottom, style=shape.triangleup,
color=color.lime, title="ZLEMA Uptrend Detected")
// ✅ Plot a red TriangleDown at the top when ZLEMA has been going DOWN for 5 bars
plotshape(series=zlemaDownTrend ? high + ta.atr(5) * 0.5 : na,
location=location.top, style=shape.triangledown,
color=color.red, title="ZLEMA Downtrend Detected")
// 🔴 Default Stop-Loss Lines (Red) - Only Show If ATR SL/TP Is Not Used
plot(series=(not useATRStopTP and strategy.position_size > 0) ? stopLossLongLevel : na,
style=plot.style_linebr, color=color.red, linewidth=2, title="Trend Stop-Loss - Long")
plot(series=(not useATRStopTP and strategy.position_size < 0) ? stopLossShortLevel : na,
style=plot.style_linebr, color=color.red, linewidth=2, title="Trend Stop-Loss - Short")
// 🟠 ATR Trailing Stop Loss Line (Thin Orange Line) - Only Draw When Checkbox is Checked
plot(series=(useTrailingStop and strategy.position_size > 0) ? trailStopLongLine : na,
style=plot.style_linebr, color=color.new(color.orange, 70), linewidth=1, title="ATR Trailing Stop - Long")
plot(series=(useTrailingStop and strategy.position_size < 0) ? trailStopShortLine : na,
style=plot.style_linebr, color=color.new(color.orange, 70), linewidth=1, title="ATR Trailing Stop - Short")
// ✅ ATR-Based Stop-Loss Visualization (Ensures Line Stays Until Trade Closes)
plot(series=(useATRStopTP and strategy.position_size > 0) ? atrStopLossLong : na,
style=plot.style_linebr, color=color.new(color.red, 50), linewidth=2, title="ATR-Based Stop-Loss - Long")
plot(series=(useATRStopTP and strategy.position_size < 0) ? atrStopLossShort : na,
style=plot.style_linebr, color=color.new(color.red, 50), linewidth=2, title="ATR-Based Stop-Loss - Short")
// ✅ ATR-Based Take-Profit Visualization (Ensures Line Stays Until Trade Closes)
plot(series=(useATRStopTP and strategy.position_size > 0) ? atrTakeProfitLong : na,
style=plot.style_linebr, color=color.new(color.green, 50), linewidth=2, title="ATR-Based Take-Profit - Long")
plot(series=(useATRStopTP and strategy.position_size < 0) ? atrTakeProfitShort : na,
style=plot.style_linebr, color=color.new(color.green, 50), linewidth=2, title="ATR-Based Take-Profit - Short")
// ✅ Standard Profit Target Visualization (Only Active if ATR SL/TP is NOT Used)
plot(series=(useProfitTarget and not useATRStopTP and strategy.position_size > 0) ? profitTargetLongLevel : na,
style=plot.style_linebr, color=color.green, linewidth=2, title="Profit Target - Long")
plot(series=(useProfitTarget and not useATRStopTP and strategy.position_size < 0) ? profitTargetShortLevel : na,
style=plot.style_linebr, color=color.green, linewidth=2, title="Profit Target - Short")
// === 📋 FLOATING TABLE: STRATEGY PERFORMANCE & SETTINGS ===
// === Track first and last trade times ===
var int firstTradeTime = na
var int lastTradeTime = na
if strategy.opentrades > 0 and na(firstTradeTime)
firstTradeTime := time
if strategy.closedtrades > 0
lastTradeTime := time
// === Format trade date strings safely ===
firstDateStr = "N/A"
lastDateStr = "N/A"
if not na(firstTradeTime)
firstDateStr := str.tostring(month(firstTradeTime)) + "/" + str.tostring(dayofmonth(firstTradeTime)) + "/" + str.tostring(year(firstTradeTime) % 100)
if not na(lastTradeTime)
lastDateStr := str.tostring(month(lastTradeTime)) + "/" + str.tostring(dayofmonth(lastTradeTime)) + "/" + str.tostring(year(lastTradeTime) % 100)