비활성 범위 반전 전략

저자:차오장, 날짜: 2023-10-30 10:54:00
태그:

img

전반적인 설명

비활성 범위 반전 전략은 변동성이 감소하는 기간을 입력 신호로 활용하고 변동성이 다시 상승할 때 이익을 목표로합니다. 가격이 좁은 비활성 범위 내에서 포함되는 상황을 식별하고 다가오는 가격 추세를 포착합니다. 현재 변동성이 낮지만 돌파구가 예상되는 경우이 전략이 잘 작동합니다.

전략 논리

전략은 먼저 잠복한 범위를 식별합니다. 이것은 가격이 이전 거래 날의 가격 범위에 포함되었을 때입니다. 이것은 변동성이 며칠 전과 비교하여 감소했다는 것을 나타냅니다. 우리는 현재 하루의 높은 < n 일 전의 높은 (일반적으로 4 일) 및 현재 하루의 낮은 > n 일 전의 낮은 상태를 확인하여 잠복한 범위에 해당하는지 확인합니다.

잠복한 범위가 확인되면 전략은 대기 중인 두 개의 주문을 배치합니다. 범위의 꼭대기에 가까운 구매 중지 및 범위의 하단에 가까운 판매 중지. 그 다음 가격이 상향 또는 하향적으로 범위를 깨는 것을 기다립니다. 가격이 상향으로 깨지면 구매 주문이 길게됩니다. 가격이 하향으로 깨지면 판매 주문이 짧게됩니다.

엔트리 후, 스톱 로스 및 영업 주문이 배치됩니다. 스톱 로스는 하락 위험을 제어하고 영업은 수익을 위해 거래를 종료합니다. 스톱 로스는 위험 매개 변수에서 정의된 엔트리 가격에서 % 거리에 배치됩니다. 영업은 이전 변동성과 유사한 가격 이동을 예상하기 때문에 잠복 한 범위 크기와 동등한 거리에 배치됩니다.

마지막으로, 고정 분수 포지션 사이징 모델은 거래 크기를 관리합니다. 위험 조정 수익을 향상시키기 위해 수익의 크기를 증가시키고 손실의 크기를 줄입니다.

장점

이 전략의 장점은 다음과 같습니다.

  1. 약화율을 신호로 사용하여 다가오는 트렌드를 포착합니다.

  2. 쌍방향 주문은 상승 추세 또는 하락 추세를 잡습니다.

  3. 스톱 로스 및 수익을 취하는 것은 단일 거래 위험을 통제합니다.

  4. 고정된 분자 크기는 자본 효율을 향상시킵니다.

  5. 간단한 논리, 쉽게 구현할 수 있는

위험성

고려해야 할 위험은 다음과 같습니다.

  1. 범위를 알 수 없는 경우 잘못된 탈출 방향

  2. 브레이크오웃은 단기적인 반전일 수도 있고 지속적인 트렌드가 아닐 수도 있습니다.

  3. 큰 움직임에 의해 제거 될 위험을 중지 손실.

  4. 고정 분자 크기는 손실 트레이드를 추가할 때 손실을 증폭시킬 수 있습니다.

  5. 매개 변수가 제대로 설정되지 않으면 성능이 좋지 않습니다.

더 나은 기회

전략을 강화하는 몇 가지 방법:

  1. 잘못된 유출을 피하기 위해 분리가 있는 필터를 추가합니다.

  2. 트래일링 또는 명령 스톱 손실로 손실을 중지하십시오.

  3. 트렌드 필터를 추가하여 트렌드 반대 항목을 피합니다.

  4. 균형 잡힌 위험/이익을 위해 고정 분자 비율을 최적화합니다.

  5. 엣지를 개선하기 위해 여러 시간 프레임을 보세요.

  6. 자동화된 매개 변수 최적화를 위해 기계 학습을 활용합니다.

결론

잠복한 범위 반전 전략은 명확한 논리와 수익 잠재력을 가지고 있습니다. 최적화, 위험 관리 및 신호 필터링을 통해 세밀한 조정으로 일관성을 더욱 향상시킬 수 있습니다. 그러나 모든 평균 반전 전략은 고유한 위험을 가지고 있으며 위치 사이징이 제어되어야합니다. 반전 전술에 익숙하고 적절한 위험 인식을 가진 거래자에게 적합합니다.


