모멘텀 반전 전략


생성 날짜: 2023-10-07 16:52:05 마지막으로 수정됨: 2023-10-07 16:52:05
복사: 0 클릭수: 675
avatar of ChaoZhang ChaoZhang
1
집중하다
1621
수행원

개요

이 전략은 동력 반전의 거래 철학에 기초하여 RSI, Stoch 및 MACD의 3 개의 지표를 통해 현재 추세를 판단하고, ATR와 결합하여 스톱 로스 스톱 포즈를 설정하여 추세 반전을 효율적으로 포착하는 자동 거래 전략을 구현합니다.

전략 원칙

이 전략은 RSI, Stoch, MACD의 세 가지 지표를 사용하여 현재 트렌드 방향을 판단합니다. 구체적인 논리는 다음과 같습니다:

  • RSI (7일): RSI 값이 50보다 높으면 상승, 50보다 낮으면 하락
  • Stoch ((%K,14,3,3): %K 값이 50보다 크면 부진, 50보다 작으면 하락
  • MACD ((12,26,9): MACD는 시그널보다 크고 시그널보다 작다

세 지표가 동시에 상승하면 바가 녹색으로 설정되며, 세 지표가 동시에 하락하면 바가 빨간색으로 설정되며, 지표 신호가 모순되면 검은색으로 설정됩니다.

거래 규칙은 다음과 같습니다.

  • 현재 바가 초록색이고 이전 바가 검은색 또는 빨간색일 때, 더 많은 입장이 이루어지며, 입장은 그 바의 최고점과 0.01을 더합니다.
  • 현재 바가 빨간색이고 이전 바가 검은색 또는 초록색일 때, 공백으로 진입하여 진입 가격은 바의 하위점으로 0.01을 니다.
  • 다자 포지션 기간 동안 빨간색 또는 검은색 바가 나타나면 평점 포지션
  • 공백 상태에서 녹색 또는 검은색 바가 나타나면 공백 상태

이 전략은 또한 ATR ((7일 평균선) 을 사용하여 스톱 로드 스톱 위치를 설정한다. 스톱 로드는 ATR의 1.5배이고, 스톱 로드는 ATR의 3배이다.

우위 분석

이 전략은 다음과 같은 장점을 가지고 있습니다.

  1. 다중 지표를 사용하여 트렌드를 판단하여 가짜 브레이크를 효과적으로 필터링 할 수 있습니다. RSI, Stoch 및 MACD의 3 개의 지표가 동시에 상승하거나 하락하면, 추세 반전 지점이 될 가능성이 높습니다.

  2. ATR 스톱포드 설정이 우수하다. ATR은 시장의 변동 정도를 효과적으로 추적할 수 있으며, ATR의 여러 배의 스톱포드 설정을 사용하여 시장 상황에 따라 스톱포드 위치를 조정할 수 있으며, 스톱포드가 너무 느슨하거나 너무 단단하지 않도록 방지한다.

  3. 거래 논리는 간단하고 명확하며, 이해하기 쉬운 구현으로 자동 거래 전략으로 사용할 수 있습니다.

위험 분석

이 전략에는 다음과 같은 위험도 있습니다.

  1. 다중 지표 조합 판단 개별 지표가 잘못된 신호를 보내는 경우가 있을 수 있으므로 출전 시기를 영향을 미칩니다. 지표 매개 변수를 조정하거나 다른 지표를 추가하여 검증하여 잘못된 신호율을 줄이는 것을 고려할 수 있습니다.

  2. ATR 크기는 스톱포드에 큰 영향을 미칩니다. ATR 계산이 정확하지 않으면 스톱포드가 너무 크거나 너무 작을 수 있습니다. ATR 크기를 확인하기 위해 다른 지표를 추가하는 것을 고려할 수 있습니다.

  3. 트렌드 판단이 부족하다. 이 전략은 역전 거래에 초점을 맞추고, 트렌드 판단이 부족하며, 불안정한 상황에서 갇히기 쉽다. 트렌드 지표 보조 판단을 추가할 수 있다.

  4. 과도한 적합의 위험이 있다. 충분한 재검토가 이루어져야 하고, 매개 변수와 규칙의 신뢰성이 검증되어야 한다.

최적화 방향

이 정책은 다음과 같은 측면에서 최적화될 수 있습니다.

  1. 트렌드 반전의 시점을 판단하는 정확도를 높이기 위해 지표를 조정하거나 추가하십시오. 예를 들어, 부린 라인을 추가하여 과매도 과매도 상태를 판단하십시오.

  2. ATR을 계산하는 방법을 최적화하여 시장의 변동을 더 잘 추적할 수 있다. 예를 들어 ATR을 가격에 대한 비율로 사용한다.

  3. 트렌드를 판단하는 지표를 추가하여, 변동적인 상황에서 함축되는 것을 피한다. 예를 들어, 이동 평균을 추가하여 트렌드 방향을 판단한다.

  4. 자금 관리를 최적화하여, 예를 들어, 철수 상황에 따라 포지션을 조정합니다.

  5. 주기 최적화를 수행하고, 다른 시간 주기 파라미터의 안정성을 검증한다.

  6. 더 많은 품종과 시간대에 걸쳐 재검토하여 전략의 안정적 신뢰성을 확인한다.

요약하다

이 전략은 동력 반전 사고방식 설계에 기초하여 RSI, Stoch 및 MACD 포트폴리오를 사용하여 트렌드 반전 시점을 판단하고 ATR 동적 설정 중지 손실 중지와 함께 전체적인 트렌드 반전 거래 전략을 형성합니다. 전략은 거래 논리가 명확하고 중지 손실 중지 설정이 합리적입니다. 그러나 지표 신호 오류, 트렌드 판단이 부족합니다. 향후 지표 매개 변수를 최적화하고 트렌드 판단에 참여하고 재원 관리를 조정하는 측면에서 개선 할 수 있습니다. 전략이 더 안정적이고 신뢰할 수 있습니다.

전략 소스 코드
/*backtest
start: 2023-09-06 00:00:00
end: 2023-10-06 00:00:00
period: 2h
basePeriod: 15m
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/
// © jwitt98
//The PowerX strategy - based on the rules outlined in the book "The PowerX Strategy: How to Trade Stocks and Options in Only 15 Minutes a Day" by Markus Heitkoetter

//@version=5
strategy("PowerX", overlay=true)
strategy.initial_capital = 50000
longEntry = "Enter long"
shortEntry = "Enter short"
longExit = "Exit long"
shortExit = "Exit short"

//*********************************Begin inputs*********************************

//get time range inputs and set time range bool
timeRangeGroup = "Select the trading range"
startDate = input(timestamp("1 Jan 2021 00:00 +0000"), "Start date", "Select the start date for the trading range", "", timeRangeGroup)
endDate = input(timestamp("1 Jan 2050 00:00 +0000"), "End date", "Select the end date for the trading range", "", timeRangeGroup)
isInTimeRange = true

//get long/short inputs
positionsAllowedGroup = "Select the direction(s) of trades to allow"
isLongsAllowed = input.bool(true, "Allow long positions", "Check the box if you want to allow long positions", "", positionsAllowedGroup)
isShortsAllowed = input.bool(true, "Allow short positions", "Check the box if you want to allow short positions", "", positionsAllowedGroup)

//get the stop loss and profit target multiples.  Per the PowerX rules the ratio shoud be 1:2.  1.5 and 3 are defaults
adrMultuplesGroup="Select the multipliers for the stop loss and profit targets"
stopLossMultiple = input.float(1.5, "Stop loss multiple", 0.1, 10, 0.1, "The ADR is multiplied by the stop loss multiple to calculate the stop loss", group=adrMultuplesGroup)
profitTargetMultiple=input.float(3.0, "Profit target multiple", 0.1, 10, 0.1, "The ADR is multiplied by the profit target multiple to calculate the profit target", group=adrMultuplesGroup)

//get the option to use the money management stategy or not.  This is a fixed ratio type management system
moneyManagementGroup="Money management"
isUsingMoneyManagement=input.bool(false, "Use money management", "Check the box if you want to use a fixed ratio type money management system, such as the type described in PowerX", group=moneyManagementGroup)
initial_riskPercent=input.float(2.0, "Percent risk per trade", .1, 100, .1, "The percentage of capital you want to risk when starting out.  This will increase or decrease base on the money management rules.  Only applicable if money managent is used", group=moneyManagementGroup)/100
isRiskDowsideLimited=input.bool(false, "Keep risk at or above the set point", "Check the box if you don't want the risk to fall below the set \"risk per trade\" percentage, for example, when your equity is underwater. Only applicable if money management is used", "", moneyManagementGroup)
initial_riskPerTrade=initial_riskPercent * strategy.initial_capital 
riskFactor = 0.0
currentProfit = 0.0
currentRisk = 0.0

//*********************************End inputs*********************************

//*********************************Begin money management*********************************

if(isUsingMoneyManagement)
    currentProfit := strategy.equity - strategy.initial_capital
    if(currentProfit < 0)
        currentProfit:=math.abs(currentProfit)
        riskFactor := 0.5*(math.pow(1+8*currentProfit/(2*initial_riskPerTrade), 0.5)+1)
        currentRisk := 1/riskFactor * initial_riskPercent * strategy.initial_capital
        if(isRiskDowsideLimited)
            currentRisk := initial_riskPerTrade
    else
        riskFactor := 0.5*(math.pow(1+8*currentProfit/(2*initial_riskPerTrade), 0.5)+1)
        currentRisk := riskFactor * initial_riskPercent * strategy.initial_capital
        
plot(strategy.equity, "Strategy equity")
plot(currentRisk, "Current risk")
plot(riskFactor, "Risk Factor")

//*********************************End money management*********************************


//*********************************Begin indicators*********************************
//4 indicators are used in this strategy, RSI(7), Stochastics(14, 3, 3), MACD(12, 26, 9), and ADR(7)

rsiVal = ta.rsi(close, 7)//this checks out
plot(rsiVal, "RSI(7)", color.lime)

stochKVal = ta.sma(ta.sma(ta.stoch(close, high, low, 14),3),3)//this formula checks out
plot(stochKVal, "Stoch %K", color.lime)

[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
plot(histLine, "MACD Hist", color.lime)

adr = ta.sma(high, 7) - ta.sma(low, 7)
plot(adr, "Average daily range", color.orange)


//*********************************End indicators*********************************

//*********************************Define the bar colors*********************************

greenBar = rsiVal > 50 and stochKVal > 50 and histLine > 0
redBar = rsiVal < 50 and stochKVal < 50 and histLine < 0
blackBar = not greenBar and not redBar

color currentBarColor = switch
    greenBar => color.green
    redBar => color.red
    blackBar => color.gray //because black is too hard to see in dark mmode
    => color.yellow
    
barcolor(currentBarColor)

//*********************************End defining the bar colors*********************************

//*********************************Define the entry, stop loss and profit target*********************************

longStopLimit = high + .01
longProfitTarget = high + (profitTargetMultiple * adr)
longStopLoss = high - (stopLossMultiple * adr)

shortStopLimit = low - .01
shortProfitTarget = low - (profitTargetMultiple * adr)
shortStopLoss = low + (stopLossMultiple * adr)

qtyToTrade= math.floor(currentRisk / (stopLossMultiple * adr))//only if using money management
if(qtyToTrade * high > strategy.equity)
    qtyToTrade := math.floor(strategy.equity / high)

//*********************************End defining stop loss and profit targets*********************************

//*********************************Execute trades, set rules, stop loss and profit targets*********************************

if (greenBar and not greenBar[1] and isInTimeRange and isLongsAllowed)
    if(isUsingMoneyManagement)
        strategy.order(longEntry, strategy.long, qtyToTrade, limit=longStopLimit, stop=longStopLimit)
        //strategy.order(longEntry, strategy.long, qtyToTrade, stop=longStopLimit)
    else
        strategy.order(longEntry, strategy.long, limit=longStopLimit,stop=longStopLimit)
        //strategy.order(longEntry, strategy.long, stop=longStopLimit)
    strategy.exit("Long limit/stop", from_entry=longEntry, limit=longProfitTarget, stop=longStopLoss)
    

if(blackBar or redBar)
    strategy.cancel(longEntry)
    strategy.close(longEntry, longExit)
    

if (redBar and not redBar[1] and isInTimeRange and isShortsAllowed)
    if(isUsingMoneyManagement)
        strategy.order(shortEntry, strategy.short, qtyToTrade, limit=shortStopLimit, stop=shortStopLimit)
        //strategy.order(shortEntry, strategy.short, qtyToTrade, stop=shortStopLimit)
    else
        strategy.order(shortEntry, strategy.short, limit=shortStopLimit, stop=shortStopLimit)
        //strategy.order(shortEntry, strategy.short, stop=shortStopLimit)
    strategy.exit("Short limit/stop", from_entry=shortEntry, limit=shortProfitTarget, stop=shortStopLoss)

if(blackBar or greenBar)
    strategy.cancel(shortEntry)
    strategy.close(shortEntry, shortExit)
    

//*********************************End execute trades, set rules, stop loss and profit targets*********************************