Estratégia de tendência baseada no indicador de fluxo de volume

Autora:ChaoZhang, Data: 2023-10-10 14:51:13
Tags:

Resumo

Esta estratégia implementa a tendência após a negociação com base no indicador de fluxo de volume (VFI).

Princípio da estratégia

  1. Calcular o indicador VFI: calcular o valor VFI com base na variação logarítmica de preços e volume e suavizar as oscilações através de técnicas de suavização.

  2. Determinação da direção da tendência: o cruzamento do VFI acima de 0 é um sinal de alta, enquanto o cruzamento abaixo de 0 é um sinal de baixa.

  3. Os sinais de negociação: vão longos quando a EMA rápida cruza acima da EMA lenta e os VFI cruzam acima da linha de compra; fecham a posição quando os VFI cruzam abaixo da linha de venda.

  4. Stop loss: definir uma percentagem fixa de stop loss.

Esta estratégia depende principalmente do VFI para determinar a direção da tendência, combinado com médias móveis para gerar sinais de negociação. O VFI reflete o sentimento do mercado através da volatilidade de preços e mudanças de volume, tornando-se um indicador de tendência.

Vantagens

  1. O VFI determina melhor as tendências do que os indicadores únicos de preços, filtrando efetivamente as consolidações e as falsas rupturas.

  2. As médias móveis fornecem juízos suplementares, evitando sinais incorretos dos FPI em mercados variáveis.

  3. O stop loss fixo controla o risco e facilita a gestão do risco.

  4. O modo de seguir tendência gera retornos excessivos sem prever reversões.

  5. Ajuste flexível dos parâmetros adapta-se a diferentes períodos e produtos.

Riscos

  1. O VFI pode gerar sinais incorretos durante flutuações significativas.

  2. A taxa de stop loss fixa pode ser demasiado larga ou demasiado estreita.

  3. As configurações de entrada e saída mal configuradas levam a operações excessivas ou em falta.

  4. O seguimento da tendência não consegue captar reversões e precisa de um stop loss oportuno.

  5. Parâmetros inadequados causam entrada prematura ou atrasada.

Melhorias

  1. Otimizar o cálculo do VFI ajustando os parâmetros.

  2. Períodos de média móvel para melhor sincronização do sinal.

  3. Empregar stop loss dinâmico em vez de stop loss fixo.

  4. Adicionar outros indicadores aos sinais de filtragem.

  5. Otimizar os parâmetros separadamente com base no prazo.

  6. Teste a robustez em diferentes produtos.

Conclusão

Esta estratégia determina a direção da tendência com VFI e usa médias móveis para filtrar sinais errados. Realiza compras baixas / vendas altas através da tendência sem prever reversões. A vantagem reside em sua detecção de tendência superior em relação a indicadores de preço único e capacidade de filtrar consolidações. O principal risco é gerar sinais incorretos durante as flutuações. Otimizar parâmetros, adicionar indicadores suplementares e técnicas de stop loss podem melhorar sua estabilidade.


