더블 MA 시간 제한 거래 전략


생성 날짜: 2023-11-14 16:45:03 마지막으로 수정됨: 2023-11-14 16:45:03
복사: 0 클릭수: 654
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

더블 MA 시간 제한 거래 전략

개요

이 전략은 원래의 쌍평선 거래 전략에 기초하여, 전략의 시작 시간을 제어하기 위해 시간 제한 모듈을 추가했다. 이 모듈은 전략의 실행 시간을 효과적으로 관리하고, 이상적이지 않은 시장 조건에서 거래 위험을 줄일 수 있다.

원칙

전략은 빠른 MA와 느린 MA를 사용하여 거래 신호를 구축한다. 빠른 MA의 매개 변수는 14일, 느린 MA의 매개 변수는 21일이다. 빠른 MA 상에서 느린 MA를 통과하면 구매 신호가 생성되며, 빠른 MA 아래에서 느린 MA를 통과하면 판매 신호가 생성된다.

이 전략은 또한 원래의 거래 신호의 방향을 되돌릴 수 있는 거래 반전 옵션을 도입했다.

시간 제한 모듈은 시간대를 통해 현재 시간과 설정된 시작 시간을 비교하여 실제 값을 반환하여, 전략이 시작되는지 여부를 제어한다. 이 모듈은 시작의 해, 달, 일, 시간, 분을 설정해야 하며, 현재 시간이 설정된 시간을 초과할 때만 정책이 시작된다.

장점

  • 이중 MA를 사용하여 거래 신호를 생성하여 중·단기 트렌드를 효과적으로 포착할 수 있습니다.
  • 시간 제한 모듈을 추가하여 전략의 실행 시간을 더 정확하게 제어하고, 이상적이지 않은 시장 조건에서 불필요한 거래를 피합니다.
  • 거래 역전 옵션은 전략의 유연성을 증가시킵니다.

위험과 해결

  • 이중 MA 전략은 거래 빈도와 거래 비용을 높이는 여러 거래 신호를 생성할 수 있습니다.
  • 시간 제한 모듈을 잘못 설정하면 놓친 거래 기회가 발생할 수 있습니다.
  • 거래 역전 선택이 잘못되면 거래 신호 오류가 발생할 수 있습니다.

적절한 MA 주기 파라미터를 최적화하여 거래 빈도를 낮출 수 있으며, 동시에 모듈의 시동 시간을 합리적으로 설정하여 기회를 놓치지 않도록 할 수 있습니다. 마지막으로, 다양한 시장 조건에 따라 거래 신호 방향을 역전할 필요가 있는지 신중하게 선택하십시오.

최적화 방향

  • 단편 거래의 위험을 더 잘 제어할 수 있는 스톱 로스 모듈을 추가
  • 모바일 스톱 트래킹을 추가하여 트렌드에 따라 스톱 포인트를 점진적으로 이동하여 수익을 추출할 수 있습니다.
  • 여러 스탠더드의 작동 신호를 결합하여 신호 품질을 향상시키고 가짜 신호를 줄일 수 있습니다.
  • 최적의 변수 조합을 자동으로 찾아내는 변수 최적화 모듈을 개발합니다.

요약하다

이 전략은 트레이딩 신호를 형성하는 쌍 MA를 통해 트레이딩 신호를 형성하고, 시간 제한 모듈 제어 전략의 실행 시간을 추가하여, 트렌드를 효과적으로 포착할 수 있으며, 동시에 이상적이지 않은 시장 조건의 위험을 회피할 수 있다. 이 전략은 또한 최적화 파라미터 설정, 손실 중지 모듈 및 크로스 스탠더드 운영 등의 수단으로 추가적으로 향상시킬 수 있으며, 거래 주파수를 줄이는 동시에 각 거래의 안정성과 수익성을 향상시킬 수 있다.

