다중 시간 기간 지수 이동 평균 교차 전략

EMA SL TP TF
생성 날짜: 2024-07-30 12:02:23 마지막으로 수정됨: 2024-07-30 12:02:23
복사: 3 클릭수: 618
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

다중 시간 기간 지수 이동 평균 교차 전략

개요

이 다중 시간 주기의 지수 이동 평균 교차 전략은 EMA 교차 신호에 기반한 자동 거래 시스템이다. 그것은 다른 시간 주기의 EMA를 사용하여 거래 신호를 생성하고, 위험을 관리하기 위해 중지 손실과 이윤 결제 메커니즘을 결합한다. 이 전략은 주로 빠른 EMA와 느린 EMA 및 더 높은 시간 주기의 EMA 사이의 교차를 통해 잠재적인 거래 기회를 식별하는 데 의존한다.

전략 원칙

이 전략의 핵심 원칙은 시장의 추세를 식별하고 거래 신호를 생성하기 위해 여러 시간 주기 지수 이동 평균 (EMA) 을 사용하는 것입니다. 구체적으로:

  1. 9주기 EMA를 고속선으로, 50주기 EMA를 느린선으로, 그리고 15분 시간 주기에서 100주기 EMA를 더 높은 시간 주기 참조선으로 사용한다.

  2. 신호 구매 조건:

    • 빠른 EMA 위에 느린 EMA를 횡단하고, 빠른 EMA는 더 높은 시간 주기 EMA 위에 있다; 또는
    • 빠른 EMA에 더 높은 시간 주기 EMA를 착용하십시오.
  3. 신호 판매 조건:

    • 빠른 EMA 아래에서 느린 EMA를 통과하고, 빠른 EMA는 더 높은 시간 주기 EMA 아래에 있습니다. 또는
    • 빠른 EMA 아래에서 더 높은 시간 주기를 통과 EMA。
  4. 거래 관리:

    • 고정된 스톱로스 (SL) 와 수익 목표 (TP) 를 설정한다.
    • 가격이 첫 번째 수익 목표 (TP1) 에 도달했을 때, 25%의 포지션을 청산하고 스톱로스는 보금자리로 이동한다.
    • 남은 포지션은 두 번째 수익 목표 ((TP2) 또는 중지 손실 (stop loss)) 까지 계속 실행됩니다.
  5. 거래시간 제어:

    • 특정 거래 기간과 거래일을 설정할 수 있습니다.

전략적 이점

  1. 다중 시간 주기의 분석: 다른 시간 주기의 EMA와 결합하여 가짜 신호를 줄이고 거래 품질을 향상시키는 데 도움이됩니다.

  2. 트렌드 추적: EMA의 교차와 위치 관계를 통해 시장의 흐름을 효과적으로 포착할 수 있다.

  3. 리스크 관리: 고정된 스톱로스 및 단계적 수익 전략으로 잠재적인 손실을 제한하고 수익을 계속 증가시킬 수 있습니다.

  4. 유연성: 다른 시장과 거래 스타일에 따라 EMA 매개 변수, 중지 손실 및 수익 수준을 조정할 수 있습니다.

  5. 자동화: 전략은 TradingView 플랫폼과 PineConnector를 통해 완전히 자동화된 거래를 구현할 수 있습니다.

  6. 시간 관리: 특정 거래 시간 및 거래 날을 설정하여 불리한 시장 환경에서 거래하는 것을 피할 수 있습니다.

전략적 위험

  1. 지연성: EMA는 본질적으로 지연된 지표이며, 급격하게 변동하는 시장에서 반응하지 않을 수 있다.

  2. 가짜 신호: 가로 시장에서, EMA 교차는 종종 가짜 신호를 생성하여 과도한 거래로 이어질 수 있습니다.

  3. 고정 스톱: 고정 점수를 사용하는 스톱은 모든 시장 조건에 적합하지 않을 수 있으며 때로는 너무 크거나 너무 작을 수 있습니다.

  4. 역사적 데이터에 의존: 전략의 효과는 재검토 기간 동안의 시장 행동에 크게 의존하며, 미래의 성능은 다를 수 있습니다.

  5. 시장 적응성: 전략은 일부 통화 쌍에서 잘 작동하지만 다른 통화 쌍에서는 효과가 좋지 않을 수 있습니다.

