Estratégia de negociação de breakout de curto prazo de reversão

Autora:ChaoZhang, Data: 2023-11-21 17:03:32
Tags:

img

Resumo

Esta estratégia visa capturar oportunidades de negociação de reversão de curto prazo. Abrirá uma posição curta após N barras ascendentes consecutivas e fechará uma posição após M barras descendentes consecutivas.

É lógica.

  1. Parâmetros de entrada: Número de barras ascendentes consecutivas N, barras descendentes consecutivas M
  2. Definição:
    • ups conta o número de barras acima, preço>preço[1] em seguida, +1, caso contrário, redefine para 0
    • dns conta o número de barras para baixo, preço
  3. Entrada: curta quando ups≥N; posição próxima quando dns≥M
  4. Exit: stop loss/take profit fixo ou final do período de tempo

Vantagens

  1. Captura de oportunidades de negociação de reversão, adequadas para negociação a curto prazo
  2. Flexível definição de prazos para atender a diferentes planos de negociação
  3. O valor da posição em risco deve ser calculado em função da posição em risco da instituição.

Riscos

  1. A reversão a curto prazo pode falhar e reverter-se novamente, levando a perdas
  2. Parâmetros N, M razoáveis necessários, demasiado grandes ou demasiado pequenos desfavoráveis
  3. Tempo de parada inadequado pode não ser capaz de parar a perda no tempo

Orientações de otimização

  1. Combinar com o indicador de tendência para evitar contra as operações de tendência
  2. Ajuste dinâmico dos parâmetros N, M
  3. Otimizar o mecanismo de stop loss

Conclusão

A estratégia capta oportunidades de negociação de curto prazo através de padrões estatísticos de linha K. Ajuste razoável de parâmetros e medidas de controle de risco são cruciais para lucros constantes.


/*backtest
start: 2023-11-13 00:00:00
end: 2023-11-20 00:00:00
period: 3h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4

// Strategy
strategy("Up/Down Short Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)

// There will be no short entries, only exits from long.
strategy.risk.allow_entry_in(strategy.direction.short)

consecutiveBarsUp = input(1, title='Consecutive Bars Up')
consecutiveBarsDown = input(1, title='Consecutive Bars Down')

price = close

ups = 0.0
ups := price > price[1] ? nz(ups[1]) + 1 : 0

dns = 0.0
dns := price < price[1] ? nz(dns[1]) + 1 : 0

// Strategy Backtesting
startDate  = input(timestamp("2021-01-01T00:00:00"), type = input.time, title='Backtesting Start Date')
finishDate = input(timestamp("2021-12-31T00:00:00"), type = input.time, title='Backtesting End Date')

time_cond  = true

//Time Restriction Settings
startendtime = input("", title='Time Frame To Enter Trades')
enableclose = input(false, title='Enable Close Trade At End Of Time Frame')
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, startendtime))

// Stop Loss & Take Profit Tick Based
enablesltp = input(false, title='Enable Take Profit & Stop Loss')
stopTick = input(5.0, title='Stop Loss Ticks', type=input.float) / 100
takeTick = input(10.0, title='Take Profit Ticks', type=input.float) / 100

longStop = strategy.position_avg_price - stopTick
shortStop = strategy.position_avg_price + stopTick
shortTake = strategy.position_avg_price - takeTick
longTake = strategy.position_avg_price + takeTick

plot(strategy.position_size > 0 and enablesltp ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL")
plot(strategy.position_size < 0 and enablesltp ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL")
plot(strategy.position_size > 0 and enablesltp ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enablesltp ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")

// Alert messages
message_enterlong  = input("", title="Long Entry message")
message_entershort = input("", title="Short Entry message")
message_closelong = input("", title="Close Long message")
message_closeshort = input("", title="Close Short message")
message_takeprofit = input("", title="Take Profit message")
message_stoploss = input("", title="Stop Loss message")

// Strategy Execution
if (ups >= consecutiveBarsUp) and time_cond and timetobuy
    strategy.entry("Long", strategy.long, stop = high + syminfo.mintick, alert_message = message_enterlong)
    
if (dns >= consecutiveBarsDown) and time_cond and timetobuy
    strategy.entry("Short", strategy.short, stop = low + syminfo.mintick, alert_message = message_entershort)
    
if strategy.position_size > 0 and timetoclose and enableclose
    strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose
    strategy.close_all(alert_message = message_closeshort)
    
if strategy.position_size > 0 and enablesltp and time_cond
    strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_takeprofit)
if strategy.position_size < 0 and enablesltp and time_cond
    strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_stoploss)






Mais.