Estrategia de inversión del impulso


Fecha de creación: 2023-10-07 16:52:05 Última modificación: 2023-10-07 16:52:05
Copiar: 0 Número de Visitas: 673
1
Seguir
1617
Seguidores

Descripción general

Esta estrategia se basa en la idea de negociación de reversión de la dinámica, para juzgar la tendencia actual a través de los tres indicadores RSI, Stoch y MACD, en combinación con la configuración de ATR para detener el stop loss, para lograr una estrategia de negociación automática de captura de reversión de tendencia de manera eficiente.

Principio de estrategia

La estrategia utiliza los tres indicadores RSI, Stoch y MACD para juzgar la dirección de la tendencia actual. La lógica específica es:

  • RSI (del día 7): RSI mayor a 50 es positivo y menor a 50 es negativo
  • Stoch ((%K,14,3,3): el valor de %K mayor a 50 es un alza, menor a 50 es una baja
  • MACD ((12,26,9): el MACD es mayor que el Signal para el alza y menor que el Signal para la baja

Cuando tres indicadores están al alza al mismo tiempo, la barra se pone en verde; cuando tres indicadores están bajando al mismo tiempo, la barra se pone en rojo; si hay discrepancias en las señales del indicador, se pone en negro.

Las reglas comerciales son las siguientes:

  • Cuando la barra actual es verde y la barra anterior es negra o roja, se hace una entrada adicional, el precio de entrada es el punto más alto de la barra más 0.01
  • Cuando la barra actual es de color rojo y la barra anterior es de color negro o verde, el precio de entrada de la barra baja se reduce a 0.01
  • Si aparece una barra roja o negra durante una posición múltiple, la posición está cerrada
  • Si aparece una barra verde o negra durante una posición en blanco, la posición está cerrada.

La estrategia también utiliza ATR (la línea media de 7 días) para establecer la posición de parada de pérdidas. La parada de pérdidas es 1.5 veces la ATR y la parada de parada es 3 veces la ATR.

Análisis de las ventajas

La estrategia tiene las siguientes ventajas:

  1. El uso de varios indicadores para determinar la tendencia puede filtrar eficazmente los brechas falsas. Cuando los tres indicadores RSI, Stoch y MACD son alentadores o bajistas al mismo tiempo, la probabilidad es un punto de reversión de la tendencia.

  2. El ATR tiene una buena configuración de paradas de pérdidas. El ATR puede rastrear eficazmente la volatilidad del mercado, y puede ajustar el parador de pérdidas según la situación dinámica del mercado, para evitar que el parador sea demasiado flexible o demasiado apretado.

  3. La lógica de las transacciones es simple, clara y fácil de entender, y es adecuada para una estrategia de comercio automático.

Análisis de riesgos

También existe el riesgo de que:

  1. La combinación de varios indicadores puede determinar que existe una situación en la que los indicadores individuales emiten señales erróneas, lo que afecta el tiempo de entrada. Se puede considerar ajustar los parámetros del indicador o agregar otros indicadores para verificar y reducir la tasa de señales erróneas.

  2. El tamaño del ATR tiene un gran impacto en el stop loss. Si el ATR no se calcula con precisión, puede causar un stop loss demasiado grande o un stop muy pequeño. Se puede considerar agregar otros indicadores para ayudar a confirmar el tamaño del ATR.

  3. Falta de juicio de tendencia. Esta estrategia se centra en el comercio inverso, el juicio de tendencia es insuficiente y es fácil de encerrar en situaciones de crisis. Se puede agregar un juicio auxiliar de indicadores de tendencia.

  4. Existe un riesgo de sobreajuste. Se debe realizar una revisión adecuada para verificar la fiabilidad de los parámetros y las reglas.

Dirección de optimización

Esta estrategia puede ser optimizada en los siguientes aspectos:

  1. Ajustar o aumentar los indicadores para mejorar la precisión de juicio sobre el momento en que la tendencia se invierte. Por ejemplo, agregar la línea de Brin para determinar el estado de sobrecompra y sobreventa.

  2. Optimizar el método de cálculo del ATR para que pueda seguir mejor las fluctuaciones del mercado. Por ejemplo, el uso del ATR en relación con el precio.

  3. Aumentar los indicadores de tendencia para evitar ser atrapados en situaciones de crisis. Por ejemplo, agregar una media móvil para determinar la dirección de la tendencia.

  4. Optimizar la gestión de fondos, por ejemplo, ajustando las posiciones en función de los retiros.

  5. Optimización del ciclo para verificar la estabilidad de los diferentes parámetros del ciclo de tiempo.

  6. La estrategia se ha probado en más variedades y períodos de tiempo para comprobar su estabilidad y fiabilidad.

Resumir

Esta estrategia se basa en el diseño de la idea de la inversión de la dinámica, el uso de la combinación de RSI, Stoch y MACD para determinar el momento de la inversión de tendencia, junto con la configuración dinámica de ATR para detener el stop loss, para formar un conjunto más completo de estrategias de inversión de tendencia. La estrategia tiene ventajas como la claridad de la lógica de negociación, la configuración razonable de stop loss, pero también tiene deficiencias como señales de error de indicadores, falta de juicio de tendencia. En el futuro, se pueden mejorar los parámetros de optimización de indicadores, la inclusión de juicios de tendencia y el ajuste de la administración de fondos, entre otros, para que la estrategia sea más estable y confiable.

Código Fuente de la Estrategia
/*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*********************************