시간 제한이 있는 이중 MA 전략

저자:차오장, 날짜: 2023-11-14 16:45:03
태그:

img

전반적인 설명

이 전략은 원래의 이중 이동 평균 전략에 기반한 시간 제한 모듈을 구현하여 전략의 시작 시간을 제어합니다. 시간 제한 모듈은 전략의 실행 시간을 효과적으로 관리하고 불리한 시장 조건에서 거래 위험을 줄일 수 있습니다.

원칙

이 전략은 빠른 MA와 느린 MA를 사용하여 거래 신호를 생성합니다. 빠른 MA는 14 일, 느린 MA는 21 일 기간을 가지고 있습니다. 빠른 MA가 느린 MA를 넘을 때 구매 신호가 생성됩니다. 빠른 MA가 느린 MA를 넘을 때 판매 신호가 생성됩니다.

이 전략은 또한 원래 무역 방향을 뒤집기 위한 무역 역전 옵션을 포함합니다.

시간 제한 모듈은 현재 시간을 구성된 시작 시간과 비교하여 타임 스탬프를 사용하여 true 또는 false를 반환하여 전략이 시작되는지 아닌지를 제어합니다. 시작 년, 달, 날, 시간 및 분을 설정해야합니다. 전략은 현재 시간이 구성된 시작 시간을 초과하면 시작됩니다.

장점

  • 이중 MAs는 중장기 및 단기 동향을 효과적으로 포착합니다.
  • 시간 제한 모듈은 전략의 실행 시간을 정확하게 제어하여 불리한 시장 조건에서 불필요한 거래를 피합니다.
  • 거래 역전 옵션은 유연성을 추가합니다.

위험 과 해결책

  • 이중 MAs는 과도한 거래 신호를 생성하여 거래 빈도와 비용을 증가시킬 수 있습니다.
  • 잘못된 시간 제한 구성으로 인해 기회를 놓칠 수 있습니다.
  • 잘못된 거래 반전은 잘못된 거래 신호로 이어질 수 있습니다.

MA 기간을 최적화하면 거래 빈도를 줄일 수 있습니다. 놓친 기회를 피하기 위해 시작 시간을 합리적으로 설정해야합니다. 마지막으로 시장 조건에 따라 신호를 반전할지 여부를 신중하게 선택하십시오.

최적화 방향

  • 스톱 로스 모듈을 추가하면 개별 거래의 위험을 더 잘 제어 할 수 있습니다.
  • 줄기 줄기 지점을 점진적으로 이동시키는 후속 스톱 손실을 구현하면 이익을 잠금하는 데 도움이 될 수 있습니다.
  • 여러 개의 기호를 통해 신호를 결합하면 신호 품질을 향상시키고 잘못된 신호를 줄일 수 있습니다.
  • 자동으로 최적의 매개 변수 조합을 찾는 매개 변수 최적화 모듈 개발

요약

이 전략은 이중 MAs를 사용하여 거래 신호를 생성하고 시간 제한 모듈로 실행 시간을 제어하여 불리한 시장 조건을 피하면서 트렌드를 효과적으로 캡처합니다. 매개 변수 조정, 스톱 로스 모듈, 크로스 자산 신호 생성 등을 통해 추가 개선이 가능하여 거래 빈도를 줄이고 각 거래의 안정성과 수익성을 향상시킵니다.


/*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)


더 많은