전략 소스 코드
/*backtest
start: 2023-11-06 00:00:00
end: 2023-11-13 00:00:00
period: 45m
basePeriod: 5m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=2

strategy(title = "Strategy Code Example", shorttitle = "Strategy Code Example", overlay = true)

// Revision:        1
// Author:          @JayRogers
//
// *** THIS IS JUST AN EXAMPLE OF STRATEGY TIME LIMITING ***
//
//  This is a follow up to my previous strategy example for risk management, extended to include a time limiting factor.

// === GENERAL INPUTS ===
// short ma
maFastSource   = input(defval = open, title = "Fast MA Source")
maFastLength   = input(defval = 14, title = "Fast MA Period", minval = 1)
// long ma
maSlowSource   = input(defval = open, title = "Slow MA Source")
maSlowLength   = input(defval = 21, title = "Slow MA Period", minval = 1)

// === STRATEGY RELATED INPUTS ===
tradeInvert     = input(defval = false, title = "Invert Trade Direction?")
// Risk management
inpTakeProfit   = input(defval = 1000, title = "Take Profit", minval = 0)
inpStopLoss     = input(defval = 200, title = "Stop Loss", minval = 0)
inpTrailStop    = input(defval = 200, title = "Trailing Stop Loss", minval = 0)
inpTrailOffset  = input(defval = 0, title = "Trailing Stop Loss Offset", minval = 0)
// *** FOCUS OF EXAMPLE ***
// Time limiting
// a toggle for enabling/disabling
useTimeLimit    = input(defval = true, title = "Use Start Time Limiter?")
// set up where we want to run from
startYear       = input(defval = 2016, title = "Start From Year",  minval = 0, step = 1)
startMonth      = input(defval = 05, title = "Start From Month",  minval = 0,step = 1)
startDay        = input(defval = 01, title = "Start From Day",  minval = 0,step = 1)
startHour       = input(defval = 00, title = "Start From Hour",  minval = 0,step = 1)
startMinute     = input(defval = 00, title = "Start From Minute",  minval = 0,step = 1)

// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit   = inpTakeProfit  >= 1 ? inpTakeProfit  : na
useStopLoss     = inpStopLoss    >= 1 ? inpStopLoss    : na
useTrailStop    = inpTrailStop   >= 1 ? inpTrailStop   : na
useTrailOffset  = inpTrailOffset >= 1 ? inpTrailOffset : na

// *** FOCUS OF EXAMPLE ***
// === TIME LIMITER CHECKING FUNCTION ===
// using a multi line function to return true or false depending on our input selection
// multi line function logic must be indented.
startTimeOk() =>
    // get our input time together
    inputTime   = timestamp(syminfo.timezone, startYear, startMonth, startDay, startHour, startMinute)
    // check the current time is greater than the input time and assign true or false
    timeOk      = time > inputTime ? true : false
    // last line is the return value, we want the strategy to execute if..
    // ..we are using the limiter, and the time is ok -OR- we are not using the limiter
    r = (useTimeLimit and timeOk) or not useTimeLimit

// === SERIES SETUP ===
/// a couple of ma's..
maFast = ema(maFastSource, maFastLength)
maSlow = ema(maSlowSource, maSlowLength)

// === PLOTTING ===
fast = plot(maFast, title = "Fast MA", color = green, linewidth = 2, style = line, transp = 50)
slow = plot(maSlow, title = "Slow MA", color = red, linewidth = 2, style = line, transp = 50)

// === LOGIC ===
// is fast ma above slow ma?
aboveBelow = maFast >= maSlow ? true : false
// are we inverting our trade direction?
tradeDirection = tradeInvert ? aboveBelow ? false : true : aboveBelow ? true : false

// *** FOCUS OF EXAMPLE ***
// wrap our strategy execution in an if statement which calls the time checking function to validate entry
// like the function logic, content to be included in the if statement must be indented.
if( startTimeOk() )
    // === STRATEGY - LONG POSITION EXECUTION ===
    enterLong = not tradeDirection[1] and tradeDirection
    exitLong = tradeDirection[1] and not tradeDirection
    strategy.entry( id = "Long", long = true, when = enterLong )
    strategy.close( id = "Long", when = exitLong )
    
    // === STRATEGY - SHORT POSITION EXECUTION ===
    enterShort = tradeDirection[1] and not tradeDirection
    exitShort = not tradeDirection[1] and tradeDirection
    strategy.entry( id = "Short", long = false, when = enterShort )
    strategy.close( id = "Short", when = exitShort )
    
    // === STRATEGY RISK MANAGEMENT EXECUTION ===
    strategy.exit("Exit Long", from_entry = "Long", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
    strategy.exit("Exit Short", from_entry = "Short", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)