전략 최적화 방향

  1. 동적 변수 조정: 시장의 변동성에 따라 동적으로 조정하는 EMA 주기, 중지 손실 및 이익 수준을 고려하십시오.

  2. 필터링 조건을 추가: 추가 기술 지표 또는 시장 감정 지표를 도입하여 거래 신호를 필터링하여 가짜 신호를 줄이십시오.

  3. 개선된 손해 중지 전략: 시장의 변동에 더 잘 적응하기 위해 추적된 손해 중지 또는 ATR 기반의 동적 손해 중단을 구현하십시오.

  4. 거래 시간을 최적화: 더 자세한 시간 분석을 통해 최적의 거래 시간 및 날짜를 찾아내십시오.

  5. 거래량 관리를 강화: 시장의 변동성과 계좌의 위험에 따라 포지션 크기를 조정한다.

  6. 다국적 통화 연관성 분석: 여러 통화 쌍 간의 연관성을 고려하여 유사한 시장 위험에 과도하게 노출되는 것을 피하십시오.

  7. 기계 학습 통합: 기계 학습 알고리즘을 사용하여 매개 변수 선택 및 신호 생성 과정을 최적화한다.

요약하다

다중 시간 주기 지수 이동 평균 교차 전략은 트렌드 추적과 위험 관리를 결합한 자동화 된 거래 시스템입니다. 이 전략은 다른 시간 주기의 EMA 교차 신호를 활용하여 시장의 추세를 포착하고 적절한 시기에 거래를 수행합니다. 전략은 특정 시장 조건에서 잘 수행하지만, 여전히 몇 가지 고유한 위험과 한계가 있습니다. 전략의 안정성과 적응력을 더욱 높이기 위해, 동적 파라미터 조정, 추가 필터링 조건 및 더 복잡한 위험 관리 기술을 도입하는 것이 고려 될 수 있습니다.

