
다중 시간 주기의 트렌드 동적 거래 전략은 다중 시간 주기의 트렌드 분석, 동적 신호, 거래량 확인 및 지능형 자금 개념을 통합하여 거래자에게 강력한 도구를 제공하여 시장 추세를 포착하고 가짜 신호를 최소화합니다. 전략의 독특한 “AI” 구성 요소는 여러 시간 주기의 트렌드를 분석하고 명확하고 작동 가능한 디스플레이를 제공하여 초보자 및 숙련 된 거래자가 쉽게 사용할 수 있습니다.
이 전략은 여러 가지 구성 요소들을 통합하여 만들어진 하나의 상환 시스템입니다.
다중 시간 주기 트렌드 분석전략은 3개의 시간주기를 사용해서 경향을 평가하고, 지수 이동 평균 (EMA) 과 거래량 가중 평균 가격 (VWAP) 을 사용한다. 가격이 EMA와 VWAP 위에 있을 때, 경향은 낙관적이라고 여겨지고, 가격이 아래에 있을 때, 낙관적이라고 여겨지며, 그렇지 않으면 중립적이다. 사용자가 선택한 더 높은 시간주기 경향이 거래 방향과 일치할 때만 신호를 생성한다. 이것은 잡음을 줄이고, 거래가 더 넓은 시장의 배경에 따르도록 보장한다.
동력 필터: 연속된 기둥들 사이의 비율 가격 변화를 측정하고, 그것을 변동률과 조정하여 평균 실제 범위에 기반한 값[ATR]) 를 비교한다. 이것은 거래가 유의미한 가격 이동 기간에만 이루어지는 것을 보장하고, 낮은 운동량 조건을 필터링한다.
성수 필터 (선택): 현재 거래량이 장기 평균을 초과하는지 확인하고, 긍정적인 단기 거래량 변화를 보여줍니다. 이것은 강력한 시장 참여를 확인하고, 가짜 돌파의 위험을 감소시킵니다.
필터를 뚫고 (선택): 가격이 최근 최고/하위점을 돌파 (구매) 하거나 돌파 (판매) 하도록 요구하며, 신호가 시장 구조의 변화와 일치하는지 확인한다.
스마트 자금 개념 (CHoCH/BOS):
AI 트렌드 디스플레이: 다른 시간 프레임의 트렌드 방향, 동력 및 변동률을 결합한 트렌드 스코어 (ATR) 계산. 0.5 이상의 스코어는 “상향” 트렌드를 나타내고, -0.5 이하의 스코어는 “하향” 트렌드를 나타냅니다. 그렇지 않으면 “중립”입니다.
동적 트렌드 선사용자 정의 기간 (shortTrendPeriod, longTrendPeriod) 에 따라 최근 흔들리는 낮은 점과 높은 점의 지원 및 저항 선을 그리십시오. 이 선은 시장 조건에 따라 적응하고 트렌드 강도에 따라 색을 띠습니다.
다중 시간 주기 트렌드 동적 양 거래 전략에는 다음과 같은 몇 가지 중요한 장점이 있습니다.
가짜 신호를 줄여라이 전략은 트렌드, 동력, 거래량, 그리고 브레이크 필터의 일관성을 요구함으로써 변동성 또는 낮은 신뢰도 시장에서의 거래를 최소화합니다.
시장에 적응하는 것ATR 기반의 동적 하락값은 변동성 동력에 따라 조정될 수 있으며, 이는 시그널이 트렌드 시장과 간격 시장에서 관련성을 유지하도록 보장합니다.
의사결정을 간소화하기: AI 디스플레이는 복잡한 다중 시간 주기 데이터를 사용자 친화적인 표로 통합하여 수동 분석의 필요성을 제거합니다.
똑똑한 자금의 활용:CHoCH와 BOS 신호 캡처 기관 가격 동작 모드, 거래자에게 역전 및 지속을 식별 할 수있는 이점을 제공합니다.
시각의 명확함전략: 중요한 수준, 신호 및 트렌드 라인을 표시하여 시장 구조를 명확하게 보이게하고 거래자가 가격 행동을 더 잘 이해할 수 있도록 도와줍니다.
리스크 관리 내장사전 정의된 스톱 및 스로드 레벨은 장기 거래의 성공에 중요한 규율적인 위험 관리를 촉진합니다.
조기 경보“준비해” 신호를 통해, 거래자는 설정이 완전히 개발되기 전에 경고를 받을 수 있으며, 더 많은 준비 및 계획 시간을 허용한다.
이 전략은 많은 장점이 있지만, 몇 가지 잠재적인 위험도 있습니다.
변수 최적화 함수: 과잉 최적화 전략의 매개 변수는 곡선 적합으로 이어질 수 있으며, 미래 시장 조건에서 좋지 않은 성능을 나타낼 수 있다. 해결책은 여러 시장과 시간 주기에서 광범위한 회귀를 통해 안정적인 매개 변수 집합을 찾는 것이다.
지연 신호다중 필터의 사용으로 인해 신호가 가격 움직임에 비해 지연되어 때로는 이상적인 입구 지점을 놓치게 될 수 있습니다. 해결책은 중심축 길이 및 동력 스값과 같은 시장 속도에 더 민감한 파라미터를 조정하는 것입니다.
잘못된 트렌드 식별: 높은 변동성이나 방향성이 없는 시장에서 트렌드 평가는 정확하지 않을 수 있다. 해결책은 이러한 조건에서 거래를 줄이거나 더 엄격한 필터 요구 사항을 추가하는 것이다.
재정 관리 결함: 고정된 스톱 및 스톱 손실 포인트는 모든 시장 조건에 적합하지 않을 수 있습니다. 해결책은 현재의 변동성에 맞게 ATR 기반의 값으로 조정하는 것입니다.
컴퓨터 집약전략의 복잡성은 일부 플랫폼에서, 특히 많은 역사 데이터를 분석할 때, 성능 문제를 일으킬 수 있다. 해결책은 재검토 시간 범위를 제한하거나 중요하지 않은 계산을 간소화하는 것이다.
데이터 의존: 전략은 정확한 다중 시간 주기 데이터에 의존하며, 이는 모든 거래 환경에서 사용되지 않을 수 있습니다. 해결책은 코드에서 표시된 로컬 값을 계산하는 것과 같은 신뢰할 수 있는 대안을 구현하는 것입니다.
유동성이 높은 시장에 대한 선호전략은 유동성이 낮은 시장에서 더 많은 잘못된 신호를 일으킬 수 있습니다. 해결책은 주요 통화 쌍, 널리 보유 된 주식 및 주요 암호화폐에 집중하는 것입니다.
이 전략은 다음과 같은 방향으로 더 개선될 수 있습니다.
적응 변수: 역사적인 변동률 데이터에 기반한 동력 하락의 최적화와 같은 자동 조정 매개 변수를 구현한다. 이것은 다양한 시장 조건에서 전략의 적응성을 향상시킬 수 있다.
기계학습 통합: 기계 학습 알고리즘을 적용하여 최적의 파라미터 조합을 식별하거나 특정 시장 조건에서 전략의 성능을 예측합니다. 이는 전략의 “AI” 측면을 더 강화하기 위해 역사적인 성능 데이터를 분석하여 수행 할 수 있습니다.
시장 감정 지표외부 시장 감정 데이터를 추가하여 거래 결정을 위해 더 넓은 배경을 제공합니다. 이것은 극단적인 시장 조건에서 거래를 피하는 전략을 도울 수 있습니다.
시간 필터: 시장의 변동 시간 패턴에 기반한 필터를 추가하고, 알려진 낮은 변동 기간 (아시아 세션 중반과 같은) 에 거래하는 것을 피하십시오. 이것은 낮은 품질의 신호의 수를 줄일 수 있습니다.
상관관계 분석: 거래와 관련 시장의 움직임이 일치하는지 확인하기 위해 자산 간 연관성 검사를 추가하십시오. (예: EUR / USD 거래시 USD 지수를 고려하십시오). 이것은 추가적인 신호 확인을 제공합니다.
자금 관리 최적화: 변동성에 기반한 동적 스톱/로스 레벨을 구현하고, 계좌 성장에 따라 포지션 규모를 조정하는 것과 같은 자금 관리 규칙을 추가한다. 이것은 장기적인 위험 조정 후 수익을 향상시킬 것이다.
성능 최적화: 코드를 단순화하여 불필요한 계산을 줄이고, 특히 트렌드 라인 및 테이블 디스플레이에서, 실시간 거래에서 전략의 응답성을 향상시킵니다.
데이터 무관성: 부강한 전략으로 데이터 중단이나 누락된 값을 더 우아하게 처리하여, 바람직하지 않은 조건에서 융통성을 보장한다.
다중 시간 주기의 트렌드 동적 거래 전략은 전통적인 기술 분석, 스마트 펀드 개념 및 고유 한 AI 동적 트렌드 분석을 결합한 포괄적 인 거래 시스템을 제공합니다. 그 강점은 다층적인 필터링 및 확인 메커니즘으로 거래 신호를 생성하는 것을 보장합니다.
이 전략의 특히 혁신적인 측면은 다중 시간 주기 트렌드 정보를 직관적인 시각적 디스플레이로 통합하여 거래자가 복잡한 수동 분석 없이 시장 상황을 신속하게 평가할 수 있도록하는 것입니다. 역동적인 지지 저항선과 핵심 구조 레벨의 가시성은 이러한 편의성을 더욱 강화합니다.
CHoCH와 BOS 개념을 지능적으로 결합하여, 이 전략은 시장 심리의 미세한 변화를 포착할 수 있으며, 이는 일반적으로 추세가 지속되거나 잠재적인 반향을 나타냅니다. ATR의 절댓값 조정 사용은 전략이 다양한 변동 조건에 적응할 수 있도록 보장하여 여러 가지 시장 환경에 적합합니다.
몇 가지 위험과 한계가 있음에도 불구하고, 이미 강력한 시스템은 제안된 최적화 조치를 통해 더욱 강화될 수 있습니다. 위험 관리 원칙을 현명하게 적용하고 특정 거래 목표와 위험 용도에 따라 매개 변수를 조정하는 전략은 모든 거래자의 도구 상자에 귀중한 도구가 될 잠재력을 가지고 있습니다.
결국, 모든 거래 전략과 마찬가지로, 성공은 적절한 변수 최적화, 규율적인 실행, 건전한 위험 관리, 그리고 시장의 역동성에 대한 깊은 이해에 달려 있습니다.
/*backtest
start: 2024-05-15 00:00:00
end: 2025-05-13 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/
//@version=5
strategy("PowerHouse SwiftEdge AI v2.10 Strategy", overlay=true, calc_on_every_tick=true)
// Inputs med fleksible indstillinger
length = input.int(5, "Pivot Length", minval=1, maxval=20, step=1, tooltip="Number of bars to identify pivot highs and lows.")
momentum_threshold_base = input.float(0.01, "Base Momentum Threshold (%)", minval=0.001, maxval=1.0, step=0.001, tooltip="Base percentage change for signals.")
tp_points = input.int(10, "Take Profit (points)", minval=5, maxval=500, step=5)
sl_points = input.int(10, "Stop Loss (points)", minval=5, maxval=500, step=5)
min_signal_distance = input.int(5, "Min Signal Distance (bars)", minval=1, maxval=50, step=1)
tp_box_height = input.float(0.5, "TP Box Height % (Optional)", minval=0.1, maxval=2.0, step=0.1)
pre_momentum_factor_base = input.float(0.5, "Base Pre-Momentum Factor", minval=0.1, maxval=1.0, step=0.1, tooltip="Base factor for Get Ready signals.")
shortTrendPeriod = input.int(30, title="Short Trend Period", minval=10, maxval=100)
longTrendPeriod = input.int(100, title="Long Trend Period", minval=50, maxval=200)
// Brugerdefinerede filtre
use_momentum_filter = input.bool(true, "Use Momentum Filter", group="Signal Filters", tooltip="Require price change to exceed momentum threshold.")
use_trend_filter = input.bool(true, "Use Higher Timeframe Trend Filter", group="Signal Filters", tooltip="Require alignment with the selected higher timeframe trend.")
higher_tf_choice = input.string("60", "Higher Timeframe", options=["60", "240", "D"], group="Signal Filters", tooltip="Choose the timeframe for the higher timeframe filter.")
use_lower_tf_filter = input.bool(true, "Use Lower Timeframe Filter", group="Signal Filters", tooltip="Prevent signals against the selected lower timeframe trend.")
lower_tf_choice = input.string("60", "Lower Timeframe", options=["60", "240", "D"], group="Signal Filters", tooltip="Choose the timeframe for the lower timeframe filter.")
use_volume_filter = input.bool(false, "Use Volume Filter", group="Signal Filters", tooltip="Require volume above average (optional).")
use_breakout_filter = input.bool(false, "Use Breakout Filter", group="Signal Filters", tooltip="Require price to break previous high/low (optional).")
show_get_ready = input.bool(true, "Show Get Ready Signals", group="Signal Filters", tooltip="Enable or disable Get Ready signals.")
restrict_repeated_signals = input.bool(false, "Restrict Repeated Signals", group="Signal Filters", tooltip="Prevent multiple signals in the same trend direction until trend changes.")
restrict_trend_tf_choice = input.string("60", "Restrict Trend Timeframe", options=["60", "240", "D"], group="Signal Filters", tooltip="Choose the timeframe to check trend for restricting repeated signals.")
enable_ai_analysis = input.bool(true, "Enable AI Market Analysis", group="AI Market Analysis", tooltip="Show AI predictions for future trends across timeframes.")
ai_table_position = input.string("Bottom Center", "AI Market Analysis Table Position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group="AI Market Analysis", tooltip="Choose the position of the AI Market Analysis table.")
// Ekstra inputs til valgfrie filtre
volumeLongPeriod = input.int(50, "Long Volume Period", minval=10, maxval=100, group="Volume Filter Settings")
volumeShortPeriod = input.int(5, "Short Volume Period", minval=1, maxval=20, group="Volume Filter Settings")
breakoutPeriod = input.int(5, "Breakout Period", minval=1, maxval=50, group="Breakout Filter Settings")
// Funktion til at konvertere streng til position
f_getTablePosition(position_string) =>
switch position_string
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
=> position.middle_right // Standard fallback
// AI-drevet adaptiv signaljustering med ATR
atr_raw = ta.atr(14)
atr = na(atr_raw) and bar_index > 0 ? (high - low) : atr_raw
volatility_factor = atr / close
momentum_threshold = momentum_threshold_base * (1 + volatility_factor * 2)
pre_momentum_factor = pre_momentum_factor_base * (1 - volatility_factor * 0.5)
pre_momentum_threshold = momentum_threshold * pre_momentum_factor
// Raw CVD-beregning
var float raw_cvd = 0.0
delta_volume = close > close[1] ? volume : close < close[1] ? -volume : 0
raw_cvd := raw_cvd + delta_volume
// Volatility Context baseret på absolut CVD
cvd_level = math.abs(raw_cvd) < 10000 ? "Low" : math.abs(raw_cvd) < 50000 ? "Medium" : "High"
cvd_color = raw_cvd > 0 ? color.lime : raw_cvd < 0 ? color.red : color.yellow
// Beregn prisændring (momentum)
price_change = ((close - close[1]) / close[1]) * 100
// Find højder og lavpunkter
pivot_high = ta.pivothigh(high, length, length)
pivot_low = ta.pivotlow(low, length, length)
// Variabler til at gemme seneste højder og lavpunkter
var float last_high = na
var float last_low = na
if not na(pivot_high)
last_high := pivot_high
if not na(pivot_low)
last_low := pivot_low
// Variabler til signalstyring
var float choch_sell_level = na
var float choch_buy_level = na
var float bos_sell_level = na
var float bos_buy_level = na
var float tp_sell_level = na
var float tp_buy_level = na
var int last_signal_bar = -min_signal_distance - 1
var string last_signal = "Neutral"
var int last_trend = 0 // Sporer den sidste trendretning for restrict_repeated_signals
// Multi-tidsramme trendanalyse med robust fallback
// Beregn EMA og VWAP for hver tidsramme
ema60_raw = request.security(syminfo.tickerid, "60", ta.ema(close, 20), lookahead=barmerge.lookahead_on)
vwap60_raw = request.security(syminfo.tickerid, "60", ta.vwap(hlc3), lookahead=barmerge.lookahead_on)
ema240_raw = request.security(syminfo.tickerid, "240", ta.ema(close, 20), lookahead=barmerge.lookahead_on)
vwap240_raw = request.security(syminfo.tickerid, "240", ta.vwap(hlc3), lookahead=barmerge.lookahead_on)
emaD_raw = request.security(syminfo.tickerid, "D", ta.ema(close, 20), lookahead=barmerge.lookahead_on)
vwapD_raw = request.security(syminfo.tickerid, "D", ta.vwap(hlc3), lookahead=barmerge.lookahead_on)
// Lokale EMA og VWAP som fallback
local_ema = ta.ema(close, 20)
local_vwap = ta.vwap(hlc3)
// Fallback for manglende data
ema60 = na(ema60_raw) ? local_ema : ema60_raw
vwap60 = na(vwap60_raw) ? local_vwap : vwap60_raw
ema240 = na(ema240_raw) ? local_ema : ema240_raw
vwap240 = na(vwap240_raw) ? local_vwap : vwap240_raw
emaD = na(emaD_raw) ? local_ema : emaD_raw
vwapD = na(vwapD_raw) ? local_vwap : vwapD_raw
// Trendbestemmelse (1 = op, -1 = ned, 0 = neutral)
trend60 = close > ema60 and close > vwap60 ? 1 : close < ema60 and close < vwap60 ? -1 : 0
trend240 = close > ema240 and close > vwap240 ? 1 : close < ema240 and close < vwap240 ? -1 : 0
trendD = close > emaD and close > vwapD ? 1 : close < emaD and close < vwapD ? -1 : 0
// AI-Trend Strength (-100 til +100)
trend_strength_raw = trend60 + trend240 + trendD
trend_strength = (trend_strength_raw / 3) * 100
// AI Confidence (simuleret succesrate)
var float ai_confidence = 50.0
if trend_strength_raw == 3 or trend_strength_raw == -3
ai_confidence := 90.0
else if trend_strength_raw >= 2 or trend_strength_raw <= -2
ai_confidence := 75.0
else
ai_confidence := 60.0
// Filterbetingelser
// Dynamisk valg af higher timeframe trend (til signalfiltrering)
var int higher_tf_trend = 0
switch higher_tf_choice
"60" => higher_tf_trend := trend60
"240" => higher_tf_trend := trend240
"D" => higher_tf_trend := trendD
bullish_trend_ok = higher_tf_trend == 1
bearish_trend_ok = higher_tf_trend == -1
// Dynamisk valg af lower timeframe trend (til signalfiltrering)
var int lower_tf_trend = 0
switch lower_tf_choice
"60" => lower_tf_trend := trend60
"240" => lower_tf_trend := trend240
"D" => lower_tf_trend := trendD
lower_tf_bullish = lower_tf_trend == 1
lower_tf_bearish = lower_tf_trend == -1
lower_tf_not_neutral = lower_tf_trend != 0
// Dynamisk valg af trend-tidsramme til restrict_repeated_signals
var int restrict_tf_trend = 0
switch restrict_trend_tf_choice
"60" => restrict_tf_trend := trend60
"240" => restrict_tf_trend := trend240
"D" => restrict_tf_trend := trendD
volAvg50 = ta.sma(volume, volumeLongPeriod)
volShort = ta.sma(volume, volumeShortPeriod)
volCondition = volume > volAvg50 and ta.change(volShort) > 0
highestBreakout = ta.highest(high, breakoutPeriod)
lowestBreakout = ta.lowest(low, breakoutPeriod)
// CHoCH og BOS definitioner
choch_sell = ta.crossunder(low, last_high) and close < open
choch_buy = ta.crossover(high, last_low) and close > open
bos_sell = ta.crossunder(low, last_low[1]) and low < last_low[1] and close < open
bos_buy = ta.crossover(high, last_high[1]) and high > last_high[1] and close > open
// Signalbetingelser med valgbare filtre
early_sell_signal = use_momentum_filter ? price_change < -momentum_threshold : true
early_buy_signal = use_momentum_filter ? price_change > momentum_threshold : true
sell_trend_ok = use_trend_filter ? bearish_trend_ok : true
buy_trend_ok = use_trend_filter ? bullish_trend_ok : true
sell_lower_tf_ok = use_lower_tf_filter ? (not lower_tf_bullish and lower_tf_not_neutral) : true
buy_lower_tf_ok = use_lower_tf_filter ? (not lower_tf_bearish and lower_tf_not_neutral) : true
sell_volume_ok = use_volume_filter ? volCondition : true
buy_volume_ok = use_volume_filter ? volCondition : true
sell_breakout_ok = use_breakout_filter ? close < lowestBreakout[1] : true
buy_breakout_ok = use_breakout_filter ? close > highestBreakout[1] : true
// Logik for at begrænse gentagne signaler baseret på restrict_tf_trend
sell_allowed = not restrict_repeated_signals or (last_signal != "Sell" or (last_signal == "Sell" and restrict_tf_trend != last_trend and restrict_tf_trend != -1))
buy_allowed = not restrict_repeated_signals or (last_signal != "Buy" or (last_signal == "Buy" and restrict_tf_trend != last_trend and restrict_tf_trend != 1))
sell_condition = early_sell_signal and (bar_index - last_signal_bar >= min_signal_distance) and sell_trend_ok and sell_lower_tf_ok and sell_volume_ok and sell_breakout_ok and sell_allowed
buy_condition = early_buy_signal and (bar_index - last_signal_bar >= min_signal_distance) and buy_trend_ok and buy_lower_tf_ok and buy_volume_ok and buy_breakout_ok and buy_allowed
get_ready_sell = use_momentum_filter ? (price_change < -pre_momentum_threshold and price_change > -momentum_threshold) : true and (bar_index - last_signal_bar >= min_signal_distance) and sell_trend_ok and sell_lower_tf_ok and sell_volume_ok and sell_breakout_ok
get_ready_buy = use_momentum_filter ? (price_change > pre_momentum_threshold and price_change < momentum_threshold) : true and (bar_index - last_signal_bar >= min_signal_distance) and buy_trend_ok and buy_lower_tf_ok and buy_volume_ok and buy_breakout_ok
// Strategy logic
if buy_condition
strategy.entry("Long", strategy.long)
strategy.exit("TP/SL Long", "Long", limit=close + tp_points, stop=close - sl_points)
label.new(bar_index, low, "Buy", color=color.green, style=label.style_label_up, textcolor=color.white)
tp_buy_level := high + tp_points
last_signal := "Buy"
last_signal_bar := bar_index
last_trend := restrict_tf_trend
if sell_condition
strategy.entry("Short", strategy.short)
strategy.exit("TP/SL Short", "Short", limit=close - tp_points, stop=close + sl_points)
label.new(bar_index, high, "Sell", color=color.red, style=label.style_label_down, textcolor=color.white)
tp_sell_level := low - tp_points
last_signal := "Sell"
last_signal_bar := bar_index
last_trend := restrict_tf_trend
// Plot Get Ready signals
if show_get_ready and get_ready_sell
label.new(bar_index, high, "Get Ready SELL", color=color.orange, style=label.style_label_down, textcolor=color.black, size=size.small)
if show_get_ready and get_ready_buy
label.new(bar_index, low, "Get Ready BUY", color=color.yellow, style=label.style_label_up, textcolor=color.black, size=size.small)
// Plot CHoCH og BOS som fulde linjer med AI-agtige farver
var line choch_sell_line = na
var line choch_buy_line = na
var line bos_sell_line = na
var line bos_buy_line = na
// Trendlinjer med bufferkontrol og AI-laser-look
var line sup = na
var line res = na
if barstate.islast
float lowest_y2 = 60000
int lowest_x2 = 0
float highest_y2 = 0
int highest_x2 = 0
// Begræns lookback til max 2000 bars for at undgå bufferfejl
int maxShortBars = math.min(math.min(shortTrendPeriod, bar_index), 2000)
for i = 1 to maxShortBars
if low[i] < lowest_y2
lowest_y2 := low[i]
lowest_x2 := i
if high[i] > highest_y2
highest_y2 := high[i]
highest_x2 := i
float lowest_y1 = 60000
int lowest_x1 = 0
float highest_y1 = 0
int highest_x1 = 0
// Begræns lookback til max 2000 bars for at undgå bufferfejl
int maxLongBars = math.min(math.min(longTrendPeriod, bar_index), 2000)
for j = shortTrendPeriod + 1 to maxLongBars
if low[j] < lowest_y1
lowest_y1 := low[j]
lowest_x1 := j
if high[j] > highest_y1
highest_y1 := high[j]
highest_x1 := j
int trendStrength = trend_strength_raw
// Plot niveauer
plot(choch_sell_level, title="Last High at CHoCH", color=color.aqua, style=plot.style_circles, linewidth=1, trackprice=false)
plot(choch_buy_level, title="Last Low at CHoCH", color=color.lime, style=plot.style_circles, linewidth=1, trackprice=false)
plot(bos_sell_level, title="Last Low at BOS", color=color.fuchsia, style=plot.style_circles, linewidth=1, trackprice=false)
plot(bos_buy_level, title="Last High at BOS", color=color.teal, style=plot.style_circles, linewidth=1, trackprice=false)
plot(tp_sell_level, title="TP Sell", color=color.red, style=plot.style_circles, linewidth=1, trackprice=false)
plot(tp_buy_level, title="TP Buy", color=color.green, style=plot.style_circles, linewidth=1, trackprice=false)
plot(last_high, title="Last High", color=color.red, style=plot.style_histogram, linewidth=1, trackprice=true)
plot(last_low, title="Last Low", color=color.green, style=plot.style_histogram, linewidth=1, trackprice=true)
// AI Markedsanalyse - Beregn data uanset betingelse
momentum_1h = request.security(syminfo.tickerid, "60", close - close[3], lookahead=barmerge.lookahead_on)
momentum_4h = request.security(syminfo.tickerid, "240", close - close[3], lookahead=barmerge.lookahead_on)
momentum_d = request.security(syminfo.tickerid, "D", close - close[3], lookahead=barmerge.lookahead_on)
// Beregn ATR og SMA(ATR) for hver tidsramme
atr_1h = request.security(syminfo.tickerid, "60", ta.atr(14), lookahead=barmerge.lookahead_on)
atr_4h = request.security(syminfo.tickerid, "240", ta.atr(14), lookahead=barmerge.lookahead_on)
atr_d = request.security(syminfo.tickerid, "D", ta.atr(14), lookahead=barmerge.lookahead_on)
sma_atr_1h = request.security(syminfo.tickerid, "60", ta.sma(ta.atr(14), 20), lookahead=barmerge.lookahead_on)
sma_atr_4h = request.security(syminfo.tickerid, "240", ta.sma(ta.atr(14), 20), lookahead=barmerge.lookahead_on)
sma_atr_d = request.security(syminfo.tickerid, "D", ta.sma(ta.atr(14), 20), lookahead=barmerge.lookahead_on)
// Lokale ATR og SMA(ATR) som fallback
local_atr = ta.atr(14)
local_sma_atr = ta.sma(ta.atr(14), 20)
// Fallback for manglende data
volatility_1h = na(atr_1h) ? local_atr : atr_1h
volatility_4h = na(atr_4h) ? local_atr : atr_4h
volatility_d = na(atr_d) ? local_atr : atr_d
volatility_avg_1h = na(sma_atr_1h) ? local_sma_atr : sma_atr_1h
volatility_avg_4h = na(sma_atr_4h) ? local_sma_atr : sma_atr_4h
volatility_avg_d = na(sma_atr_d) ? local_sma_atr : sma_atr_d
momentum_1h := na(momentum_1h) ? 0 : momentum_1h
momentum_4h := na(momentum_4h) ? 0 : momentum_4h
momentum_d := na(momentum_d) ? 0 : momentum_d
// Analyse baseret på trend, momentum og volatilitet
score_1h = trend60 + (momentum_1h > 0 ? 0.5 : momentum_1h < 0 ? -0.5 : 0) + (volatility_1h > volatility_avg_1h ? 0.5 : 0)
score_4h = trend240 + (momentum_4h > 0 ? 0.5 : momentum_4h < 0 ? -0.5 : 0) + (volatility_4h > volatility_avg_4h ? 0.5 : 0)
score_d = trendD + (momentum_d > 0 ? 0.5 : momentum_d < 0 ? -0.5 : 0) + (volatility_d > volatility_avg_d ? 0.5 : 0)
// Forudsigelser
pred_1h = score_1h > 0.5 ? "Up" : score_1h < -0.5 ? "Down" : "Neutral"
pred_4h = score_4h > 0.5 ? "Up" : score_4h < -0.5 ? "Down" : "Neutral"
pred_d = score_d > 0.5 ? "Up" : score_d < -0.5 ? "Down" : "Neutral"
// Futuristisk AI-Trend Dashboard
var table trendTable = table.new(position.top_right, columns=2, rows=6, bgcolor=color.new(color.black, 50), border_width=2, border_color=color.new(color.teal, 20))
table.cell(trendTable, 0, 0, "AI-Trend Matrix v2.10", text_color=color.new(color.aqua, 0), bgcolor=color.new(color.navy, 60))
table.cell(trendTable, 1, 0, "", bgcolor=color.new(color.navy, 60))
table.merge_cells(trendTable, 0, 0, 1, 0)
table.cell(trendTable, 0, 1, "Trend Strength", text_color=color.white)
table.cell(trendTable, 1, 1, str.tostring(math.round(trend_strength)), text_color=trend_strength > 0 ? color.rgb(0, math.min(255, trend_strength * 2.55), 0) : color.rgb(math.min(255, math.abs(trend_strength) * 2.55), 0, 0))
table.cell(trendTable, 0, 2, "AI Confidence", text_color=color.white)
table.cell(trendTable, 1, 2, str.tostring(ai_confidence) + "%", text_color=color.teal)
table.cell(trendTable, 0, 3, "AI Calibration", text_color=color.white)
table.cell(trendTable, 1, 3, "CVD: " + str.tostring(math.round(raw_cvd)) + " (" + cvd_level + ")", text_color=cvd_color)
table.cell(trendTable, 0, 4, "1H", text_color=color.white)
table.cell(trendTable, 1, 4, trend60 == 1 ? "Up" : trend60 == -1 ? "Down" : "Neutral", text_color=trend60 == 1 ? color.lime : trend60 == -1 ? color.fuchsia : color.yellow)
table.cell(trendTable, 0, 5, "4H", text_color=color.white)
table.cell(trendTable, 1, 5, trend240 == 1 ? "Up" : trend240 == -1 ? "Down" : "Neutral", text_color=trend240 == 1 ? color.lime : trend240 == -1 ? color.fuchsia : color.yellow)
// Tabel for AI Markedsanalyse
if enable_ai_analysis
var table ai_table = table.new(f_getTablePosition(ai_table_position), columns=4, rows=2, bgcolor=color.new(color.black, 50), border_width=2, border_color=color.new(color.teal, 20))
table.cell(ai_table, 0, 0, "AI Market Analysis", text_color=color.new(color.aqua, 0), bgcolor=color.new(color.navy, 60))
table.cell(ai_table, 1, 0, "1H", text_color=color.white)
table.cell(ai_table, 2, 0, "4H", text_color=color.white)
table.cell(ai_table, 3, 0, "1D", text_color=color.white)
table.cell(ai_table, 0, 1, "Prediction", text_color=color.white)
table.cell(ai_table, 1, 1, pred_1h, text_color=pred_1h == "Up" ? color.lime : pred_1h == "Down" ? color.fuchsia : color.yellow)
table.cell(ai_table, 2, 1, pred_4h, text_color=pred_4h == "Up" ? color.lime : pred_4h == "Down" ? color.fuchsia : color.yellow)
table.cell(ai_table, 3, 1, pred_d, text_color=pred_d == "Up" ? color.lime : pred_d == "Down" ? color.fuchsia : color.yellow)
// Debug alerts for null data
if na(ema60) or na(vwap60)
alert("Warning: 60-minute timeframe data is null!", alert.freq_once_per_bar)
if na(ema240) or na(vwap240)
alert("Warning: 240-minute timeframe data is null!", alert.freq_once_per_bar)
if na(emaD) or na(vwapD)
alert("Warning: Daily timeframe data is null!", alert.freq_once_per_bar)