マルチタイムフレームゼロレイテンシートレンドシグナル取引戦略:ZLEMAに基づく動的エントリー・エグジットシステム

ZLEMA ATR EMA MTF RR TP SL
作成日: 2025-05-20 14:45:41 最終変更日: 2025-05-20 14:45:41
コピー: 0 クリック数: 592
2
フォロー
319
フォロワー

マルチタイムフレームゼロレイテンシートレンドシグナル取引戦略:ZLEMAに基づく動的エントリー・エグジットシステム マルチタイムフレームゼロレイテンシートレンドシグナル取引戦略:ZLEMAに基づく動的エントリー・エグジットシステム

概要

マルチタイムフレームゼロレイテンズトレンドシグナル取引戦略は,従来の移動平均の遅れを軽減し,より迅速で正確なトレンド認識信号を提供するために,ゼロレイテンズインデックス移動平均 ((ZLEMA) に基づく定量取引システムである.この戦略は,トレンドの変化を認識するために,変動チャネルを組み合わせるだけでなく,リスクリターン,出場利益目標出場,ATRベースのストップとストップ,動的トラッキングストップと出場を横切る線などを含む複数の柔軟な出場メカニズムを統合している.この戦略は,中期および長期の取引に特に適しています.

戦略原則

この戦略の核心原則は,価格データ遅延をなくすか減らすことで移動平均の反応速度を向上させる技術指標であるゼロ遅延指数移動平均 (ZLEMA) に基づいています.具体的には,以下の手順を実行します.

  1. ゼロの遅延計算ZLEMAを計算し,公式で計算するzlema = ta.ema(src + (src - src[lag]), length)実現しましたlagこの方法は,従来のEMAでの遅滞を効果的に減らすことができます.

  2. トレンド識別

    • ZLEMAの基礎に波動的な通路を追加する (ブリン帯のような),通路の幅はATRの最高値の倍数で決定される
    • 価格が上位に進むと,トレンドは上昇します.
    • 価格が下位軌道に突入すると,トレンドは下向きに変化します (−1)
    • このシステムは,ZLEMAの方向に一致する5つの連続したK線の確認機能も提供しています.zlemaUpTrendそしてzlemaDownTrend変数の実現
  3. 多様な入学条件

    • 基本は複数のエントリー:価格が上位に並び,日付の範囲内
    • 進出は多入場:基本条件とZLEMAの継続的な5Kラインの上昇傾向が確認された
    • 空気入場:価格を下回り,日付範囲で (オプション機能)
    • ZLEMAゼロライン再入場:価格が一時的な回調の後,ZLEMA上に戻り,依然として多トレンド中
  4. 総合ダイナミック出場システム

    • リスク・リターン・リターン目標: 入場価格とストップ・ロスの計算に基づく特定のリスク・リターン・比率の目標価格
    • ATR ベースストップとストップ:ATR 乘数の動的にストップとストップ位置を計算する
    • ATRトラッキングストップ: 価格の動きに合わせてストップを自動で移動する
    • 利益のバランス・ストップ:利益が特定のリスク・リターン比率に達すると,ストップは入場価格に移動する
    • トレンド反転出場: トレンド指標が反転すると自動的に出場する
    • EMA出場:価格が特定のEMAを超えると退出する

戦略的優位性

複数のタイムフレームのゼロ遅延トレンドシグナル取引戦略には,顕著な利点があります.

  1. 信号の遅延を減らすZLEMA技術により,従来の移動平均の遅延が減り,トレンドの認識がより迅速になり,トレンドの起点がより早く捉えられます.

  2. 全面的なリスク管理システム: 複数のレベルのリスク管理機構を統合し,固定ストップ,ATRダイナミックストップ,トラッキングストップから利回りバランスストップまで,異なる市場環境に完全な保護を提供します.

  3. 柔軟な取引方法: 複数の戦略のみまたは双方向の取引戦略として設定でき,異なる市場好みと規制環境に対応します.

  4. 再入学制度: ZLEMAのゼロライン再入場機能により,強気なトレンドで短期的な回調後に再入場を許可し,トレンドの利益を最大化します.

  5. 多様化による脱退策: 市場状況に合わせて複数の退出オプションを提供します. 利潤目標を設定することで利潤を固定したり,ストップ・ロスを追跡することで利潤を走らせたりできます.

  6. ビジュアルアシスタント: トレンドシャドー,ストップ・ロズ・ライン,ストップフローライン,トレンドインジケーターなどのビジュアル要素を使用して,取引信号とリスク管理位置を直視的に表示する.

  7. 詳細な業績統計: 戦略の評価と最適化に役立つ勝利率,純利益,最大回収などの重要な指標を表示する取引統計表を統合した.

戦略リスク

この戦略は合理的に設計されていますが,注意すべき潜在的なリスクがあります.

  1. パラメータ感度:ZLEMAの長さやATRの倍数などのコアパラメータは,戦略のパフォーマンスに顕著な影響を及ぼし,不適切な設定は,信号を過多または過少に導きます.

  2. 市場を揺るがす偽信号: 明確なトレンドがない不安定な市場では,誤った信号が頻繁に発生し,連続的な損失を招く可能性があります.

  3. トレンド反転リスク戦略は,退出の仕組みを複数用意しているものの,急激なトレンドの逆転で,退出を遅らせて大きな損失を被る可能性がある.

  4. オーバーフィットするリスク:複数のパラメータの組み合わせにより,過去のデータに過度に適合し,将来の市場環境で不十分なパフォーマンスを発揮する可能性があります.

  5. 長周期信号は稀である: 長いZLEMAの長さを使用すると,戦略は取引信号を少なくして,資金利用の効率に影響を与える可能性があります.

  6. 幅の減少を阻止する挑戦ATRに基づくストップは,高波動の市場では過幅になり,単一の損失が過大になる可能性があります.低波動の市場では過狭になり,頻繁にトリガーされる可能性があります.

これらのリスクを緩和する方法は,厳格なパラメータの反省と前向きの検証,市場の状況指標と組み合わせた,不安定な市場での取引を避ける,厳格な資金管理規則の実施,市場の変化に対応するために戦略パラメータを定期的に再最適化することです.

戦略最適化の方向性

この戦略は,以下の方向からさらにパフォーマンスを向上させるための多くの最適化領域があります.

  1. ダイナミックなパラメータは自律的に市場変動に応じてZLEMAの長さとATRの倍数を自動的に調整する自己適応メカニズムを開発し,異なる市場環境における戦略の適応性を向上させる.

  2. 市場状況のフィルター市場状態指標 (ADX,波動性指標など) を導入し,有利な市場条件でのみ取引し,低効率な波動的な市場での頻繁な取引を避ける.

  3. 複数時間枠確認: より高い時間枠のトレンド方向を組み合わせて,大きなトレンド方向が一致している場合にのみ参加し,成功率を上げます.

  4. 取引量確認: 取引量指標を統合し,取引量が増えるとのみトレンド変化信号を確認する.

  5. 機械学習の最適化: 最適なパラメータの組み合わせと入場タイミングを探すために機械学習アルゴリズムを使用し,特にどの信号が成功する可能性が高いかを予測するモデルを訓練できます.

  6. 季節性および時間フィルター: 取引時間やカレンダーフィルターを追加して,低効率な取引やリスクの高い取引を避ける.

  7. 関連資産関連分析関連資産の関連性分析を導入し,複数の資産の同向確認時に信号の信頼性を高めます.

これらの最適化方向は,戦略の安定性と収益性を向上させるだけでなく,リスクを低減し,異なる市場環境と個人のリスク好みに適したものにすることができる.

要約する

複数の時間枠のゼロ遅延トレンドシグナル取引戦略は,ゼロ遅延指数移動平均 ((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)