동력 역전 거래 전략

저자:차오장, 날짜: 2023-10-07 16:52:05
태그:

전반적인 설명

이 전략은 모멘텀 역전 거래의 개념을 기반으로 합니다. 현재 트렌드 방향을 결정하기 위해 RSI, 스톡 및 MACD를 사용하며, 트렌드 역전을 효율적으로 포착할 수 있는 자동화된 거래 전략을 구현하기 위해 ATR을 기반으로 스톱 로스를 설정하고 수익을 취합니다.

거래 논리

이 전략은 현재 트렌드 방향을 결정하기 위해 RSI, Stoch 및 MACD를 세 가지 지표로 사용합니다. 구체적인 논리는 다음과 같습니다.

  • RSI ((7): 50 이상의 RSI는 상승 추세를 나타내고, 50 이하는 하락 추세를 나타냅니다.
  • 주식 (%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가 모두 동의하면 트렌드 반전 가능성이 높습니다.

  2. ATR Stop Loss 및 Take Profit 설정은 합리적입니다. ATR은 시장 변동성을 효과적으로 추적 할 수 있습니다. ATR의 배수를 사용하여 시장 조건에 따라 스톱 및 타겟을 동적으로 조정 할 수 있습니다.

  3. 단순하고 명확한 논리, 이해하기 쉽고 자동화. 자동화 거래 전략으로 적합합니다.

위험 분석

이 전략의 위험은 다음과 같습니다.

  1. 개별 지표의 오류는 입력 시점에 영향을 미칠 수 있습니다. 오류를 줄이기 위해 매개 변수를 조정하거나 더 많은 확인 지표를 추가하는 것을 고려할 수 있습니다.

  2. ATR의 크기는 정지 및 목표물에 크게 영향을 미칩니다. 잘못된 ATR 계산으로 인해 정지가 너무 넓거나 목표물이 너무 좁을 수 있습니다. ATR을 확인하기 위해 추가 지표를 추가 할 수 있습니다.

  3. 트렌드 결정의 부족. 역전 거래에 초점을 맞추고, 불충분한 트렌드 분석은 시장의 범위에서 위프사우로 이어질 수 있습니다. 트렌드 지표를 추가 할 수 있습니다.

  4. 과도한 부착 위험. 매개 변수와 규칙의 안정성을 확인하기 위해 철저한 백테스팅이 필요합니다.

개선 방향

이 전략의 가능한 개선 사항:

  1. 전환점을 결정하는 정확성을 높이기 위해 지표를 조정하거나 추가합니다. 예를 들어 과잉 구매/ 과잉 판매 수준을 확인하기 위해 볼링거 밴드를 추가합니다.

  2. 변동성을 더 잘 추적하기 위해 ATR 계산을 최적화합니다. 예를 들어 ATR / 가격 비율을 사용하여.

  3. 트렌드 지표를 추가하여 변화 시장에서 현상을 피합니다. 예를 들어 이동 평균

  4. 자금 관리 최적화, 마감에 따라 포지션 크기를 조정하는 등.

  5. 기간 최적화 시간 프레임에 걸쳐 견고성을 테스트하기 위해.

  6. 신뢰성을 확인하기 위해 다양한 제품과 기간에 대한 더 많은 백테스팅.

요약

이 전략은 역동 역전 개념에 기초하여 설계되었으며, 역전을 식별하기 위해 RSI, 스톡 및 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*********************************






















더 많은