Estrategia avanzada de trading cuantitativo: sistema de ejecución automatizado basado en el impulso intradiario y la gestión de riesgos

DOJI SL TP ATR momentum
Fecha de creación: 2025-02-21 14:25:50 Última modificación: 2025-02-27 16:57:06
Copiar: 2 Número de Visitas: 446
2
Seguir
319
Seguidores

Estrategia avanzada de trading cuantitativo: sistema de ejecución automatizado basado en el impulso intradiario y la gestión de riesgos Estrategia avanzada de trading cuantitativo: sistema de ejecución automatizado basado en el impulso intradiario y la gestión de riesgos

Descripción general

Se trata de una estrategia de negociación totalmente automatizada, basada en la dinámica diaria, combinada con una estricta gestión de riesgos y un sistema de gestión de posiciones preciso. La estrategia se ejecuta principalmente durante el horario de negociación en Londres, buscando oportunidades de negociación mediante la identificación de cambios en la dinámica del mercado y la exclusión de las formas de Doji, al tiempo que se aplica una regla de bloqueo diario para controlar el riesgo.

Principio de estrategia

La lógica central de la estrategia se basa en varios componentes clave. En primer lugar, el tiempo de negociación se limita al horario de Londres (excluyendo el 0 y el tiempo después del 19), para garantizar una fluidez adecuada del mercado. Las señales de entrada se basan en la movilidad de los precios.

Ventajas estratégicas

  1. Gestión integral del riesgo: incluye paradas de pérdidas fijas, reglas de paradas diarias y gestión dinámica de posiciones
  2. Adaptabilidad: el tamaño de las transacciones se ajusta automáticamente según los intereses de la cuenta y se adapta a diferentes tamaños de fondos
  3. Garantía de liquidez: la ejecución de las operaciones está estrictamente limitada a la hora de Londres para evitar el riesgo de baja liquidez.
  4. Filtración de señales falsas: reduce la pérdida de falsas brechas al excluir formas de Doji y señales continuas
  5. Claridad de la lógica de ejecución: las condiciones de entrada y salida son claras, lo que facilita la supervisión y optimización

Riesgo estratégico

  1. Riesgo de fluctuaciones en el mercado: el stop loss fijo puede no ser lo suficientemente flexible durante la alta volatilidad
  2. Riesgo de deslizamiento de precios: puede haber un deslizamiento más grande en un mercado con rápidas fluctuaciones
  3. Dependencia de la tendencia: la estrategia puede generar más señales falsas en mercados convulsionados
  4. Sensibilidad de los parámetros: la configuración de la parada de pérdidas tiene un gran impacto en el rendimiento de la estrategia Las soluciones incluyen: la adopción de mecanismos de parada de pérdidas dinámicas, el aumento de filtros de volatilidad del mercado, la introducción de indicadores de confirmación de tendencias, etc.

Dirección de optimización de la estrategia

  1. Introducción de un mecanismo de pérdidas adaptativo: rango de pérdidas de ajuste dinámico basado en el ATR o la volatilidad
  2. Aumentar el filtro de entornos de mercado: agregar indicadores de intensidad de tendencia y aumentar el tiempo de mantenimiento de las posiciones cuando hay una tendencia clara
  3. Mecanismo de confirmación de señal optimizado: mejora de la fiabilidad de la señal combinada con el volumen de tráfico y otros indicadores técnicos
  4. Mejorar la gestión de fondos: introducir un sistema de gestión de riesgos integrado y considerar la retirada de los controles
  5. Aumentar el análisis de la microestructura del mercado: la integración de los datos de flujo de pedidos mejora la precisión de entrada

Resumir

La estrategia construye un marco de negociación completo mediante la combinación de brechas de dinámica, gestión de riesgos estricta y sistemas de ejecución automatizados. La principal ventaja de la estrategia reside en su sistema de control de riesgos completo y diseño de adaptabilidad, pero aún necesita optimización en la identificación de entornos de mercado y filtración de señales.

Código Fuente de la Estrategia
/*backtest
start: 2025-01-21 00:00:00
end: 2025-02-08 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Binance","currency":"ETH_USDT"}]
*/

//@version=6
strategy("Trading Strategy for XAUUSD (Gold) – Automated Execution Plan", overlay=true, initial_capital=10000, currency=currency.USD)

//────────────────────────────
// 1. RISK MANAGEMENT & POSITION SIZING
//────────────────────────────
// Configurable inputs for Stop Loss and Take Profit
sl = input.float(title="Stop Loss ($)", defval=5, step=0.1)
tp = input.float(title="Take Profit ($)", defval=15, step=0.1)

// Volume: 0.01 lots per $100 of equity → lotSize = equity / 10000
lotSize = strategy.equity / strategy.initial_capital

