Estratégia de sincronização de tendências RMI

Autora:ChaoZhang, Data: 2024-01-16 14:10:25
Tags:

img

Resumo

A estratégia RMI Trend Sync combina efetivamente os pontos fortes do Relative Momentum Index (RMI) e do indicador Super Trend para realizar a integração da análise do momento e do julgamento da tendência.

Princípios de estratégia

Índice de Impulso Relativo (RMI)

O RMI é uma versão aprimorada do Relative Strength Index (RSI). Incorpora mais características das mudanças de preços, como direcionalidade e magnitude, para medir mais precisamente o impulso do mercado.

Método de cálculo do IMR

O método de cálculo do RMI é: primeiro calcular o ganho médio e a perda média durante um determinado período. Ao contrário do RSI, o RMI usa a mudança entre o preço de fechamento atual e o preço de fechamento anterior, em vez de simples crescimento positivo e negativo. Em seguida, divida o ganho médio pela perda média e normalize o valor para caber dentro de uma escala de 0 a 100.

Julgamento de Impulso

Esta estratégia utiliza o valor médio dos IMR e das IFM para comparar com limiares de dinâmica positiva e de dinâmica negativa pré-estabelecidos para determinar o nível atual de dinâmica do mercado para as decisões de entrada e saída.

Indicador de Super Tendência

O indicador Super Trend é calculado com base em um período de tempo mais longo, que pode fornecer julgamentos sobre as principais tendências.
Esta estratégia inclui igualmente a média móvel ponderada por volume (VWMA) para reforçar ainda mais a sua capacidade de detectar importantes mudanças de tendência.

Selecção da direcção de negociação

Esta estratégia permite escolher entre negociação longa, curta ou bidirecional.

Análise das vantagens

Combinação de Momentum e Análise de Tendências

Em comparação com as estratégias que se baseiam unicamente em indicadores de dinâmica ou tendência, esta estratégia permite uma identificação mais precisa das tendências do mercado através da integração dos pontos fortes do RMI e da Super Tendência.

Análise de vários prazos

A aplicação do RMI e da Super Tendência em diferentes prazos conduz a uma compreensão mais adequada das tendências a curto e a longo prazo.

Stop Loss em tempo real

O mecanismo de stop loss em tempo real baseado na Super Trend pode efetivamente limitar as perdas por transação.

Orientação comercial flexível

A escolha entre negociação longa, curta ou bidirecional permite que esta estratégia se adapte a diferentes ambientes de mercado.

Análise de riscos

Optimização de parâmetros difícil

A otimização para parâmetros como RMI e Super Trend é bastante complexa.

Parar Perda Muito Apertada

A sensibilidade excessiva a pequenas flutuações pode resultar em desencadeamentos excessivos de stop loss.

Solução: afrouxar adequadamente o intervalo de stop loss ou adotar outros métodos de stop loss baseados na volatilidade.

Orientações de otimização

Adaptabilidade entre ativos

Expandir os ativos aplicáveis e identificar direcções de otimização de parâmetros para diferentes ativos, para permitir uma replicação mais ampla em mais mercados.

Perda de paragem dinâmica

Incorporar mecanismos dinâmicos de stop loss para melhor rastrear as ondas de balanço da corrente e reduzir a perda de stop excessiva causada por retracements menores.

Condições adicionais do filtro

Adicionar juízos de mais indicadores como condições de filtro para evitar a entrada em posições sem sinais claros.

Conclusão

Através da combinação engenhosa de RMI e Super Trend, esta estratégia realiza julgamentos precisos da condição do mercado.


/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-31 23:59:59
period: 3h
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/
// @ presentTrading

//@version=5
strategy("RMI Trend Sync - Strategy [presentTrading]", shorttitle = "RMI Sync [presentTrading]", overlay=true )

// ---> Inputs --------------
// Add Button for Trading Direction
tradeDirection = input.string("Both", "Select Trading Direction", options=["Long", "Short", "Both"])