전략 소스 코드
/*backtest
start: 2023-07-30 00:00:00
end: 2024-07-29 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("Miles Multi TF EMA Strategy v 1", overlay=true)

Fast = input.int(9, "Fast EMA")
Xslow = input.int(50, "Slow EMA")

var bool inTrade = false // Ensure inTrade is declared and initialized
var int tradeDirection = 0
var float buy_slPrice = na
var float buy_tp1Price = na
var float buy_tp2Price = na
var float sell_slPrice = na
var float sell_tp1Price = na
var float sell_tp2Price = na
var bool tp1Hit = false
var bool buytp1Hit = false
var bool selltp1Hit = false
var float entryPrice = na
var float lastSignalBar = na
fastEMA = ta.ema(close, Fast)
XslowEMA = ta.ema(close, Xslow)
var int step = 0

// Example SL and TP settings (adjust according to your strategy)
slPips = input.int(150, "Stop Loss")
tp1Pips = input.int(75, "Take Profit 1")
tp2Pips = input.int(150, "Take Profit 2")
beoff = input.int(25, "Breakeven Offset")

// Define the higher time frame
higherTimeFrame = input.timeframe("15", "Higher Timeframe EMA")

// Fetch the EMA from the higher time frame
higherTimeFrameEMA = request.security(syminfo.tickerid, higherTimeFrame, ta.ema(close, 100))

// Input for trading start and end times, allowing end time to extend beyond midnight
startHour = input.int(1, "Start Hour", minval=0, maxval=23)
endHour = input.int(25, "End Hour", minval=0, maxval=47) // Extend maxval to 47 to allow specifying times into the next day

// Adjust endHour to be within 24-hour format using modulo operation
adjustedEndHour = endHour % 24

// Function to determine if the current time is within the trading hours
isTradingTime(currentHour) =>
    if startHour < adjustedEndHour
        currentHour >= startHour and currentHour < adjustedEndHour
    else
        currentHour >= startHour or currentHour < adjustedEndHour

// Get the current hour in the exchange's timezone
currentHour = hour(time, "Australia/Sydney")

// Check if the current time is within the trading hours
trading = isTradingTime(currentHour)

// Plot background color if within trading hours
bgcolor(trading ? color.new(color.blue, 90) : na)

// Inputs for trading days
tradeOnMonday = input.bool(true, "Trade on Monday")
tradeOnTuesday = input.bool(true, "Trade on Tuesday")
tradeOnWednesday = input.bool(true, "Trade on Wednesday")
tradeOnThursday = input.bool(true, "Trade on Thursday")
tradeOnFriday = input.bool(true, "Trade on Friday")

// Current time checks
currentDayOfWeek = dayofweek(time, "Australia/Sydney")

// Check if current time is within trading hours
isTradingHour = (currentHour >= startHour and currentHour < endHour)

// Check if trading is enabled for the current day of the week
isTradingDay = (currentDayOfWeek == dayofweek.monday and tradeOnMonday) or 
               (currentDayOfWeek == dayofweek.tuesday and tradeOnTuesday) or 
               (currentDayOfWeek == dayofweek.wednesday and tradeOnWednesday) or 
               (currentDayOfWeek == dayofweek.thursday and tradeOnThursday) or 
               (currentDayOfWeek == dayofweek.friday and tradeOnFriday)

// Combined check for trading time and day
isTradingTime = isTradingHour and isTradingDay

buySignal = false
sellSignal = false

// Conditions
if (step == 0 or step == 4) and ta.crossover(fastEMA, XslowEMA) and fastEMA > higherTimeFrameEMA
    step := 1

if (step == 0 or step == 4) and ta.crossover(fastEMA, higherTimeFrameEMA)
    step := 1

if step == 3 and ta.crossover(fastEMA, XslowEMA) and fastEMA > higherTimeFrameEMA
    step := 3

if step == 2 and ta.crossover(fastEMA, XslowEMA) and fastEMA > higherTimeFrameEMA
    step := 1

if (step == 0 or step == 3) and ta.crossunder(fastEMA, XslowEMA) and fastEMA < higherTimeFrameEMA
    step := 2

if (step == 0 or step == 3) and ta.crossunder(fastEMA, higherTimeFrameEMA)
    step := 2

if step == 4 and ta.crossunder(fastEMA, XslowEMA) and fastEMA < higherTimeFrameEMA
    step := 4

if step == 1 and ta.crossunder(fastEMA, XslowEMA) and fastEMA < higherTimeFrameEMA
    step := 2

// For buy signals
if step == 1 and isTradingTime and fastEMA > ta.ema(close, Xslow) and fastEMA > higherTimeFrameEMA
    buySignal := true
    inTrade := true
    entryPrice := close
    tradeDirection := 1
    buytp1Hit := false
    lastSignalBar := bar_index
    buy_slPrice := entryPrice - slPips * syminfo.mintick
    buy_tp1Price := entryPrice + tp1Pips * syminfo.mintick // Set TP1
    buy_tp2Price := entryPrice + tp2Pips * syminfo.mintick // Set TP2
    tp1Hit := false
    step := 3
    strategy.entry("Buy", strategy.long, stop=buy_slPrice, limit=buy_tp1Price)

if step == 2 and isTradingTime and fastEMA < ta.ema(close, Xslow) and fastEMA < higherTimeFrameEMA
    sellSignal := true
    inTrade := true
    entryPrice := close
    tradeDirection := -1
    lastSignalBar := bar_index
    selltp1Hit := false
    sell_slPrice := entryPrice + slPips * syminfo.mintick
    sell_tp1Price := entryPrice - tp1Pips * syminfo.mintick // Set TP1
    sell_tp2Price := entryPrice - tp2Pips * syminfo.mintick // Set TP2
    tp1Hit := false
    step := 4
    strategy.entry("Sell", strategy.short, stop=sell_slPrice, limit=sell_tp1Price)

// Move SL to breakeven once TP1 is hit and close 25% of the trade
if (ta.valuewhen(strategy.position_size != 0, strategy.position_size, 0) > 0)
    if high >= buy_tp1Price and not tp1Hit
        tp1Hit := true
        buy_slPrice := entryPrice + beoff * syminfo.mintick
        strategy.close("Buy", qty_percent = 25, comment = "TP1 Hit")
        strategy.exit("Close", from_entry="Buy", stop=buy_slPrice, limit=buy_tp2Price)
        
if (ta.valuewhen(strategy.position_size != 0, strategy.position_size, 0) < 0)
    if low <= sell_tp1Price and not tp1Hit
        tp1Hit := true
        sell_slPrice := entryPrice - beoff * syminfo.mintick
        strategy.close("Sell", qty_percent = 25, comment = "TP1 Hit")
        strategy.exit("Close", from_entry="Sell", stop=sell_slPrice, limit=sell_tp2Price)

// Managing the trade after it's initiated
if inTrade and tradeDirection == 1 and sellSignal
    inTrade := false
    tradeDirection := 0
    buy_slPrice := na
    buy_tp1Price := na
    buy_tp2Price := na
    tp1Hit := false
    step := 2

if inTrade and tradeDirection == -1 and buySignal
    inTrade := false
    tradeDirection := 0
    sell_slPrice := na
    sell_slPrice := na
    sell_tp2Price := na
    tp1Hit := false
    step := 1

if inTrade and tradeDirection == 1 and step == 1
    step := 0

if inTrade and tradeDirection == -1 and step == 2
    step := 0

if inTrade and tradeDirection == 1 and (bar_index - lastSignalBar) >= 1
    if high >= buy_tp1Price and not tp1Hit
        tp1Hit := true
        buytp1Hit := true
        lastSignalBar := bar_index
        buy_slPrice := entryPrice + beoff * syminfo.mintick
        step := 3

    if low <= buy_slPrice and not tp1Hit and (bar_index - lastSignalBar) >= 1
        strategy.close("Buy", qty_percent = 100, comment = "SL Hit")
        inTrade := false
        tradeDirection := 0
        buy_slPrice := na
        buy_tp1Price := na
        buy_tp2Price := na
        tp1Hit := false
        buytp1Hit := false
        step := 0

if inTrade and tradeDirection == 1 and tp1Hit and (bar_index - lastSignalBar) >= 1
    if low <= buy_slPrice
        inTrade := false
        tradeDirection := 0
        buy_slPrice := na
        buy_tp1Price := na
        buy_tp2Price := na
        tp1Hit := false
        buytp1Hit := false
        step := 0

    if high >= buy_tp2Price and (bar_index - lastSignalBar) >= 1
        inTrade := false
        tradeDirection := 0
        buy_slPrice := na
        buy_tp1Price := na
        buy_tp2Price := na
        tp1Hit := false
        buytp1Hit := false
        step := 0

if inTrade and tradeDirection == -1 and (bar_index - lastSignalBar) >= 1
    if low <= sell_tp1Price and not tp1Hit
        tp1Hit := true
        lastSignalBar := bar_index
        selltp1Hit := true
        sell_slPrice := entryPrice - beoff * syminfo.mintick
        step := 4

    if high >= sell_slPrice and not tp1Hit and (bar_index - lastSignalBar) >= 1
        strategy.close("Sell", qty_percent = 100, comment = "SL Hit")
        inTrade := false
        tradeDirection := 0
        sell_slPrice := na
        sell_tp1Price := na
        sell_tp2Price := na
        tp1Hit := false
        selltp1Hit := false
        step := 0

if inTrade and tradeDirection == -1 and tp1Hit  and (bar_index - lastSignalBar) >= 1
    if high >= sell_slPrice
        inTrade := false
        tradeDirection := 0
        sell_slPrice := na
        sell_tp1Price := na
        sell_tp2Price := na
        tp1Hit := false
        selltp1Hit := false
        step := 0
    if low <= sell_tp2Price
        inTrade := false
        tradeDirection := 0
        sell_slPrice := na
        sell_tp1Price := na
        sell_tp2Price := na
        tp1Hit := false
        selltp1Hit := false
        step := 0