
다중 시간 프레임 자동 적응 시장 메커니즘 정량 거래 전략은 다중 지표 통합 분석을 기반으로 한 고급 정량 거래 시스템으로, 다양한 시장 조건에 따라 거래 전략을 자동으로 조정할 수 있습니다. 이 전략은 인공 지능을 사용하여 4 가지 시장 메커니즘을 식별하는 기술 (향상형, 간격형, 파동형 및 정지형) 을 사용하여 현재 시장 상태에 따라 거래 매개 변수를 동적으로 조정합니다. 핵심 기술은 다중 시간 프레임 분석, 도형 인식, 동적 위험 관리 및 자동 최적화 알고리즘을 포함하여 거래자에게 포괄적이고 유연한 거래 도구를 제공합니다.
이 전략의 핵심은 다단계 시장 분석 프레임워크로, 여러 기술 지표를 통합하여 정확한 시장 상태 탐지 및 신호 생성을 구현합니다.
이동 평균 시스템: 빠른 ((9주기) 와 느린 ((34주기) 지수 이동 평균 ((EMA) 를 사용하여 트렌드 방향을 결정하고, ATR 값과 결합하여 판단 정확성을 강화한다.
다중 시간 프레임 확인 메커니즘: 더 높은 시간 주기의 RSI와 MACD 지표를 통해 더 큰 시장 관점을 제공 하 고, 낮은 시간 주기의 잡음 신호를 필터링. 전략은 특히 높은 시간 프레임의 추세를 확인 하 고, HTF_RSI와 HTF_MACD의 교차점을 강도 필터로 사용합니다.
시장 메커니즘 식별 알고리즘:
그램 형식 인식 및 매매량 확인전략: 여러 가지 높은 확률의 차트 형태를 탐지합니다. 삼키기 형태, ?? 子線, 새벽 별 형태, 穿刺線, 雙底, 그리고 그것의 하향 대응 형태. 각 형태는 거래량을 확대 확인하고 신호 신뢰성을 강화합니다.
다인자 점수 시스템: 종합적으로 기술 지표, 형태 인식 및 거래량 상황을 평가하여 종합적인 점수를 생성한다. 구매 신호는 황소 시장 점수 ≥1.0을 요구하며, 판매 신호는 곰 시장 점수 ≥1.0을 요구한다.
동적 중지 및 추적 중지: ATR을 사용하여 동적 중지 수준을 계산하여 위험 관리가 시장의 변동성에 적응하도록합니다. 중지 거리는 ATR 값에 따라 자동으로 조정되며 변동성이 증가하면 확대되고 변동성이 감소하면 축소됩니다.
자동 최적화 성능 추적시스템: 시스템에는 다양한 시장 메커니즘의 거래 성과를 기록하여 거래 매개 변수 및 등급 하락을 조정하고 전략의 적응 최적화를 구현합니다.
전체 시장 적응성이 전략의 가장 큰 장점은 4 가지 다른 시장 상태를 자동으로 식별하고 적응할 수 있다는 것입니다. 이는 변화하는 시장 환경에서 단일 전략의 한계를 피할 수 있습니다. 시장이 강한 추세, 가로 정리, 높은 변동 또는 낮은 변동 상태에 있더라도 시스템이 파라미터와 신호 절정을 적절하게 조정할 수 있습니다.
다중 시간 프레임 확인이 전략은 더 높은 시간 주기 지표를 통합함으로써 신호 품질을 크게 향상시킵니다. 이러한 “상부터 아래로”의 분석 방법은 낮은 품질의 신호를 효과적으로 필터링하여 가짜 돌파구와 잡음 거래를 줄입니다.
고급 형식 인식: 트래픽 확인을 결합한 그라프 형태 인식은 높은 확률의 입문 신호를 제공한다. 이러한 형태는 지지점과 저항점 근처에 나타나고 트래픽이 증가할 때 특히 효과적이다.
동적 위험 관리ATR 기반의 중지 및 추적 중지 메커니즘은 시장의 변동성에 따라 위험 관리가 자동으로 조정될 수 있도록 보장합니다. 이 방법은 자본을 보호하면서도 수익성있는 포지션이 계속 작동하도록 허용하며 위험과 수익률을 최적화합니다.
자동 최적화 메커니즘전략은 다양한 시장 체제에서의 성과를 기록하고, 향후 거래에 대한 피드백과 조정 근거를 제공하며, 지속적인 자기 개선을 실현합니다.
시각적 감시: 컬러 코딩 된 배경과 성능 디스플레이를 통해 거래자는 현재의 시장 상태, 전략 성능 및 주요 지표를 직관적으로 이해할 수 있으며, 운영 투명성을 높일 수 있습니다.
매개변수 민감도이 전략은 여러 개의 변수와 값을 사용하여 시장 메커니즘을 식별하고 신호를 생성한다. 이러한 변수들의 설정은 신중하게 조정되어야 하며, 그렇지 않으면 시장 상태를 잘못 판단하거나 잘못된 신호를 생성할 수 있다. 특히 ADX, ATR 비율 및 블린 대역폭과 같은 중요한 값은 서로 다른 거래 품종의 특성에 따라 최적화되어야 한다.
계산 복잡도다층적인 지표 계산과 논리적 판단은 전략의 복잡성을 증가시키고, 특히 낮은 시간 주기 또는 고주파 거래 환경에서 회수와 실시간 실행 속도가 느려질 수 있습니다.
시장 전환이 지연됐습니다.: 전략이 다른 시장 상태를 식별하기 위해 설계되었지만, 시장 전환 과정은 순간적이지 않고 점진적일 수 있습니다. 전환 중에 전략은 오해와 잘못된 신호의 위험에 직면 할 수 있습니다.
기술적인 지표에 지나치게 의존하는 것전략은 주로 기술적 지표와 가격 형태에 기반하며, 기본적 요소와 시장의 정서를 고려하지 않습니다. 중요한 뉴스 또는 블랙 스 사건이 발생하면 순수한 기술적 분석이 무효가 될 수 있습니다.
오차 감지전략의 복잡성과 자기 적응성 때문에, 역사적인 데이터에 지나치게 맞춤하는 위험이 있으며, 실제적인 성과는 재검토 결과보다 떨어질 수 있다.
자본 요구: 동적 위험 관리 메커니즘은 특정 시장 조건에서 더 큰 스톱 라인지가 필요할 수 있습니다. 이것은 합리적인 위험 비율을 유지하기 위해 충분한 거래 자금을 요구합니다.
기계 학습 강화: 시장 메커니즘 식별 및 변수 조정을 최적화하기 위해 기계 학습 알고리즘을 도입한다. 역사적 데이터 훈련 모델을 사용하여 다양한 시장 상태의 잠재적인 패턴을 식별하여 분류 정확도를 향상시킬 수 있다. 구현 방법은 무작위 숲을 사용하거나 시장 상태를 분류하기 위해 벡터 기계를 지원하는 방법, 신경 네트워크 최적화 지표 무게를 사용하는 것을 포함 할 수 있다.
감정 지표 통합: 시장 감정 지표를 도입 (VIX, 사상/보상 옵션 비율, 소셜 미디어 감정 분석 등) 추가 확인 계층으로. 시장 감정 데이터는 시장 전환점을 예측하는 데 도움이되는 선도적인 지표로 사용될 수 있습니다.
기본 데이터 통합: 경제 달력 이벤트, 수익 보고서 또는 주요 뉴스 발표와 같은 중요한 기본 데이터를 통합하는 프레임 워크를 개발하십시오. 이것은 중요한 발표 전에 위험 을 조정하고 예상치 못한 변동으로 인한 손실을 피하는 데 도움이됩니다.
시간 필터거래 시간 필터를 적용하여 유동성이 낮거나 변동성이 이상한 시간을 피하십시오. 이것은 아시아, 유럽 및 미국 시장의 거래 시간에 교차하는 시간의 이상 행위를 피하는 데 특히 중요합니다.
연관성 분석 모듈: 자산 간 연관성 분석 기능을 추가하여 다중 시장 패턴과 분산 신호를 식별합니다. 예를 들어, 통화 쌍 간의 연관성, 주식 지수와 VIX의 관계 등이 추가 거래 확인을 제공합니다.
동적 지분 규모 최적화: 현재 시장 메커니즘과 역사적인 성과에 기초하여 포지션 크기를 자동으로 조정한다. 좋은 성능의 시장 메커니즘은 위험 을 증가시킬 수 있으며, 불확실성이나 역사적으로 좋지 않은 환경에서 위험을 줄일 수 있다.
하드웨어 최적화: 코드 효율성을 개선하고, 특히 실시간 거래 환경에서 계산 복잡성을 줄인다. 더 효율적인 알고리즘과 데이터 구조를 사용하여 일부 논리를 다시 작성하는 것을 고려할 수 있다.
다중 시간 프레임 자체 적응 시장 메커니즘 수량 거래 전략은 시장 메커니즘 식별, 다중 시간 프레임 분석, 형태 식별 및 동적 위험 관리를 통합하는 수량 거래 시스템의 중요한 혁신을 나타냅니다. 자체 적응 능력과 전체적인 기술 지표 통합은 단일 시장 상태에만 국한되지 않고 다양한 시장 환경에서 경쟁력을 유지할 수 있습니다.
이 전략의 진정한 가치는 개별적인 구성 요소가 아닌 전체적인 프레임워크에 있습니다. 시장 메커니즘 식별, 다중 시간 프레임 확인, 형태 식별 및 동적 위험 관리의 연동으로 전략은 고품질 신호를 생성하고 위험을 효과적으로 관리 할 수 있습니다. 이러한 다층적 접근은 잘못된 신호를 줄이고 전반적인 건전성을 향상시킵니다.
그러나, 이 전략은 또한 파라미터의 민감성, 계산의 복잡성, 그리고 잠재적인 과도한 매칭과 같은 도전을 직면한다. 거래자는 이 전략을 적용할 때 이러한 위험을 주의해야 하며, 충분한 파라미터 최적화와 전향 테스트를 실시해야 한다.
미래 최적화 방향은 기계 학습 강화, 감정 지표 통합 및 동적 지주 규모 조정 등이 포함됩니다. 이러한 개선은 전략의 적응성과 안정성을 더욱 향상시켜 더 포괄적인 거래 시스템으로 만들 것입니다.
/*backtest
start: 2025-04-13 00:00:00
end: 2025-04-20 00:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"TRX_USD"}]
*/
//@version=6
strategy("Dskyz (DAFE) AI Adaptive Regime - Pro", overlay=true, default_qty_type=strategy.fixed, default_qty_value=1, calc_on_order_fills=true, calc_on_every_tick=true)
// This script uses higher timeframe values for RSI/MACD, integrated into regime detection and scoring.
// Logic uses closed HTF bars to avoid repainting.
// D=====================================================Z
// 1. ATR SETTINGS==Z
// D=====================================================Z
group_atr = "⚡ ATR Settings"
atr_period = input.int(14, "ATR Period", minval=1, group=group_atr)
atr_multiplier = input.float(1.5, "ATR Multiplier", minval=0.1, step=0.1, group=group_atr)
atr_val = ta.atr(atr_period)
atr_avg = ta.sma(atr_val, 50)
// D=====================================================Z
// 2. MOVING AVERAGE (MA) SETTINGS==Z
// D=====================================================Z
group_ma = "📊 Moving Averages"
fast_ma_length = input.int(9, "Fast MA Length", minval=1, group=group_ma)
slow_ma_length = input.int(34, "Slow MA Length", minval=1, group=group_ma)
ma_fast = ta.ema(close, fast_ma_length)
ma_slow = ta.ema(close, slow_ma_length)
ma_strength_threshold = input.float(0.5, "MA Strength Threshold", minval=0.0, step=0.1, group=group_ma)
trend_dir = ma_fast > ma_slow + (atr_val * ma_strength_threshold) ? 1 : ma_fast < ma_slow - (atr_val * ma_strength_threshold) ? -1 : 0
// D=====================================================Z
// 3. MULTI-TIMEFRAME (HTF) SETTINGS==Z
// D=====================================================Z
group_MTA = "⏱️ Multi-Timeframe Inputs"
htf = input.timeframe("D", "HTF for RSI & MACD", group=group_MTA)
htf_rsi_raw = request.security(syminfo.tickerid, htf, ta.rsi(close, 14))
htf_rsi = htf_rsi_raw[1]
[htf_macd_line_raw, htf_macd_signal_raw, htf_macd_hist_raw] = request.security(syminfo.tickerid, htf, ta.macd(close, 12, 26, 9))
htf_macd_line = htf_macd_line_raw[1]
htf_macd_signal = htf_macd_signal_raw[1]
htf_macd_hist = htf_macd_hist_raw[1]
// new: HTF trend direction for regime detection
htf_trend_bull = htf_macd_line > htf_macd_signal and htf_rsi > 50
htf_trend_bear = htf_macd_line < htf_macd_signal and htf_rsi < 50
// D=====================================================Z
// 4. TRADE SETTINGS==Z
// D=====================================================Z
group_trade = "⚙️ Trade Settings"
risk_per_trade = input.int(500, "Risk per Trade ($)", minval=50, group=group_trade)
max_contracts = input.int(5, "Max Contracts", minval=1, group=group_trade)
max_daily_drawdown = input.float(0.05, "Max Daily Drawdown (%)", minval=0.01, group=group_trade)
tick_value = input.float(12.5, "Tick Value ($)", minval=0.01, group=group_trade)
ticks_per_point = input.int(4, "Ticks per Point", minval=1, group=group_trade)
default_stop_points = input.float(8.0, "Default Stop (Points)", minval=0.25, group=group_trade)
// D=====================================================Z
// 5. ADVANCED INDICATOR CALCULATIONS==Z
// D=====================================================Z
// --- ADX Calculation ---Z
adx_len = 14
up = ta.change(high)
down = -ta.change(low)
plus_dm = na(up) ? na : (up > down and up > 0 ? up : 0)
minus_dm = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, adx_len)
plus_di = 100 * ta.rma(plus_dm, adx_len) / trur
minus_di = 100 * ta.rma(minus_dm, adx_len) / trur
adx_val = 100 * ta.rma(math.abs(plus_di - minus_di) / (plus_di + minus_di), adx_len)
// --- Bollinger Bands Calculation ---Z
bb_basis = ta.sma(close, 20)
bb_dev = 2 * ta.stdev(close, 20)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
bb_width = (bb_upper - bb_lower) / bb_basis
bb_width_avg = ta.sma(bb_width, 50)
// --- Price Action Range ---Z
price_range = ta.highest(high, 20) - ta.lowest(low, 20)
range_ratio = price_range / close
// D=====================================================Z
// 6. REGIME ASSIGNMENT & PATTERN RECOGNITION==Z
// D=====================================================Z
// Regime assignment with HTF influence and looser thresholds
is_trending = adx_val > 20 and math.abs(ma_fast - ma_slow) > atr_val * 0.3 and htf_trend_bull or htf_trend_bear // loosened ADX and MA thresholds, added HTF
is_range = adx_val < 25 and range_ratio < 0.03 and not htf_trend_bull and not htf_trend_bear // loosened ADX and range, HTF neutral
is_volatile = bb_width > bb_width_avg * 1.5 and atr_val > atr_avg * 1.2 and (htf_rsi > 70 or htf_rsi < 30) // loosened BB/ATR, added HTF overbought/oversold
is_quiet = bb_width < bb_width_avg * 0.8 and atr_val < atr_avg * 0.9 // loosened BB/ATR
regime = is_trending ? 1 : is_range ? 2 : is_volatile ? 3 : is_quiet ? 4 : 5
regime_name = regime == 1 ? "Trending" : regime == 2 ? "Range" : regime == 3 ? "Volatile" : regime == 4 ? "Quiet" : "Other"
// Pattern Recognition & Volume Confirmation-Z
vol_avg = ta.sma(volume, 20)
vol_spike = volume > vol_avg * 1.5
recent_low = ta.lowest(low, 20)
recent_high = ta.highest(high, 20)
is_near_support = low <= recent_low * 1.01
is_near_resistance = high >= recent_high * 0.99
bullish_engulfing = close[1] < open[1] and close > open and close > open[1] and open < close[1] and is_near_support and vol_spike
hammer = high - low > 3 * math.abs(open - close) and (close - low) / (0.001 + high - low) > 0.6 and is_near_support and vol_spike
morning_star = close[2] < open[2] and math.abs(close[1] - open[1]) < 0.2 * (high[1] - low[1]) and close > open and close > (open[2] + close[2]) / 2 and is_near_support and vol_spike
piercing = close[1] < open[1] and close > open and close > (open[1] + close[1]) / 2 and open < close[1] and is_near_support and vol_spike
double_bottom = low < low[1] and low[1] > low[2] and low[2] < low[3] and close > open and is_near_support and vol_spike
bearish_engulfing = close[1] > open[1] and close < open and close < open[1] and open > close[1] and is_near_resistance and vol_spike
shooting_star = high - low > 3 * math.abs(open - close) and (high - close) / (0.001 + high - low) > 0.6 and is_near_resistance and vol_spike
evening_star = close[2] > open[2] and math.abs(close[1] - open[1]) < 0.2 * (high[1] - low[1]) and close < open and close < (open[2] + close[2]) / 2 and is_near_resistance and vol_spike
dark_cloud = close[1] > open[1] and close < open and close < (open[1] + close[1]) / 2 and open > close[1] and is_near_resistance and vol_spike
double_top = high > high[1] and high[1] < high[2] and high[2] > high[3] and close < open and is_near_resistance and vol_spike
bull_signal = (bullish_engulfing ? 0.5 : 0.0) +
(hammer ? (regime == 2 ? 0.4 : 0.2) : 0.0) +
(morning_star ? 0.2 : 0.0) +
(piercing ? 0.2 : 0.0) +
(double_bottom ? (regime == 3 ? 0.3 : 0.15) : 0.0)
bear_signal = (bearish_engulfing ? 0.5 : 0.0) +
(shooting_star ? (regime == 2 ? 0.4 : 0.2) : 0.0) +
(evening_star ? 0.2 : 0.0) +
(dark_cloud ? 0.2 : 0.0) +
(double_top ? (regime == 3 ? 0.3 : 0.15) : 0.0)
// Multi-Factor Confirmation with HTF-Z
rsi_val = ta.rsi(close, 14)
[macd_line, macd_signal, macd_hist] = ta.macd(close, 12, 26, 9)
trend_bull = ma_fast > ma_slow
trend_bear = ma_fast < ma_slow
rsi_bull = rsi_val < 30
rsi_bear = rsi_val > 70
macd_bull = macd_line > macd_signal
macd_bear = macd_line < macd_signal
vol_expansion = atr_val > atr_avg * 1.2
// new: HTF confirmation for scoring
htf_bull_confirm = htf_trend_bull and htf_rsi < 70
htf_bear_confirm = htf_trend_bear and htf_rsi > 30
bull_score = bull_signal + (trend_bull ? 0.2 : 0) + (rsi_bull ? 0.15 : 0) + (macd_bull ? 0.15 : 0) + (vol_expansion ? 0.1 : 0) + (htf_bull_confirm ? 0.2 : 0)
bear_score = bear_signal + (trend_bear ? 0.2 : 0) + (rsi_bear ? 0.15 : 0) + (macd_bear ? 0.15 : 0) + (vol_expansion ? 0.1 : 0) + (htf_bear_confirm ? 0.2 : 0)
// D=====================================================Z
// 7. PERFORMANCE TRACKING & ADAPTIVE THRESHOLDS==Z
// D=====================================================Z
var float[] regime_pnl_long = array.new_float(5, 0)
var float[] regime_pnl_short = array.new_float(5, 0)
var int[] regime_win_long = array.new_int(5, 0)
var int[] regime_loss_long = array.new_int(5, 0)
var int[] regime_win_short = array.new_int(5, 0)
var int[] regime_loss_short = array.new_int(5, 0)
var int entry_regime = na
if barstate.isconfirmed and strategy.closedtrades > 0 and not na(entry_regime)
last_trade_profit = strategy.closedtrades.profit(strategy.closedtrades - 1)
last_trade_entry_id = strategy.closedtrades.entry_id(strategy.closedtrades - 1)
idx = entry_regime - 1
if last_trade_entry_id == "Long"
array.set(regime_pnl_long, idx, array.get(regime_pnl_long, idx) + last_trade_profit)
if last_trade_profit > 0
array.set(regime_win_long, idx, array.get(regime_win_long, idx) + 1)
else
array.set(regime_loss_long, idx, array.get(regime_loss_long, idx) + 1)
else if last_trade_entry_id == "Short"
array.set(regime_pnl_short, idx, array.get(regime_pnl_short, idx) + last_trade_profit)
if last_trade_profit > 0
array.set(regime_win_short, idx, array.get(regime_win_short, idx) + 1)
else
array.set(regime_loss_short, idx, array.get(regime_loss_short, idx) + 1)
entry_regime := na
// D=====================================================Z
// 8. DRAWDOWN & CIRCUIT BREAKER==Z
// D=====================================================Z
var float max_equity = strategy.equity
if strategy.equity > max_equity
max_equity := strategy.equity
daily_drawdown = (max_equity - strategy.equity) / max_equity
pause_trading = daily_drawdown > max_daily_drawdown
// D=====================================================Z
// 9. ENTRY & EXIT LOGIC WITH DYNAMIC STOPS & TRAILING STOPS=Z
// D=====================================================Z
swing_low = ta.lowest(low, 5)
swing_high = ta.highest(high, 5)
long_condition = bull_score >= 1.0 and not pause_trading
short_condition = bear_score >= 1.0 and not pause_trading
var float trail_stop_long = na
var float trail_stop_short = na
var float long_stop_price = na
var float long_limit_price = na
var float short_stop_price = na
var float short_limit_price = na
if long_condition and strategy.position_size <= 0
intended_stop = swing_low - atr_multiplier * atr_val
stop_distance_points = close - intended_stop
risk_per_contract = stop_distance_points * syminfo.pointvalue
contracts = math.floor(risk_per_trade / risk_per_contract)
contracts := contracts > 0 ? contracts : 1
contracts := math.min(contracts, max_contracts)
long_limit = close + stop_distance_points * 2
strategy.entry("Long", strategy.long, qty = contracts)
strategy.exit("Exit", from_entry = "Long", stop = intended_stop, limit = long_limit)
long_stop_price := intended_stop
long_limit_price := long_limit
trail_stop_long := intended_stop
entry_regime := regime
if short_condition and strategy.position_size >= 0
intended_stop = swing_high + atr_multiplier * atr_val
stop_distance_points = intended_stop - close
risk_per_contract = stop_distance_points * syminfo.pointvalue
contracts = math.floor(risk_per_trade / risk_per_contract)
contracts := contracts > 0 ? contracts : 1
contracts := math.min(contracts, max_contracts)
short_limit = close - stop_distance_points * 2
strategy.entry("Short", strategy.short, qty = contracts)
strategy.exit("Exit", from_entry = "Short", stop = intended_stop, limit = short_limit)
short_stop_price := intended_stop
short_limit_price := short_limit
trail_stop_short := intended_stop
entry_regime := regime
if strategy.position_size > 0
if close > long_limit_price * 0.5
trail_stop_long := math.max(trail_stop_long, close - atr_val * atr_multiplier)
strategy.exit("Long Trailing Stop", from_entry = "Long", stop = trail_stop_long)
if strategy.position_size < 0
if close < short_limit_price * 0.5
trail_stop_short := math.min(trail_stop_short, close + atr_val * atr_multiplier)
strategy.exit("Short Trailing Stop", from_entry = "Short", stop = trail_stop_short)
if strategy.position_size == 0
long_stop_price := na
long_limit_price := na
short_stop_price := na
short_limit_price := na
// D=====================================================Z
// 10. VISUALIZATION==Z
// D=====================================================Z
bgcolor(regime == 1 ? color.new(color.green, 85) :
regime == 2 ? color.new(color.orange, 85) :
regime == 3 ? color.new(color.red, 85) :
regime == 4 ? color.new(color.gray, 85) :
color.new(color.navy, 85))
plotshape(long_condition, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Long Signal")
plotshape(short_condition, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Short Signal")
plot(ma_fast, "Fast MA", color=color.new(color.blue, 0), linewidth=2)
plot(ma_slow, "Slow MA", color=color.new(color.red, 0), linewidth=2)
plot(strategy.position_size > 0 ? long_stop_price : na, "Long Stop", color=color.new(color.red, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? long_limit_price : na, "Long Target", color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? short_stop_price : na, "Short Stop", color=color.new(color.red, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? short_limit_price : na, "Short Target", color=color.new(color.green, 0), style=plot.style_linebr)
// D=====================================================Z
// 11. DASHBOARD: METRICS TABLE (Bottom-Left)=Z
// D=====================================================Z
var table dashboard = table.new(position.bottom_left, 2, 13, bgcolor=color.new(#000000, 29), border_color=color.rgb(80,80,80), border_width=1)
if barstate.islast
table.cell(dashboard, 0, 0, "⚡(DAFE) AI Adaptive Regime™", text_color=color.rgb(96,8,118), text_size=size.small)
modeStr = pause_trading ? "Paused" : "Active"
table.cell(dashboard, 0, 1, "Mode:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 1, modeStr, text_color=color.white, text_size=size.small)
trendText = trend_dir == 1 ? "Bullish" : trend_dir == -1 ? "Bearish" : "Neutral"
table.cell(dashboard, 0, 2, "Trend:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 2, trendText, text_color=trend_dir == 1 ? color.green : trend_dir == -1 ? color.red : color.gray, text_size=size.small)
table.cell(dashboard, 0, 3, "ATR:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 3, str.tostring(atr_val, "#.##"), text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 4, "ATR Avg:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 4, str.tostring(atr_avg, "#.##"), text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 5, "Volume Spike:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 5, vol_spike ? "YES" : "NO", text_color=vol_spike ? color.green : color.red, text_size=size.small)
table.cell(dashboard, 0, 6, "RSI:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 6, str.tostring(rsi_val, "#.##"), text_color=color.white, text_size=size.small)
rsiCondText = rsi_val < 30 ? "Oversold" : rsi_val > 70 ? "Overbought" : "Neutral"
table.cell(dashboard, 0, 7, "RSI Cond:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 7, rsiCondText, text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 8, "HTF RSI:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 8, str.tostring(htf_rsi, "#.##"), text_color=color.white, text_size=size.small)
htfTrendText = htf_trend_bull ? "Bullish" : htf_trend_bear ? "Bearish" : "Neutral"
table.cell(dashboard, 0, 9, "HTF Trend:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 9, htfTrendText, text_color=htf_trend_bull ? color.green : htf_trend_bear ? color.red : color.gray, text_size=size.small)
lastSignal = long_condition ? "Buy" : short_condition ? "Sell" : "None"
table.cell(dashboard, 0, 10, "Last Signal:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 10, lastSignal, text_color=long_condition ? color.green : short_condition ? color.red : color.white, text_size=size.small)
table.cell(dashboard, 0, 11, "Regime:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 11, regime_name, text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 12, "Bull Score:", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 12, str.tostring(bull_score, "#.##"), text_color=color.white, text_size=size.small)
// D=====================================================Z
// REGIME CONDITIONS
// D=====================================================Z
var table debug_table = table.new(position.top_right, 2, 5, bgcolor=color.new(#000000, 50), border_color=color.rgb(80,80,80), border_width=1)
if barstate.islast
table.cell(debug_table, 0, 0, "Regime Conditions", text_color=color.rgb(96,8,118), text_size=size.small)
table.cell(debug_table, 0, 1, "ADX:", text_color=color.white, text_size=size.small)
table.cell(debug_table, 1, 1, str.tostring(adx_val, "#.##"), text_color=color.white, text_size=size.small)
table.cell(debug_table, 0, 2, "BB Width Ratio:", text_color=color.white, text_size=size.small)
table.cell(debug_table, 1, 2, str.tostring(bb_width / bb_width_avg, "#.##"), text_color=color.white, text_size=size.small)
table.cell(debug_table, 0, 3, "ATR Ratio:", text_color=color.white, text_size=size.small)
table.cell(debug_table, 1, 3, str.tostring(atr_val / atr_avg, "#.##"), text_color=color.white, text_size=size.small)
table.cell(debug_table, 0, 4, "Range Ratio:", text_color=color.white, text_size=size.small)
table.cell(debug_table, 1, 4, str.tostring(range_ratio, "#.##"), text_color=color.white, text_size=size.small)
// --- Bollinger Bands Visuals ---Z
p_bb_basis = plot(bb_basis, title="BB Basis", color=color.new(#ffffff, 50), linewidth=1)
p_bb_upper = plot(bb_upper, title="BB Upper", color=color.new(#4caf4f, 45), linewidth=2)
p_bb_lower = plot(bb_lower, title="BB Lower", color=color.new(#ff5252, 45), linewidth=2)
fill(p_bb_upper, p_bb_lower, color=color.new(#423645, 65))
//D=================================================================Z
// DASHBOARD: WATERMARK LOGO (Bottom-Right)
//D=================================================================Z
var table watermarkTable = table.new(position.bottom_right, 1, 1, bgcolor=color.rgb(0,0,0,80), border_color=color.rgb(0,50,137), border_width=1)
if barstate.islast
table.cell(watermarkTable, 0, 0, "⚡ Dskyz (DAFE) AI Adaptive Regime - Pro", text_color=color.rgb(96,8,118), text_size=size.normal)
// --- ALERTS ---Z
alertcondition(long_condition, title="Long Signal Alert", message="Enhanced Strategy Long Signal")
alertcondition(short_condition, title="Short Signal Alert", message="Enhanced Strategy Short Signal")