// Relative Momentum Index (RMI) Settings
Length = input.int(21, "RMI Length", group = "RMI Settings")
pmom = input.int(70, "Positive Momentum Threshold", group = "RMI Settings")
nmom = input.int(30, "Negative Momentum Threshold", group = "RMI Settings")
bandLength = input.int(30, "Band Length", group = "Momentum Settings")
rwmaLength = input.int(20, "RWMA Length", group = "Momentum Settings")


// Super Trend Settings
len = input.int(10, "Super Trend Length", minval=1, group="Super Trend Settings")
higherTf1 = input.timeframe('480', "Higher Time Frame", group="Super Trend Settings")
factor = input.float(3.5, "Super Trend Factor", step=.1, group="Super Trend Settings")
maSrc = input.string("WMA", "MA Source", options=["SMA", "EMA", "WMA", "RMA", "VWMA"], group="Super Trend Settings")
atr = request.security(syminfo.tickerid, higherTf1, ta.atr(len))
TfClose1 = request.security(syminfo.tickerid, higherTf1, close)

// Visual Settings
filleshow = input.bool(true, "Display Range MA", group = "Visual Settings")
bull = input.color(#00bcd4, "Bullish Color", group = "Visual Settings")
bear = input.color(#ff5252, "Bearish Color", group = "Visual Settings")

// Calculation of Bar Range
barRange = high - low

// RMI and MFI Calculations
upChange = ta.rma(math.max(ta.change(close), 0), Length)
downChange = ta.rma(-math.min(ta.change(close), 0), Length)
rsi = downChange == 0 ? 100 : upChange == 0 ? 0 : 100 - (100 / (1 + upChange / downChange))
mf = ta.mfi(hlc3, Length)
rsiMfi = math.avg(rsi, mf)

// Momentum Conditions
positiveMomentum = rsiMfi[1] < pmom and rsiMfi > pmom and rsiMfi > nmom and ta.change(ta.ema(close,5)) > 0
negativeMomentum = rsiMfi < nmom and ta.change(ta.ema(close,5)) < 0

// Momentum Status
bool positive = positiveMomentum ? true : negativeMomentum ? false : na
bool negative = negativeMomentum ? true : positiveMomentum ? false : na

// Band Calculation
calculateBand(len) =>
    math.min(ta.atr(len) * 0.3, close * (0.3/100)) * 4 

band = calculateBand(bandLength)

// Range Weighted Moving Average (RWMA) Calculation
calculateRwma(range_, period) =>
    weight = range_ / math.sum(range_, period)
    sumWeightedClose = math.sum(close * weight, period)
    totalWeight = math.sum(weight, period)
    sumWeightedClose / totalWeight

rwma = calculateRwma(barRange, rwmaLength)
colour = positive ? bull : negative ? bear : na
rwmaAdjusted = positive ? rwma - band : negative ? rwma + band : na

max = rwma + band
min = rwma - band

longCondition       = positive and not positive[1]
shortCondition      = negative and not negative[1]

longExitCondition   = shortCondition
shortExitCondition  = longCondition

// Dynamic Trailing Stop Loss

vwma1 = switch maSrc
    "SMA"  => ta.sma(TfClose1*volume, len) / ta.sma(volume, len)
    "EMA"  => ta.ema(TfClose1*volume, len) / ta.ema(volume, len)
    "WMA"  => ta.wma(TfClose1*volume, len) / ta.wma(volume, len)

upperBand = vwma1 + factor * atr
lowerBand = vwma1 - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
float superTrend = na
int direction = na
superTrend := direction == -1 ? lowerBand : upperBand

longTrailingStop = superTrend - atr * factor
shortTrailingStop = superTrend + atr * factor

// Strategy Order Execution
if (tradeDirection == "Long" or tradeDirection == "Both")
    strategy.entry("Long", strategy.long, when = longCondition)
    strategy.exit("Exit Long", "Long", when=longExitCondition, stop = longTrailingStop)
if (tradeDirection == "Short" or tradeDirection == "Both")
    strategy.entry("Short", strategy.short, when =shortCondition)
    strategy.exit("Exit Short", "Short", when=shortExitCondition, stop = shortTrailingStop)

Mais.