
이 전략은 지수 이동 평균 (EMA) 교차 신호에 기반한 스마트 달러 비용 평균 (DCA) 전략으로, 변동성에 적응하는 안전 주문 (SO) 배포와 혁신적인 쌍로 스톱스 메커니즘을 결합한다. 상승 추세가 확인되면 시장에 진입하고, 시장의 변동성에 따라 자동으로 추가 안전 주문을 배포하며, 표준 추적 스톱스 및 수익 잠금 추적 시스템을 사용하여 수익을 보호한다. 이 전략은 변동성이 높은 시장 환경에서 운영하기에 적합하며, 특히 1시간 주기를 위해 최적화되어 있으며, 총 자본금 4000달러의 거래 운영을 사용합니다.
이 전략의 핵심 논리는 다음과 같은 몇 가지 핵심 구성 요소를 중심으로 펼쳐집니다.
트렌드 인식 시스템: 빠른 EMA (기본 9주기) 와 느린 EMA (기본 21주기) 의 교차를 사용하여 잠재적인 상승세를 식별한다. 빠른 EMA가 느린 EMA를 상향으로 통과하면 시스템이 상승세를 확인하고 기본 입찰 주문을 유발한다.
다단계 DCA 입력 시스템3단계 입학 전략:
변동성 적응 장치: 안전 주문의 촉발 가격은 ATR (평균 실제 범위) 지표에 기초하여 동적으로 계산될 수 있으며, 이는 시장의 현재 변동에 따라 전략이 자동으로 입점 위치를 조정할 수 있도록 해준다. 사용자는 ATR 곱셈을 사용하거나 고정된 퍼센트 하락을 사용하여 안전 주문의 촉발점을 계산할 수 있다.
이중 레일 상해 방지 시스템:
냉각기 메커니즘: 기본 주문 실행 후 냉각 기간을 시행하기 (설정 4개의 K 라인), 짧은 시간에 과도한 거래를 방지하기.
분석 결과, 이 전략은 다음과 같은 중요한 장점을 보여준다.
적응력ATR을 통해 보안 주문을 계산하여 가격을 유발하여 전략이 다양한 시장 변동 환경에 현명하게 적응할 수 있도록합니다. 높은 변동 기간 동안 보안 주문 간격을 적절히 늘리고 낮은 변동 기간 동안 간격을 강화합니다.
자금 관리 최적화: 증가하는 자금 분배 방식을 사용함 ((1000달러→1250달러→1750달러), “피라미드식” 포지션 관리 원칙에 부합하여, 가격이 하락할 때 전략이 더 큰 자금 규모로 더 우수한 평균 입시 가격을 얻을 수 있게 한다.
이중 보호 장치: 혁신적인 쌍로 스톱 시스템은 기본 하향 위험 보호를 제공하면서도 수익을 올릴 때 자동으로 더 보수적인 스톱 모드로 전환하여 수익 극대화와 위험 관리를 효과적으로 균형을 맞추고 있습니다.
맞춤형 유연성: 모든 핵심 매개 변수는 사용자 정의 가능하며, EMA 주기, ATR 길이, 안전 주문 간격, 중지 비율 및 주문 크기를 포함합니다. 개인 위험 선호 및 시장 조건에 따라 거래자가 최적화 할 수 있습니다.
통합성이 전략은 JSON 메시지로 포맷된 경고 조건을 내장하여 3rd-party 자동 거래 플랫폼 (예: 3Commas) 과 통합하여 완전히 자동화된 거래 실행을 가능하게 한다.
이 전략은 포괄적으로 설계되었지만 다음과 같은 잠재적인 위험과 도전이 있습니다.
추세 반전 위험이 전략은 EMA 교차 신호에 의존하며 시장의 급격한 변화 또는 흔들리는 시장에서 잘못된 신호가 발생하여 불필요한 입장을 초래할 수 있습니다. 해결책은 EMA 주기의 길이를 조정하거나 추가 확인 지표를 추가하는 것입니다.
자금 소모의 위험: 계속적으로 하락하는 시장에서, 모든 안전 주문이 배치되어도 평균 입시 가격은 시장 가격보다 훨씬 높을 수 있으며, 장기적인 손실을 초래합니다. 최대 손실 제한 또는 전체 포지션 규모 제한을 설정하는 것이 좋습니다.
과도한 거래의 위험: 격렬한 시장에서 EMA는 자주 교차하여 과다 거래를 유발할 수 있습니다. 냉각 기간 메커니즘이 내장되어 있음에도 불구하고 추가 거래 주파수 제한을 추가하거나 추가 최적화가 필요할 수 있습니다.
이중 경로 정지 서로 간섭: 어떤 시장 상황에서는 두 가지의 스톱 메커니즘이 서로 간섭하여 조기 종료 또는 반복 신호를 유발할 수 있습니다. 이 두 가지 스톱 매개 변수 사이의 균형을 정기적으로 재검토하고 조정해야합니다.
매개 변수 최적화 문제: 전략의 여러 매개 변수가 서로 조율되어야 최적의 효과를 얻을 수 있으며 매개 변수 최적화의 복잡성을 증가시킵니다. 피드백 최적화 도구를 사용하여 전체적인 매개 변수 분석을 수행하는 것이 좋습니다.
코드의 심층적인 분석을 바탕으로, 이 전략의 잠재적인 최적화 방향은 다음과 같습니다.
다중 동향 확인 메커니즘을 도입합니다.현재 전략은 단일 EMA 교차 신호에만 의존하고 있으며, 잘못된 신호를 줄이기 위해 RSI, MACD 또는 더 긴 기간의 추세 판단과 같은 추가적인 추세 확인 지표를 추가하는 것이 고려 될 수 있습니다.
동적 자금 배분 시스템: 현재 전략은 고정된 달러 금액을 주문 크기로 사용하며, 시장의 변동성이나 계정 이해관계에 따라 동적으로 조정되는 시스템으로 최적화되어 다양한 시장 조건에서 적절한 수준의 위험 노출을 유지하도록 보장합니다.
최적화된 스톱로스 탈퇴 전략더 복잡한 중지 논리를 개발할 수 있습니다. 예를 들어, 시장의 변동성에 기반한 자율적 추적 중지, 또는 단기 변동성에서 조기 종료를 피하기 위해 탈퇴 결정을 최적화하기 위해 운동량과 거래량 지표를 통합합니다.
철수 통제 강화: 전략이 기본 설정된 최대 인출 비율에 도달하면 새로운 주문을 자동으로 중지하거나 기존 포지션을 닫는 총 인출 제한 기능을 추가하여 극한 시장 조건에서 재앙적인 손실을 방지합니다.
주기 최적화 시스템: 자동 주기 최적화 기능을 개발하여 전략이 시장 상태의 변화에 따라 최근 시장 조건에 따라 EMA 길이를, ATR 주기를 및 다른 시간 관련 매개 변수를 자동으로 조정할 수 있도록합니다.
“지능한 변동 추적형 DCA 전략과 이중 경로 상쇄 시스템”은 우수한 설계된 양적 거래 프로그램으로, 특히 변동성 시장에서 상승 추세를 포착하고 위험을 관리하는 데 적합합니다. 그것은 트렌드 추적, 달러 비용 평균법과 변동율 자조 장치를 교묘하게 결합하고, 혁신적인 이중 경로 상쇄 시스템으로 수익을 보호합니다.
이 전략의 핵심 장점은 적응성과 위험 관리의 균형을 이루며, 다양한 시장 환경에서 입출출 결정을 자동으로 조정할 수 있다는 것입니다. ATR을 사용하여 보안 주문 트리거 포인트를 동적으로 계산함으로써, 전략은 사전 설정된 정적 매개 변수에 의존하지 않고 실시간 시장 조건에 따라 지능적으로 대응 할 수 있습니다.
트렌드 식별 및 재무 관리에 대한 잠재적인 위험은 있지만, 이러한 위험은 제안된 최적화 방향에 의해 효과적으로 완화 될 수 있습니다. 특히, 다중 트렌드 확인 및 동적 재무 분배 시스템을 도입하면 전략의 안정성과 장기적 성과를 크게 향상시킬 수 있습니다.
변동성 시장에서 체계적인 거래 방법을 찾는 수량 거래자들에게 이 전략은 상향 추세를 포착하는 동시에 불리한 시장 조건에서 충분한 위험 보호를 제공하는 포괄적이고 확장 가능한 프레임 워크를 제공합니다.
/*backtest
start: 2025-03-14 00:00:00
end: 2025-04-02 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/
//@version=5
strategy(
title="BONK/USD (1H) - $4k DCA + Dual Trailing + Date Filter", // Updated Title
overlay=true,
initial_capital=4000,
currency=currency.USD,
default_qty_type=strategy.fixed,
default_qty_value=0, // Quantity calculated dynamically based on USD value
commission_type=strategy.commission.percent, // Example: Add commission settings
commission_value=0.1 // Example: 0.1% commission
)
// 1) USER INPUTS (Defaults adjusted for 1H timeframe - REQUIRES BACKTESTING/TUNING)
// --- Trend ---
fastMALen = input.int(9, title="Fast EMA Length (Default for 1H)")
slowMALen = input.int(21, title="Slow EMA Length (Default for 1H)")
// --- Trailing Stops ---
trailStopPerc = input.float(8.0, title="Standard Trailing Stop (%) (Default for 1H)", minval=0.1) / 100
lockInThreshold = input.float(2.5, title="Profit Lock-In Trigger (%) (Default for 1H)", minval=0.1) / 100
lockInTrailPct = input.float(1.5, title="Lock-In Trail (%) after Trigger (Default for 1H)", minval=0.1) / 100
// --- Safety Orders (SO) ---
useATRSpacing = input.bool(true, title="Use ATR-Based Spacing?")
atrLength = input.int(14, title="ATR Length", minval=1)
atrSo1Multiplier = input.float(1.2, title="ATR SO1 Multiplier (Default for 1H)", minval=0.1)
atrSo2Multiplier = input.float(2.5, title="ATR SO2 Multiplier (Default for 1H)", minval=0.1)
// --- Fallback SO Spacing (if not using ATR) ---
fallbackSo1Perc = input.float(4.0, title="Fallback SO1 Drop (%) (Default for 1H)", minval=0.1) / 100
fallbackSo2Perc = input.float(8.0, title="Fallback SO2 Drop (%) (Default for 1H)", minval=0.1) / 100
// --- Entry Cooldown ---
cooldownBars = input.int(4, "Cooldown Bars After Base Entry (Default for 1H)", minval=0)
// --- Order Sizes in USD ---
baseUsd = input.float(1000.0, title="Base Order Size (USD)", minval=1.0)
so1Usd = input.float(1250.0, title="Safety Order 1 Size (USD)", minval=1.0)
so2Usd = input.float(1750.0, title="Safety Order 2 Size (USD)", minval=1.0)
// 2) CALCULATIONS
// --- Trend & Reversal Detection ---
fastMA = ta.ema(close, fastMALen)
slowMA = ta.ema(close, slowMALen)
trendUp = ta.crossover(fastMA, slowMA)
trendDown = ta.crossunder(fastMA, slowMA)
// --- ATR Value ---
atrValue = ta.atr(atrLength)
// 3) BASE ENTRY LOGIC
// Base Buy Signal: EMA crossover
baseBuySignal = trendUp
var int lastBuyBar = na // Tracks the bar index of the last base entry
inCooldown = not na(lastBuyBar) and (bar_index - lastBuyBar < cooldownBars)
var float baseEntryPrice = na // Stores the price of the initial base entry for SO calculations
// --- Execute Base Entry ---
// Added 'inDateRange' to the condition
if baseBuySignal and strategy.position_size == 0 and not inCooldown
baseQty = baseUsd / close // Calculate quantity based on USD
strategy.entry("Base Order", strategy.long, qty=baseQty, comment="Base Entry")
baseEntryPrice := close
lastBuyBar := bar_index
// 4) SAFETY ORDERS LOGIC
// --- Calculate SO Trigger Prices ---
float so1TriggerPrice = na
float so2TriggerPrice = na
if not na(baseEntryPrice) // Only calculate if a base order has been placed
so1TriggerPrice := useATRSpacing ?
(baseEntryPrice - atrValue * atrSo1Multiplier) :
(baseEntryPrice * (1 - fallbackSo1Perc))
so2TriggerPrice := useATRSpacing ?
(baseEntryPrice - atrValue * atrSo2Multiplier) :
(baseEntryPrice * (1 - fallbackSo2Perc))
// --- Conditions for SO Execution ---
// Added 'inDateRange' check
// Ensure base order exists, price trigger hit, and the specific SO hasn't filled yet
bool so1Condition = not na(baseEntryPrice) and strategy.position_size > 0 and close <= so1TriggerPrice and strategy.opentrades == 1
bool so2Condition = not na(baseEntryPrice) and strategy.position_size > 0 and close <= so2TriggerPrice and strategy.opentrades == 2
// --- Execute SO1 ---
if so1Condition
so1Qty = so1Usd / close // Calculate quantity based on USD
strategy.entry("Safety Order 1", strategy.long, qty=so1Qty, comment="SO1")
// --- Execute SO2 ---
if so2Condition
so2Qty = so2Usd / close // Calculate quantity based on USD
strategy.entry("Safety Order 2", strategy.long, qty=so2Qty, comment="SO2")
// 5) AVERAGE ENTRY PRICE
// Use the built-in variable for the average price of the open position
avgEntryPrice = strategy.position_avg_price
// 6) DUAL TRAILING STOP LOGIC
// Variables to track trailing stop levels and states
var float highestSinceEntry = na
var float trailStopPrice = na
var bool stopHitNormal = false
var bool lockInTriggered = false
var float lockInPeak = na
var float lockInStopPrice = na
var bool stopHitLockIn = false
// --- Update Trailing Logic when in a Position ---
if strategy.position_size > 0
// --- Standard Trail ---
highestSinceEntry := na(highestSinceEntry) ? close : math.max(highestSinceEntry, close)
trailStopPrice := highestSinceEntry * (1 - trailStopPerc)
stopHitNormal := close < trailStopPrice
// --- Lock-In Trail ---
if not lockInTriggered and close >= avgEntryPrice * (1 + lockInThreshold)
lockInTriggered := true
lockInPeak := close
if lockInTriggered
lockInPeak := math.max(lockInPeak, close)
lockInStopPrice := lockInPeak * (1 - lockInTrailPct)
stopHitLockIn := close < lockInStopPrice
else
stopHitLockIn := false
lockInStopPrice := na
// --- Reset Variables when Flat ---
else
highestSinceEntry := na
trailStopPrice := na
stopHitNormal := false
lockInTriggered := false
lockInPeak := na
lockInStopPrice := na
stopHitLockIn := false
baseEntryPrice := na
// lastBuyBar is intentionally NOT reset here, cooldown depends on it
// 7) EXIT CONDITIONS
// Added 'inDateRange' check
// Exit if either trailing stop is hit OR if the trend reverses downward, within the active date range
exitCondition = (stopHitNormal or stopHitLockIn or trendDown) and strategy.position_size > 0
if exitCondition
strategy.close_all(comment="Exit: SL / LockIn / TrendDown")
// 8) ALERT CONDITIONS (Potential 3Commas Integration)
// WARNING: Verify and adapt these JSON message strings for your specific 3Commas bot configuration!
// The required format ('action', parameters, etc.) can vary.
// Added 'inDateRange[1]' check for Base Alert
alertcondition(inDateRange[1] and baseBuySignal and strategy.position_size[1] == 0 and not inCooldown[1],
title="Base Buy Alert",
message='{"action":"start_deal","order":"base"} // Verify/Adapt JSON for your 3Commas bot!')
// Added 'inDateRange' check for SO1 Alert
alertcondition(so1Condition, title="SO1 Alert",
message='{"action":"add_funds","order":"so1"} // Verify/Adapt JSON for your 3Commas bot!')
// Added 'inDateRange' check for SO2 Alert
alertcondition(so2Condition, title="SO2 Alert",
message='{"action":"add_funds","order":"so2"} // Verify/Adapt JSON for your 3Commas bot!')
// Added 'inDateRange' check for Exit Alert
alertcondition(exitCondition, title="Exit Alert",
message='{"action":"close_at_market_price"} // Verify/Adapt JSON for your 3Commas bot!')
// 9) PLOTS & DEBUG TABLE
// --- Plot MAs ---
plot(fastMA, color=color.new(color.green, 0), title="Fast EMA", linewidth=2)
plot(slowMA, color=color.new(color.red, 0), title="Slow EMA", linewidth=2)
// --- Plot Trailing Stops ---
plot(strategy.position_size > 0 ? trailStopPrice : na, color=color.new(color.orange, 0), title="Standard Trailing Stop", style=plot.style_linebr, linewidth=2)
plot(lockInTriggered ? lockInStopPrice : na, color=color.new(color.fuchsia, 0), title="Lock-In Trailing Stop", style=plot.style_linebr, linewidth=2)
// --- Debug Info Table ---
var table tradeInfo = table.new(position=position.bottom_right, columns=2, rows=10, border_width=1)