/*backtest
start: 2023-09-29 00:00:00
end: 2023-10-29 00:00:00
period: 1d
basePeriod: 1h
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/
// © gsanson66


//This code is based on the Narrow Range strategy
//Interactive Broker fees are applied on this strategy
//@version=5
strategy("NARROW RANGE BACKTESTING", shorttitle="NR BACKTESTING", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, commission_type=strategy.commission.percent, commission_value=0.18)


//--------------------------------FUNCTIONS------------------------------------//

//@function to print label
debugLabel(txt, color) =>
    label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)

//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)


//--------------------------------USER INPUTS------------------------------------//

//Narrow Range Length 
nrLength = input.int(4, minval=2, title="Narrow Range Length", group="Strategy parameters")
//Risk Management
stopLossInput = input.float(0.5, title="Stop Loss (in percentage of reference range)", group="Strategy parameters")
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management")
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management")
//Backtesting period
startDate = input(title="Start Date", defval=timestamp("1 Janv 2020 00:00:00"), group="Backtesting Period")
endDate = input(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")


//--------------------------------VARIABLES INITIALISATION--------------------------//
strategy.initial_capital = 50000
bool nr = na
var bool long = na
var bool short = na
var float stopPriceLong = na
var float stopLossLong = na
var float takeProfitLong = na
var float stopPriceShort = na
var float stopLossShort = na
var float takeProfitShort = na
var float takeProfit = na
var float stopLoss = na
bool inRange = na
int closedtrades = strategy.closedtrades
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95


//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//

//Checking if the date belong to the range
inRange := true

//Checking performances of the strategy
if equity > capital_ref + fixedRatio
    spread = (equity - capital_ref)/fixedRatio
    nb_level = int(spread)
    increasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder + increasingOrder
    capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
    spread = (capital_ref - equity)/fixedRatio
    nb_level = int(spread)
    decreasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder - decreasingOrder
    capital_ref := capital_ref - nb_level*fixedRatio

//We check if a trade has been closed to cancel all previous orders
if closedtrades > closedtrades[1]
    strategy.cancel("Long")
    strategy.cancel("Short")
    stopPriceLong := na
    stopPriceShort := na

//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
    debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
    strategy.close_all()
    long := na
    short := na
    stopPriceLong := na
    stopLossLong := na
    takeProfitLong := na
    stopPriceShort := na
    stopLossShort := na
    takeProfitShort := na
    takeProfit := na
    stopLoss := na

//----------------------------------FINDING NARROW RANGE DAY------------------------------------------//

// We find the Narrow Range Day
if low > low[nrLength] and high < high[nrLength]
    nr := true 


//------------------------------------STOP ORDERS--------------------------------------------//

// We handle plotting of stop orders and cancellation of other side order if one order is triggered
if strategy.position_size > 0 and not na(stopPriceLong) and not na(stopPriceShort)
    long := true
    strategy.cancel("Short")
    stopPriceLong := na
    stopPriceShort := na
    takeProfit := takeProfitLong
    stopLoss := stopLossLong
if strategy.position_size < 0 and not na(stopPriceLong) and not na(stopPriceShort)
    short := true
    strategy.cancel("Long") 
    stopPriceLong := na
    stopPriceShort := na
    takeProfit := takeProfitShort
    stopLoss := stopLossShort


//------------------------------------STOP LOSS & TAKE PROFIT--------------------------------//

// If an order is triggered we plot TP and SL
if not na(takeProfit) and not na(stopLoss) and long
    if high >= takeProfit and closedtrades == closedtrades[1] + 1
        takeProfit := na
        stopLoss := na
        long := na
    if low <= stopLoss and closedtrades == closedtrades[1] + 1
        takeProfit := na
        stopLoss := na
        long := na
if not na(takeProfit) and not na(stopLoss) and short
    if high >= stopLoss and closedtrades == closedtrades[1] + 1
        takeProfit := na
        stopLoss := na
        short := na
    if low <= takeProfit and closedtrades == closedtrades[1] + 1
        takeProfit := na
        stopLoss := na
        short := na


//-----------------------------LONG/SHORT CONDITION-------------------------//

// Conditions to create two stop orders (one for Long and one for Short) and SL & TP calculation
if nr and inRange and strategy.position_size == 0
    stopPriceLong := high[4]
    takeProfitLong := high[4] + (high[4] - low[4])
    stopLossLong := high[4] - (high[4] - low[4])*stopLossInput
    qtyLong = cashOrder/stopPriceLong
    strategy.entry("Long", strategy.long, qtyLong, stop=stopPriceLong)
    strategy.exit("Exit Long", "Long", limit=takeProfitLong ,stop=stopLossLong)
    stopPriceShort := low[4]
    takeProfitShort := low[4] - (high[4] - low[4])
    stopLossShort := low[4] + (high[4] - low[4])*stopLossInput
    qtyShort = cashOrder/stopPriceShort
    strategy.entry("Short", strategy.short, qtyShort, stop=stopPriceShort)
    strategy.exit("Exit Short", "Short", limit=takeProfitShort ,stop=stopLossShort)


//--------------------------PLOTTING ELEMENT----------------------------//

plotshape(nr, "NR", shape.arrowdown, location.abovebar, color.rgb(255, 132, 0), text= "NR4", size=size.huge)
plot(stopPriceLong, "Stop Order", color.blue, 3, plot.style_linebr)
plot(stopPriceShort, "Stop Order", color.blue, 3, plot.style_linebr)
plot(takeProfit, "Take Profit", color.green, 3, plot.style_linebr)
plot(stopLoss, "Stop Loss", color.red, 3, plot.style_linebr)

더 많은