EMA 지표를 기반으로 한 크로스마켓 롱 앤 숏 트렌드 오버나잇 포지션 전략

EMA MA
생성 날짜: 2024-11-12 10:49:00 마지막으로 수정됨: 2024-11-12 10:49:00
복사: 2 클릭수: 483
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

EMA 지표를 기반으로 한 크로스마켓 롱 앤 숏 트렌드 오버나잇 포지션 전략

이 전략은 EMA 기술 지표에 기반한 시장 간 야간 포지션 전략으로, 시장 종료 전과 오픈 후의 거래 기회를 포착하기 위한 것이다. 전략은 정확한 시간 제어와 기술 지표 필터링을 통해 다양한 시장 환경에서 지능적인 거래를 실현한다.

전략 개요

전략은 주로 시장 종결 전 특정 시간에 입문하고 다음 날 상장 후 특정 시간에 출장하여 수익을 얻습니다. EMA 지표와 결합하여 트렌드 확인으로 여러 글로벌 시장에서 거래 기회를 찾습니다. 전략은 자동화 거래 기능을 통합하여 무인 경호 작업을 구현합니다.

전략 원칙

  1. 시간 제어: 다른 시장의 거래 시간에 따라, 상장 전 고정 시간 입시, 상장 후 고정 시간 출시
  2. EMA 필터링: 선택 가능한 EMA 지표를 사용하여 입시 신호를 검증한다
  3. 시장 선택: 미국, 아시아, 유럽의 3대 시장에서 거래 시간을 조정할 수 있도록 지원
  4. 주말 보호: 금요일 폐지 전에 포지션을 의무적으로 청산하여 주말 위험을 피하십시오.

전략적 이점

  1. 다 시장 적응성: 시장 특성에 따라 거래 시간을 유연하게 조정할 수 있습니다.
  2. 리스크 관리가 완성된: 주말 평점 보호 장치 포함
  3. 높은 수준의 자동화: 자동 거래 인터페이스 조화를 지원한다
  4. 매개 변수 유연성: 거래 시간 및 기술 지표 매개 변수를 사용자 정의 할 수 있습니다
  5. 거래 비용 고려: 수수료와 슬라이드 포인트 설정 포함

전략적 위험

  1. 시장의 변동 위험: 하룻밤을 지탱하는 것은 폭락의 위험에 처할 수 있다
  2. 시간 의존성: 전략의 효과는 시장의 시간 기간 선택에 의해 영향을 받는다.
  3. 기술 지표의 제한: 단일 EMA 지표가 지연될 수 있습니다. 추천: 스톱로스 제한을 설정하고, 더 많은 기술 지표 검증을 추가하십시오.

전략 최적화 방향

  1. 더 많은 기술 지표 포지션을 추가합니다.
  2. 변동율 필터링을 도입한다
  3. 최적화된 출전 시간 선택
  4. 자율적 변수 조정 기능을 추가합니다.
  5. 위험 제어 모듈을 강화

요약하다

이 전략은 정확한 시간 제어 및 기술 지표 필터링을 통해 신뢰할 수 있는 야간 거래 시스템을 구현한다. 전략 설계는 다 시장 적응, 위험 제어, 자동화 거래 등의 요소를 포함한 실제 전투 요구 사항을 전체적으로 고려하고 있으며, 강력한 실용적 가치를 가지고 있다. 이 전략은 지속적인 최적화 및 개선을 통해 실제 거래에서 안정적인 수익을 얻을 수 있다.