/*backtest
start: 2023-10-02 00:00:00
end: 2023-10-06 21:00:00
period: 3m
basePeriod: 1m
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/
// © mohanee
//This strategy is based on VFI indicator published by  UTS.  
//more details of VFI indicator can be found at  [url=http://mkatsanos.com/VFI.html]http://mkatsanos.com/VFI.html[/url] 
// I have added buy line and sell line to the indicator  and tested  SPY stock/index on one hour chart

//@version=4
strategy(title="VFI  strategy [based on VFI indicator published by  UTS]", overlay=false,pyramiding=2, default_qty_type=strategy.fixed,    initial_capital=10000, currency=currency.USD)


// Const
kMaColor = color.aqua
kNeutralColor = color.gray
kBearColor = color.red
kBullColor = color.green

kAlma = "ALMA"
kEma = "EMA"
kSma = "SMA"
kWma = "WMA"


// Input

vfi_length = input(8, title="Length", minval=1)  //default 130
vfi_coef = input(0.2, title="Coef", minval=0.1)
vfi_volCutoff = input(2.5, title="Volume Cutoff", minval=0.1)
vfi_smoothLen = input(3, title="Smoothing Period", minval=1)
vfi_smoothType = input(kEma, title="Smoothing Type", options=[kAlma, kEma, kSma, kWma])

//These are adde by me for the strategy purpose  BEGIN
vfi_buyLine = input(-4, title="Buy Line", minval=-10)
vfi_sellLine = input(5, title="Sell Line", minval=-10)
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
//These are adde by me for the strategy purpose  END

vfi_longEMA = input(200, title="Long EMA", minval=1)
vfi_shortEMA1 = input(50, title="short EMA1", minval=1)
vfi_shortEMA2 = input(9, title="short EM2A", minval=1)

vfi_showTrend = input(false, title="Visualize Trend")
vfi_showFill = input(true, title="Apply Filling")
vfi_showMa = input(true, title="Show Moving Average")
vfi_maType = input(kSma, title="Moving Average Type", options=[kAlma, kEma, kSma, kWma])
vfi_maLength = input(30, title="Moving Average Length", minval=1)
vfi_almaOffset = input(0.85, title="• ALMA - Offset (global setting)", minval=0.0, maxval=1.0, step=0.05) // more smoothness (closer to 1) vs. more responsiveness (closer to 0)
vfi_almaSigma = input(6.0, title="• ALMA - Sigma (global setting)", minval=0.0, step=0.05) // the larger sigma the smoother ALMA


// Functionality

isRising(sig) =>
    sig > sig[1]
    
isFlat(sig) =>
    sig == sig[1]

vfi_trendColor(sig) =>
    isFlat(sig) ? kNeutralColor : isRising(sig) ? kBullColor : kBearColor
    
vfi_color(sig) =>
    isFlat(sig) ? kNeutralColor : sig > 0 ? kBullColor : kBearColor
    
osc_color(sig) =>
    sig == 0 ? kNeutralColor : sig > 0 ? kBullColor : kBearColor

smooth(t, sig, len) =>
    ma = float(sig)         // None
    if t == kSma            // Simple
        ma := sma(sig, len)
    if t == kEma            // Exponential
        ma := ema(sig, len)
    if t == kWma            // Weighted
        ma := wma(sig, len)
    if t == kAlma           // Arnaud Legoux
        ma := alma(sig, len, vfi_almaOffset, vfi_almaSigma)
    ma

calc_vfi(fviPeriod, smoothType, smoothLen, coef, vCoef) =>
    avg = nz(hlc3)
    inter = log(avg) - log(avg[1])
    vInter = stdev(inter, 30)
    cutOff = coef * vInter * close
    vAve = smooth(kSma, volume[1], fviPeriod)
    vMax = vAve * vCoef
    vC = min(volume, vMax)
    mf = avg - avg[1]
    vCp = iff(mf > cutOff, vC, iff(mf < -cutOff, -vC, 0))
    sVfi = sum(vCp, fviPeriod) / vAve
    vfi = smooth(smoothType, sVfi, smoothLen)
    
value_vfi = calc_vfi(vfi_length, vfi_smoothType, vfi_smoothLen, vfi_coef, vfi_volCutoff)
value_ma = smooth(vfi_maType, value_vfi, vfi_maLength)

longEMAval= ema(close, vfi_longEMA)
shortEMAval1= ema(close, vfi_shortEMA1)
shortEMAval2= ema(close, vfi_shortEMA2)

color_vfi = vfi_showTrend ? vfi_trendColor(value_vfi) : vfi_color(value_vfi)
color_osc = vfi_showFill ? osc_color(value_vfi) : na
color_ma = vfi_showMa ? kMaColor : na


// Drawings

plot_vfi = plot(value_vfi, title="VFI", color=color_vfi, linewidth=1)
plot_fill = plot(0, color=color_vfi, editable=false)
fill(plot_vfi, plot_fill, title="Oscillator Fill", color=color_osc, transp=75) 
hline(vfi_buyLine, color=color.green, title="Buy Line", linewidth=2, linestyle=hline.style_dashed)
hline(vfi_sellLine, color=color.purple, title="Sell Line", linewidth=2, linestyle=hline.style_dashed)
plot(value_ma, title="MA", color=color_ma, linewidth=2)

strategy.entry(id="VFI LE", long=true,  when=crossover(value_vfi,vfi_buyLine)  and ( shortEMAval1 >= longEMAval  ))

//strategy.close(id="VFI LE", comment="Exit",   when=crossunder(value_vfi,vfi_sellLine))
strategy.close(id="VFI LE", comment="TP Exit",   when=crossunder(value_vfi,vfi_sellLine) and close>strategy.position_avg_price)
//strategy.close(id="VFI LE", comment="Exit",   when=  (shortEMAval1 > shortEMAval2 )  and crossunder(close, shortEMAval2))

//stoploss
stopLossVal =   strategy.position_avg_price -  (strategy.position_avg_price*stopLoss*0.01) 
strategy.close(id="VFI LE", comment="SL Exit",   when=crossunder(value_vfi,vfi_sellLine) and close < stopLossVal)




Mais.