//────────────────────────────
// 2. TRADING HOURS (London Time)
//────────────────────────────
// Get the current bar's timestamp in London time.
londonTime   = time(timeframe.period, "", "Europe/London")
londonHour   = hour(londonTime)
tradingAllowed = (londonHour != 0) and (londonHour < 19)

//────────────────────────────
// 3. DOJI CANDLE DEFINITION
//────────────────────────────
// A candle is considered a doji if the sum of its upper and lower shadows is greater than its body.
upperShadow = high - math.max(open, close)
lowerShadow = math.min(open, close) - low
bodySize    = math.abs(close - open)
isDoji      = (upperShadow + lowerShadow) > bodySize

//────────────────────────────
// 4. ENTRY CONDITIONS
//────────────────────────────
// Buy Signal:
//   • Current candle’s high > previous candle’s high.
//   • Current candle’s low is not below previous candle’s low.
//   • Bullish candle (close > open) and not a doji.
//   • Skip if previous candle already qualified.
buyRaw    = (high > high[1]) and (low >= low[1]) and (close > open) and (not isDoji)
buySignal = buyRaw and not (buyRaw[1] ? true : false)

// Sell Signal:
//   • Current candle’s low < previous candle’s low.
//   • Current candle’s high is not above previous candle’s high.
//   • Bearish candle (close < open) and not a doji.
//   • Skip if previous candle already qualified.
sellRaw    = (low < low[1]) and (high <= high[1]) and (close < open) and (not isDoji)
sellSignal = sellRaw and not (sellRaw[1] ? true : false)

//────────────────────────────
// 5. DAILY TAKE PROFIT (TP) RULE
//────────────────────────────
// Create a day-string (year-month-day) using London time.
// This flag will block new trades for the rest of the day if a TP is hit.
var string lastDay = ""
currentDay = str.tostring(year(londonTime)) + "-" + str.tostring(month(londonTime)) + "-" + str.tostring(dayofmonth(londonTime))
var bool dailyTPHit = false
if lastDay != currentDay
    dailyTPHit := false
    lastDay := currentDay

//────────────────────────────
// 6. TRACK TRADE ENTRY & EXIT FOR TP DETECTION
//────────────────────────────
// We record the TP target when a new trade is entered.
// Then, when a trade closes, if the bar’s high (for long) or low (for short) reached the TP target,
// we assume the TP was hit and block new trades for the day.
var float currentTP = na
var int currentTradeType = 0   // 1 for long, -1 for short

// Detect a new trade entry (transition from no position to a position).
tradeEntered = (strategy.position_size != 0 and strategy.position_size[1] == 0)
if tradeEntered
    if strategy.position_size > 0
        currentTP := strategy.position_avg_price + tp
        currentTradeType := 1
    else if strategy.position_size < 0
        currentTP := strategy.position_avg_price - tp
        currentTradeType := -1

// Detect trade closure (transition from position to flat).
tradeClosed = (strategy.position_size == 0 and strategy.position_size[1] != 0)
if tradeClosed and not na(currentTP)
    // For a long trade, if the bar's high reached the TP target;
    // for a short trade, if the bar's low reached the TP target,
    // mark the daily TP flag.
    if (currentTradeType == 1 and high >= currentTP) or (currentTradeType == -1 and low <= currentTP)
        dailyTPHit := true
    currentTP := na
    currentTradeType := 0

//────────────────────────────
// 7. ORDER EXECUTION
//────────────────────────────
// Only open a new position if no position is open, trading is allowed, and daily TP rule is not active.
if (strategy.position_size == 0) and tradingAllowed and (not dailyTPHit)
    if buySignal
        strategy.entry("Long", strategy.long, qty=lotSize)
    if sellSignal
        strategy.entry("Short", strategy.short, qty=lotSize)

//────────────────────────────
// 8. EXIT ORDERS (Risk Management)
//────────────────────────────
// For long positions: SL = entry price - Stop Loss, TP = entry price + Take Profit.
// For short positions: SL = entry price + Stop Loss, TP = entry price - Take Profit.
if strategy.position_size > 0
    longSL = strategy.position_avg_price - sl
    longTP = strategy.position_avg_price + tp
    strategy.exit("Exit Long", from_entry="Long", stop=longSL, limit=longTP)
if strategy.position_size < 0
    shortSL = strategy.position_avg_price + sl
    shortTP = strategy.position_avg_price - tp
    strategy.exit("Exit Short", from_entry="Short", stop=shortSL, limit=shortTP)

//────────────────────────────
// 9. VISUALIZATION
//────────────────────────────
plotshape(buySignal and tradingAllowed and (not dailyTPHit) and (strategy.position_size == 0), title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy")
plotshape(sellSignal and tradingAllowed and (not dailyTPHit) and (strategy.position_size == 0), title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell")