
다차원 자기 적응 이동 평균 매트릭스와 ATR 동적 정밀 거래 전략은 급변하는 시장 조건에 맞게 설계된 고급 정량 거래 시스템이다. 이 전략의 핵심은 여러 종류의 이동 평균과 ATR (평균 실제 파도) 필터를 결합하여 매우 유연하고 자기 적응하는 거래 매트릭스를 형성하는 것이다. 시장의 추세와 변동성을 정확하게 포착함으로써 이 전략은 고주파 거래 환경에서 높은 확률의 입점과 출구를 식별할 수 있으며, 동시에 엄격한 위험 제어 조치를 시행한다.
이 전략의 핵심은 다음과 같은 몇 가지 핵심 요소의 협동적인 작업에 기반합니다.
고차원 이동 평균 행렬전략은 SMA, EMA, SMMA, HMA, TEMA, WMA, VWMA, ZLEMA, ALMA, KAMA 및 DEMA를 포함하여 최대 11 가지의 다른 유형의 이동 평균을 구현합니다. 각각의 이동 평균은 고유한 계산 방법과 반응 특성을 가지고 있으며 시장 조건에 따라 유연하게 선택할 수 있습니다. 시스템은 두 가지 이동 평균을 ((고속 및 느린) 을 주요 트렌드 지표로 사용하고, 그들의 교차와 상대적인 위치가 기본 거래 신호를 생성합니다.
ATR 기반의 위험 관리전략: ATR 지표를 사용하여 시장의 변동성을 측정하고 여러 가지 측면에서 적용합니다.
다중 시간 프레임 트렌드 필터전략: 더 높은 시간 프레임 ((15분) 의 이동 평균 트렌드를 검색하여 신호 신뢰성을 강화하고 거래 방향이 더 큰 시장 트렌드와 일치하도록합니다.
거래량 및 시간 창 검증: 거래는 최소 거래량 요구사항을 충족하고 거래량이 돌파되는 경우에만 실행되며 미리 정의된 거래 시간 창 내에서 거래 품질을 더욱 향상시킵니다.
신호 생성 논리:
합성 탈퇴 논리이 전략은 3층의 탈퇴 메커니즘을 사용한다. 고정된 스톱로스 (ATR의 배수), 목표 수익 (ATR의 배수), 추적된 스톱로스 (ATR에 기반한 동적 조정) 을 사용한다.
이 전략의 코드를 분석하면 다음과 같은 중요한 장점을 찾을 수 있습니다.
뛰어난 적응력: HMA에서 KAMA에 이르기까지 다양한 이동 평균 유형을 전환하여 전략은 다른 시장 조건에 적응할 수 있습니다. 이러한 유연성은 거래자가 전체 전략을 다시 작성하지 않고 현재 시장 환경에 따라 최적의 지표를 선택할 수 있습니다.
동적 위험 관리ATR 기반의 위험 제어 메커니즘은 시장의 변동성에 따라 자동으로 중지 손실과 수익 목표가 조정되는 것을 보장합니다. 이 방법은 변동성이 높은 시장에서 더 나은 보호를 제공하면서 추세 시장에서 더 많은 이익을 잡을 수 있습니다.
다층 신호 필터링이동 평균 크로스, 거래량 분석, 변동성 하락 및 다중 시간 프레임 트렌드 필터링을 결합하여 전략은 오류 신호를 효과적으로 줄이고 거래 품질을 향상시킵니다. 특히 15 분 시간 프레임의 트렌드 필터링 기능은 역행 거래의 가능성을 크게 감소시킵니다.
정확한 입학 조건이 전략은 기술 지표의 교차에만 의존하지 않고, 가격과 느린 이동 평균 사이의 충분한 ATR 거리를 유지하도록 요구합니다. 이것은 가로 시장에서 자주 거래되는 것을 피하고 가짜 돌파구로 인한 손실을 줄이는 데 도움이됩니다.
투명성 있는 성능 모니터링: 내장된 디스플레이 패널은 현재 이익/손실, 주식, ATR (원본값과 비율) 및 이동 평균 사이의 격차를 포함한 주요 성과 지표의 실시간 표시를 제공하여 거래자가 전략 상태를 언제든지 평가할 수 있도록합니다.
이 전략은 훌륭하게 설계되었지만, 다음과 같은 잠재적인 위험들이 있습니다.
변수 최적화 함수전략에는 많은 변수가 포함되어 있습니다. 이동 평균 유형 및 주기, ATR 주기 및 곱하기 등 과잉 최적화로 인해 곡선 적합성이 발생하여 전략이 실판 거래에서 좋지 않은 성능을 발휘 할 수 있습니다. 해결책은 안정적인 시장 간 및 기간 간 테스트를 수행하여 변수를 과도하게 조정하는 것을 피하는 것입니다.
급격한 반전 위험: ATR 동적 스톱을 사용함에도 불구하고, 시장이 급격히 반전되면 (중요한 뉴스 발표 이후) 스톱이 터지기 전에 가격이 급등하여 예상 이상의 손실을 초래할 수 있습니다. 추가적인 야간 위험 관리를 시행하거나 높은 변동성 사건 전에 거래를 중단하는 것이 좋습니다.
신호 지연: 모든 이동 평균은 본질적으로 지연적입니다. HMA 또는 ZLEMA와 같은 낮은 지연 변이조차도 빠른 시장에서 이상적인 진입 지점을 놓칠 수 있습니다. 기존의 신호 시스템을 보완하기 위해 운동량이나 가격 행동 지표를 결합하는 것이 고려 될 수 있습니다.
거래량 의존성전략: 거래량이 급격히 증가할 때 신호를 냅니다. 그러나 특정 시장이나 시간 동안 거래량이 오해 할 수 있습니다. 거래량 필터를 조정하거나 특정 시장 조건에서이 기능을 비활성화하는 것이 필요하면 고려하십시오.
시간 창 제한: 지정된 거래 시간 창은 중요한 야간 또는 이른 거래 기회를 놓칠 수 있습니다. 특정 시장의 가장 활발한 시간에 따라 거래 시간을 조정하는 것이 좋습니다.
코드를 분석한 후, 몇 가지 최적화 방향이 있습니다:
적응 변수 조정현재 전략은 고정된 파라미터 설정을 사용한다. 고급 최적화는 시장 상태 (트렌드, 변동, 범위) 에 따라 자동으로 조정되는 파라미터를 구현한다. 예를 들어, 높은 변동 기간 동안 ATR 곱수를 자동으로 증가시킬 수 있거나 다른 시장 환경에서 이동 평균 유형을 전환할 수 있다.
기계학습 모델을 통합합니다.: 현재 시장 조건에서 어떤 이동 평균 유형이 가장 잘 수행 될 수 있는지 예측하기 위해 기계 학습 계층을 도입하여 최적의 이동 평균 조합을 자동으로 선택합니다. 이것은 역사적 데이터에서 다른 지표의 상대적 성능을 분석하여 수행 할 수 있습니다.
개선의 트렌드를 파악하는 것기존의 15분 트렌드 필터 외에도 더 복잡한 트렌드 식별 알고리즘, 예를 들어 허스트 지수 또는 방향 운동 지표 (DMI) 를 더 정확하게 트렌드 강도 및 지속성을 결정할 수 있습니다.
탈퇴 전략 강화현재의 탈퇴 전략은 트렌드 라인 브레이크, 핵심 지지/저항 지점, 또는 급격한 변동성 등의 시장 구조에 기반한 탈퇴 신호를 추가하여 더욱 최적화 할 수 있습니다. 이것은 트렌드 종료 전에 수익을 고정하는 데 도움이 될 수 있습니다.
리스크 조정 포지션 규모: 현재 변동성과 계좌 자금에 기반한 동적인 포지션 규모 조정을 구현하는 것, 일정한 거래 수를 사용하는 것이 아닙니다. 예를 들어, 높은 변동성 동안 포지션을 줄이고, 낮은 변동성 동안 포지션을 적당히 증가시켜 리스크 수익률을 최적화합니다.
관련 시장 필터링: 관련 시장을 모니터링하여 신호 품질을 향상 시키십시오 (주식 지수 거래시 VIX와 같은) 또는 자산 간 연관성을 향상 시키십시오. 관련 시장이 일관된 방향적 움직임을 표시하면 거래의 신뢰성을 높일 수 있습니다.
다차원 자기 적응 이동 평균 매트릭스와 ATR 동적 정밀 거래 전략은 포괄적이고 진보된 양적 거래 방법을 대표한다. 여러 이동 평균 유형의 장점과 엄격한 ATR 기반의 위험 통제를 결합하여 이 전략은 좋은 위험 관리를 유지하면서도 다양한 시장 조건에 적응할 수 있다. 여러 계층의 신호 필터링 메커니즘, 정밀한 입시 조건 및 포괄적 인 퇴출 논리는 함께 높은 확률의 거래 기회를 식별 할 수있는 강력한 시스템을 만듭니다.
이 전략의 진정한 가치는 특정 시장과 개인 위험 선호도에 따라 트레이더가 맞춤화 할 수 있는 유연성과 적응성입니다. 제안된 최적화 방향, 특히 자율적 변수 조정 및 기계 학습 통합을 통해 전략의 성능을 더욱 향상시킬 잠재력이 있습니다.
고주파 거래 환경에서 기술적으로 강하고 규율적인 시스템을 사용하려는 거래자에게 이 전략은 기술적인 정밀성과 위험 통제가 결합된 견고한 프레임 워크를 제공합니다. 중요한 것은 거래자가 철저한 회귀와 시뮬레이션 거래를 통해 이 전략의 성능을 확인해야한다는 것입니다.
/*backtest
start: 2024-04-16 00:00:00
end: 2025-04-15 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=6
strategy("Dskyz (DAFE) MAtrix with ATR-Powered Precision",
overlay=true,
default_qty_type=strategy.fixed,
initial_capital=1000000,
commission_value=0,
slippage=1,
pyramiding=10)
// ==================================================================
// USER-DEFINED FUNCTIONS
// ==================================================================
// Hull Moving Average (HMA)
hma(src, len) =>
halfLen = math.round(len * 0.5)
sqrtLen = math.round(math.sqrt(len))
wmaf = ta.wma(src, halfLen)
wmaFull = ta.wma(src, len)
ta.wma(2 * wmaf - wmaFull, sqrtLen)
// Triple Exponential Moving Average (TEMA)
tema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
3 * (ema1 - ema2) + ema3
// Double Exponential Moving Average (DEMA)
dema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
2 * ema1 - ema2
// VWMA - Volume Weighted Moving Average
vwma(src, len) =>
ta.vwma(src, len)
// ZLEMA - Zero Lag EMA
zlema(src, len) =>
lag = math.floor((len - 1) / 2)
ta.ema(2 * src - src[lag], len)
// ALMA - Arnaud Legoux Moving Average
alma(src, len, offset=0.85, sigma=6) =>
ta.alma(src, len, offset, sigma)
// Custom Kaufman Adaptive Moving Average (KAMA)
kama(src, len) =>
fastSC = 2.0 / (2 + 1)
slowSC = 2.0 / (30 + 1)
change = math.abs(src - src[len])
volatility = 0.0
for i = 0 to len - 1
volatility += math.abs(src - src[i])
er = volatility != 0 ? change / volatility : 0.0
sc = math.pow(er * (fastSC - slowSC) + slowSC, 2)
var float kama_val = na
kama_val := na(kama_val) ? ta.sma(src, len) : kama_val + sc * (src - kama_val)
kama_val
// ==================================================================
// INPUTS
// ==================================================================
fastLength = input.int(9, "[MA] Fast MA Length", minval=1)
slowLength = input.int(19, "[MA] Slow MA Length", minval=1)
fastMAType = input.string("SMA", "Fast MA Type", options=["SMA", "EMA", "SMMA", "HMA", "TEMA", "WMA", "VWMA", "ZLEMA", "ALMA", "KAMA", "DEMA"])
slowMAType = input.string("SMA", "Slow MA Type", options=["SMA", "EMA", "SMMA", "HMA", "TEMA", "WMA", "VWMA", "ZLEMA", "ALMA", "KAMA", "DEMA"])
atrPeriod = input.int(14, "ATR Period", minval=1)
atrMultiplier = input.float(1.5, "ATR Multiplier for Filter", minval=0.1, step=0.1)
useTrendFilter = input.bool(true, "[Filter Settings] Use 15m Trend Filter")
minVolume = input.int(10, "Minimum Volume", minval=1)
volatilityThreshold = input.float(1.0, "Volatility Threshold (%)", minval=0.1, step=0.1) / 100
tradingStartHour = input.int(9, "Trading Start Hour (24h)", minval=0, maxval=23)
tradingEndHour = input.int(16, "Trading End Hour (24h)", minval=0, maxval=23)
trailOffset = input.float(0.5, "[Exit Settings] Trailing Stop Offset ATR Multiplier", minval=0.01, step=0.01)
profitTargetATRMult = input.float(1.2, "Profit Target ATR Multiplier", minval=0.1, step=0.1)
fixedStopMultiplier = input.float(1.3, "Fixed Stop Multiplier", minval=0.5, step=0.1)
fixedQuantity = input.int(2, "Trade Quantity", minval=1)
resetDashboard = input.bool(false, "Reset Dashboard Stats")
// ==================================================================
// CALCULATIONS
// ==================================================================
volumeOk = volume >= minVolume
currentHour = hour(time)
timeWindow = currentHour >= tradingStartHour and currentHour <= tradingEndHour
volumeSpike = volume > 1.2 * ta.sma(volume, 10)
// ATR Calculation
atr = ta.atr(atrPeriod)
volatility = nz(atr / close, 0)
volatilityOk = volatility <= volatilityThreshold
// ==================================================================
// MOVING AVERAGES CALCULATIONS
// ==================================================================
var float fastMA = na
var float slowMA = na
// Fast MA Logic
if fastMAType == "SMA"
fastMA := ta.sma(close, fastLength)
else if fastMAType == "EMA"
fastMA := ta.ema(close, fastLength)
else if fastMAType == "SMMA"
fastMA := ta.rma(close, fastLength)
else if fastMAType == "HMA"
fastMA := hma(close, fastLength)
else if fastMAType == "TEMA"
fastMA := tema(close, fastLength)
else if fastMAType == "WMA"
fastMA := ta.wma(close, fastLength)
else if fastMAType == "VWMA"
fastMA := vwma(close, fastLength)
else if fastMAType == "ZLEMA"
fastMA := zlema(close, fastLength)
else if fastMAType == "ALMA"
fastMA := alma(close, fastLength)
else if fastMAType == "KAMA"
fastMA := kama(close, fastLength)
else if fastMAType == "DEMA"
fastMA := dema(close, fastLength)
// Slow MA Logic
if slowMAType == "SMA"
slowMA := ta.sma(close, slowLength)
else if slowMAType == "EMA"
slowMA := ta.ema(close, slowLength)
else if slowMAType == "SMMA"
slowMA := ta.rma(close, slowLength)
else if slowMAType == "HMA"
slowMA := hma(close, slowLength)
else if slowMAType == "TEMA"
slowMA := tema(close, slowLength)
else if slowMAType == "WMA"
slowMA := ta.wma(close, slowLength)
else if slowMAType == "VWMA"
slowMA := vwma(close, slowLength)
else if slowMAType == "ZLEMA"
slowMA := zlema(close, slowLength)
else if slowMAType == "ALMA"
slowMA := alma(close, slowLength)
else if slowMAType == "KAMA"
slowMA := kama(close, slowLength)
else if slowMAType == "DEMA"
slowMA := dema(close, slowLength)
// ==================================================================
// TREND FILTER & SIGNAL LOGIC
// ==================================================================
// Retrieve 15-minute MAs for trend filtering
[fastMA15m, slowMA15m] = request.security(syminfo.tickerid, "15", [ta.sma(close, fastLength), ta.sma(close, slowLength)])
trend15m = fastMA15m > slowMA15m ? 1 : fastMA15m < slowMA15m ? -1 : 0
trendLongOk = not useTrendFilter or trend15m >= 0
trendShortOk= not useTrendFilter or trend15m <= 0
// ATR-based Price Filter
atrFilterLong = close > slowMA + atr * atrMultiplier
atrFilterShort = close < slowMA - atr * atrMultiplier
// Signal Logic: MA alignment + filters
maAbove = close > fastMA and fastMA > slowMA
maBelow = close < fastMA and fastMA < slowMA
longCondition = maAbove and trendLongOk and atrFilterLong and volumeOk and volumeSpike and timeWindow and volatilityOk
shortCondition= maBelow and trendShortOk and atrFilterShort and volumeOk and volumeSpike and timeWindow and volatilityOk
// ==================================================================
// ENTRY LOGIC
// ==================================================================
if strategy.position_size == 0 and longCondition
strategy.entry("Long", strategy.long, qty=fixedQuantity)
if strategy.position_size == 0 and shortCondition
strategy.entry("Short", strategy.short, qty=fixedQuantity)
// ==================================================================
// EXIT LOGIC
// ==================================================================
if strategy.position_size > 0
strategy.exit("Long Exit", "Long",
stop = strategy.position_avg_price - atr * fixedStopMultiplier,
limit = strategy.position_avg_price + atr * profitTargetATRMult,
trail_offset = atr * trailOffset,
trail_points = atr * trailOffset)
if strategy.position_size < 0
strategy.exit("Short Exit", "Short",
stop = strategy.position_avg_price + atr * fixedStopMultiplier,
limit = strategy.position_avg_price - atr * profitTargetATRMult,
trail_offset = atr * trailOffset,
trail_points = atr * trailOffset)
// ==================================================================
// VISUALS: PLOT MAs
// ==================================================================
plot(fastMA, color=color.blue, linewidth=2, title="Fast MA")
plot(slowMA, color=color.red, linewidth=2, title="Slow MA")
// ==================================================================
// METRICS CALCULATIONS (for Dashboard)
// ==================================================================
// Additional metrics:
atrPct = close != 0 ? (atr / close) * 100 : na // ATR as percentage of Close
maGapPct = (slowMA != 0) ? (math.abs(fastMA - slowMA) / slowMA) * 100 : na // % difference between MAs
// Open PnL Calculation
currentPnL = strategy.position_size != 0 ? (close - strategy.position_avg_price) * strategy.position_size : 0
// Persistent variable for highest equity (for drawdown calculation)
var float highestEquity = strategy.equity
highestEquity := math.max(highestEquity, strategy.equity)
totalDrawdown = strategy.equity - highestEquity
// Reset dashboard metrics if reset toggle is on.
if resetDashboard
highestEquity := strategy.equity
// ==================================================================
// DASHBOARD: WATERMARK LOGO (Bottom-Right)
// ==================================================================
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 Trading Systems", text_color=color.rgb(159, 127, 255, 80), text_size=size.large)
// ==================================================================
// DASHBOARD: METRICS TABLE (Bottom-Left)
// ==================================================================
var table dashboard = table.new(position.middle_right, 2, 12, bgcolor=color.new(#000000, 29), border_color=color.rgb(80, 80, 80), border_width=1)
if barstate.islast
// Row 0 – Dashboard Title (duplicated in both columns to simulate spanning)
table.cell(dashboard, 0, 0, "⚡(DAFE) Trading Systems", text_color=color.rgb(135, 135, 135), text_size=size.small)
// Row 1 – Position
table.cell(dashboard, 0, 1, "Position", text_color=color.gray)
positionText = strategy.position_size > 0 ? "Long" : strategy.position_size < 0 ? "Short" : "Flat"
table.cell(dashboard, 1, 1, positionText, text_color=strategy.position_size > 0 ? color.green : strategy.position_size < 0 ? color.red : color.blue)
// Row 2 – Current PnL
table.cell(dashboard, 0, 2, "Current P/L", text_color=color.gray)
table.cell(dashboard, 1, 2, str.tostring(currentPnL, "#.##"), text_color=(currentPnL > 0 ? color.green : currentPnL < 0 ? color.red : color.gray))
// Row 3 – Equity
table.cell(dashboard, 0, 3, "Equity", text_color=color.gray)
table.cell(dashboard, 1, 3, str.tostring(strategy.equity, "#.##"), text_color=color.white)
// Row 4 – Closed Trades
table.cell(dashboard, 0, 4, "Closed Trades", text_color=color.gray)
table.cell(dashboard, 1, 4, str.tostring(strategy.closedtrades), text_color=color.white)
// Row 5 – Title Step
table.cell(dashboard, 0, 5, "Metrics", text_color=color.rgb(76, 122, 23))
// Row 6 – Fast MA
table.cell(dashboard, 0, 6, "Fast MA", text_color=color.gray)
table.cell(dashboard, 1, 6, str.tostring(fastMA, "#.##"), text_color=color.white)
// Row 7 – Slow MA
table.cell(dashboard, 0, 7, "Slow MA", text_color=color.gray)
table.cell(dashboard, 1, 7, str.tostring(slowMA, "#.##"), text_color=color.white)
// Row 8 – ATR (Raw)
table.cell(dashboard, 0, 8, "ATR", text_color=color.gray)
table.cell(dashboard, 1, 8, str.tostring(atr, "#.##"), text_color=color.white)
// Row 9 – ATR (%)
table.cell(dashboard, 0, 9, "ATR (%)", text_color=color.gray)
table.cell(dashboard, 1, 9, str.tostring(atrPct, "#.##") + "%", text_color=color.white)
// Row 10 – MA Gap (%)
table.cell(dashboard, 0, 10, "MA Gap (%)", text_color=color.gray)
table.cell(dashboard, 1, 10, na(maGapPct) ? "N/A" : str.tostring(maGapPct, "#.##") + "%", text_color=color.white)
// Row 11 – Volatility (%)
table.cell(dashboard, 0, 11, "Volatility (%)", text_color=color.gray)
table.cell(dashboard, 1, 11, str.tostring(volatility * 100, "#.##") + "%", text_color=color.white)