Estrategia de negociación de ruptura a corto plazo de inversión

El autor:¿ Qué pasa?, Fecha: 2023-11-21 17:03:32
Las etiquetas:

img

Resumen general

Esta estrategia tiene como objetivo capturar oportunidades comerciales de reversión a corto plazo. Abrirá una posición corta después de N barras ascendentes consecutivas y cerrará una posición después de M barras descendentes consecutivas. También incorpora filtros de marco de tiempo y características de stop loss / take profit.

La lógica

  1. Parámetros de entrada: número de barras ascendentes consecutivas N, barras descendentes consecutivas M
  2. Definición:
    • ups cuenta el número de barras superiores, precio>precio[1] luego +1, de lo contrario se restablece a 0
    • dns cuenta el número de barras hacia abajo, precio
  3. Entrada: corta cuando ups≥N; posición cerrada cuando dns≥M
  4. Exit: límite de pérdida fijo/beneficio de toma o final del período de tiempo

Ventajas

  1. Captura de oportunidades de negociación de inversión, adecuadas para negociación a corto plazo
  2. Establecimiento de plazos flexibles para adaptarse a los diferentes planes comerciales
  3. Se incluye un stop loss/take profit incorporado que facilita la gestión del riesgo

Los riesgos

  1. La inversión a corto plazo puede fracasar y volver a invertirse, lo que conduce a pérdidas.
  2. Parámetros razonables N, M necesarios, demasiado grandes o muy pequeños desfavorables
  3. El tiempo de parada incorrecto puede no ser capaz de detener la pérdida a tiempo

Direcciones de optimización

  1. Combinar con el indicador de tendencia para evitar operaciones contra tendencia
  2. Ajuste dinámico de los parámetros N, M
  3. Optimizar el mecanismo de stop loss

Conclusión

La estrategia captura oportunidades comerciales a corto plazo a través de patrones estadísticos de la línea K. Un ajuste razonable de parámetros y medidas de control de riesgos son cruciales para obtener ganancias 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)






Más.