전략 소스 코드
/*backtest
start: 2019-12-23 08:00:00
end: 2024-11-11 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading

// This strategy, titled "Overnight Market Entry Strategy with EMA Filter," is designed for entering long positions shortly before 
// the market closes and exiting shortly after the market opens. The strategy allows for selecting between different global market sessions (US, Asia, Europe) and 
// uses an optional EMA (Exponential Moving Average) filter to validate entry signals. The core logic is to enter trades based on conditions set for a specified period before 
// the market close and to exit trades either after a specified period following the market open or just before the weekend close. 
// Additionally, 3commas bot integration is included to automate the execution of trades. The strategy dynamically adjusts to market open and close times, ensuring trades are properly timed based on the selected market. 
// It also includes a force-close mechanism on Fridays to prevent holding positions over the weekend.

//@version=5
strategy("Overnight Positioning with EMA Confirmation - Strategy [presentTrading]", overlay=true, precision=3, commission_value=0.02, commission_type=strategy.commission.percent, slippage=1, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=10000)

// Input parameters
entryMinutesBeforeClose = input.int(20, title="Minutes Before Close to Enter", minval=1)
exitMinutesAfterOpen = input.int(20, title="Minutes After Open to Exit", minval=1)
emaLength = input.int(100, title="EMA Length", minval=1)
emaTimeframe = input.timeframe("240", title="EMA Timeframe")
useEMA = input.bool(true, title="Use EMA Filter")

// Market Selection Input
marketSelection = input.string("US", title="Select Market", options=["US", "Asia", "Europe"])

// Timezone for each market
marketTimezone = marketSelection == "US" ? "America/New_York" :
                 marketSelection == "Asia" ? "Asia/Tokyo" :
                 "Europe/London"  // Default to London for Europe

// Market Open and Close Times for each market
var int marketOpenHour = na
var int marketOpenMinute = na
var int marketCloseHour = na
var int marketCloseMinute = na

if marketSelection == "US"
    marketOpenHour := 9
    marketOpenMinute := 30
    marketCloseHour := 16
    marketCloseMinute := 0
else if marketSelection == "Asia"
    marketOpenHour := 9
    marketOpenMinute := 0
    marketCloseHour := 15
    marketCloseMinute := 0
else if marketSelection == "Europe"
    marketOpenHour := 8
    marketOpenMinute := 0
    marketCloseHour := 16
    marketCloseMinute := 30

// 3commas Bot Settings
emailToken = input.string('', title='Email Token', group='3commas Bot Settings')
long_bot_id = input.string('', title='Long Bot ID', group='3commas Bot Settings')
usePairAdjust = input.bool(false, title='Use this pair in PERP', group='3commas Bot Settings')
selectedExchange = input.string("Binance", title="Select Exchange", group='3commas Bot Settings', options=["Binance", "OKX", "Gate.io", "Bitget"])

// Determine the trading pair based on settings
var pairString = ""
if usePairAdjust
    pairString := str.tostring(syminfo.currency) + "_" + str.tostring(syminfo.basecurrency) + (selectedExchange == "OKX" ? "-SWAP" : "") 
else
    pairString := str.tostring(syminfo.currency) + "_" + str.tostring(syminfo.basecurrency)

// Function to check if it's a trading day (excluding weekends)
isTradingDay(t) =>
    dayOfWeek = dayofweek(t, marketTimezone)
    dayOfWeek >= dayofweek.monday and dayOfWeek <= dayofweek.friday

// Function to get the timestamp for market open and close times
getMarketTimes(t) =>
    y = year(t, marketTimezone)
    m = month(t, marketTimezone)
    d = dayofmonth(t, marketTimezone)
    marketOpenTime = timestamp(marketTimezone, y, m, d, marketOpenHour, marketOpenMinute, 0)
    marketCloseTime = timestamp(marketTimezone, y, m, d, marketCloseHour, marketCloseMinute, 0)
    [marketOpenTime, marketCloseTime]

// Get the current time in the market's timezone
currentTime = time

// Calculate market times
[marketOpenTime, marketCloseTime] = getMarketTimes(currentTime)

// Calculate entry and exit times
entryTime = marketCloseTime - entryMinutesBeforeClose * 60 * 1000
exitTime = marketOpenTime + exitMinutesAfterOpen * 60 * 1000

// Get EMA data from the specified timeframe
emaValue = request.security(syminfo.tickerid, emaTimeframe, ta.ema(close, emaLength))

// Entry condition with optional EMA filter
longCondition = close > emaValue or not useEMA

// Functions to create JSON strings
getEnterJson() =>
    '{"message_type": "bot", "bot_id": "' + long_bot_id + '", "email_token": "' + emailToken + '", "delay_seconds": 0, "pair": "' + pairString + '"}'

getExitJson() =>
    '{"action": "close_at_market_price", "message_type": "bot", "bot_id": "' + long_bot_id + '", "email_token": "' + emailToken + '", "delay_seconds": 0, "pair": "' + pairString + '"}'

// Entry Signal
entrySignal = isTradingDay(currentTime) and currentTime >= entryTime and currentTime < marketCloseTime and dayofweek(currentTime, marketTimezone) != dayofweek.friday

// Exit Signal
exitSignal = isTradingDay(currentTime) and currentTime >= exitTime and currentTime < marketCloseTime

// Entry Logic
if strategy.position_size == 0 and longCondition
    strategy.entry("Long", strategy.long, alert_message=getEnterJson())

// Exit Logic
if  strategy.position_size > 0
    strategy.close("Long", alert_message=getExitJson())

// Force Close Logic on Friday before market close
isFriday = dayofweek(currentTime, marketTimezone) == dayofweek.friday
if  strategy.position_size > 0  // Close 5 minutes before market close on Friday
    strategy.close("Long", comment="Force close on Friday before market close", alert_message=getExitJson())

// Plotting entry and exit points
plotshape( strategy.position_size == 0 and longCondition, title="Entry", text="Entry", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape( strategy.position_size > 0, title="Exit", text="Exit", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)

// Plot EMA for reference
plot(useEMA ? emaValue : na, title="EMA", color=color.blue)