Estrategia de conteo de velas de media móvil siguiendo tendencias


Fecha de creación: 2023-09-16 19:04:02 Última modificación: 2023-09-16 19:04:02
Copiar: 0 Número de Visitas: 880
1
Seguir
1617
Seguidores

Descripción general

En este artículo se presenta una estrategia de seguimiento de tendencias basada en el conteo de la línea K. La estrategia determina el movimiento de la tendencia al calcular la dirección de la línea K y entrar en el mercado después de la línea K de raíz fija.

Principio de estrategia

La estrategia se basa en los siguientes principios:

  1. La dirección de la línea K es estadística y se determina la tendencia Bias. Cuando las raíces N son consecutivas en la dirección de la línea K, se determina la tendencia.

  2. En una tendencia alcista, haga más cuando aparezcan N raíces de línea negativa continua; en una tendencia bajista, haga vacío cuando aparezcan N raíces de línea positiva continua.

  3. Los valores más pequeños de N permiten que la estrategia capte la tendencia más rápidamente; pero los valores más pequeños de N también son más propensos a ser engañados por los mercados convulsivos.

  4. Se puede establecer un punto de parada fijo para bloquear las ganancias y controlar el riesgo.

  5. Cuando aparece la línea K inversa, la posición se detiene.

Análisis de las ventajas

La estrategia tiene las siguientes ventajas:

  1. El uso de la línea K para juzgar las tendencias estadísticas, simple, directo y fácil de operar.

  2. La entrada en línea es una buena manera de capturar las tendencias.

  3. Puntos de parada fijos para controlar el riesgo de manera efectiva.

  4. Los parámetros de conteo de la línea K son ajustables y se aplican a diferentes entornos de mercado.

  5. La estrategia es simple, clara y fácil de modificar y optimizar.

Análisis de riesgos

La estrategia también tiene ciertos riesgos:

  1. En caso de temblor, el conteo de la línea K puede emitir una señal errónea.

  2. El punto de parada fijo puede ser demasiado rígido para obtener una ganancia suficiente.

  3. El error en el reconocimiento de la señal de giro puede causar un fallo prematuro.

  4. Se deben ajustar los parámetros y controlar el tamaño de la posición.

  5. El comerciante debe evaluar cuidadosamente la racionalidad de los parámetros del recuento.

Resumir

La estrategia integra la idea de la estadística de la línea K y el seguimiento de la tendencia. Si los parámetros se establecen de manera razonable, pueden tener un buen efecto. Sin embargo, el comerciante debe evaluar cuidadosamente el entorno del mercado y ajustar los parámetros adecuadamente para obtener ganancias a largo plazo.

Código Fuente de la Estrategia
/*backtest
start: 2023-08-16 00:00:00
end: 2023-09-15 00:00:00
period: 4h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
//@author=Daveatt

StrategyName = "BEST Candle Meter Strategy"
ShortStrategyName = "BEST Candle Meter Strategy"

// strategy(title=StrategyName, shorttitle=ShortStrategyName, overlay=true, 
//  pyramiding=0, default_qty_value=100, precision=7, currency=currency.USD,
//  commission_value=0.2,commission_type=strategy.commission.percent, initial_capital=10000)

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////// INPUTS ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

// TD Sequential approach would be setting bar_counter == 9
bar_counter = input(5, "Bar Counter",minval=1, step=1)

// if based on same candle
GreenCandle = close > open
RedCandle = close < open

// if based on previous candle open
GreenPrevCandle = close > open[1]
RedPrevCandle = close < open[1]

// conditons
barUP = GreenCandle
barDN = RedCandle

///////////////////////////////////////////////////////////////////////////////
////////////////////////////// COUNTERS ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
var barsFromUp = 0
var barsFromDn = 0
barsFromUp := barUP ? barsFromUp + 1 : 0
barsFromDn := barDN ? barsFromDn + 1 : 0

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////// PLOTS ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

plot_color = barsFromUp > 0 ? color.lime : color.red
//plot(barsFromUp, title="UP Histogram", color=plot_color, style=plot.style_histogram, linewidth=4)
//plot(barsFromDn, title="DN Histogram", color=plot_color, style=plot.style_histogram, linewidth=4)

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////// HLINE ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

//hline(9, '9 TD Sequential Line', linestyle=hline.style_solid, linewidth=2, color=color.black)
//hline(13, '12 TD Sequential Line', linestyle=hline.style_solid, linewidth=3, color=color.purple)

///////////////////////////////////////////////////////////////////////////////
/////////////////////////////// PLOTCHAR //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

// var _lbl_UP = label(na)
// if barsFromUp > 0
//     _lbl_UP := label.new(bar_index, close, tostring(barsFromUp, '#'), textcolor=color.green, style=label.style_none, yloc=yloc.price, xloc=xloc.bar_index, size=size.normal)

// var _lbl_DN = label(na)
// if barsFromDn > 0
//     _lbl_DN := label.new(bar_index, close, tostring(barsFromDn, '#'), textcolor=color.red, style=label.style_none, yloc=yloc.price, xloc=xloc.bar_index, size=size.normal)


//plotshape(barsFromUp > 0, "", shape.arrowup,      location.abovebar, color.green,     text="A")

///////////////////////////////////////////////////////////////////////////////
/////////////////////////////// ALERTS ////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

// alertcondition(barsFromUp == 9, title='🔔Sell 9 Alert🔔', message="Sell 9 Alert")
// alertcondition(barsFromDn == 9, title='🔔Buy 9 Alert🔔', message='Buy 9 Alert')
// alertcondition(barsFromUp > 9, title='🔔Sell > 9 Alert🔔', message="Sell > 9 Alert")
// alertcondition(barsFromDn > 9, title='🔔Buy > 9 Alert🔔', message='Buy > 9 Alert')

///////////////////////////////////////////////
//* Backtesting Period Selector | Component *//
///////////////////////////////////////////////


StartYear = input(2017, "Backtest Start Year",minval=1980)
StartMonth = input(1, "Backtest Start Month",minval=1,maxval=12)
StartDay = input(1, "Backtest Start Day",minval=1,maxval=31)
testPeriodStart = timestamp(StartYear,StartMonth,StartDay,0,0)

StopYear = input(2020, "Backtest Stop Year",minval=1980)
StopMonth = input(12, "Backtest Stop Month",minval=1,maxval=12)
StopDay = input(31, "Backtest Stop Day",minval=1,maxval=31)
testPeriodStop = timestamp(StopYear,StopMonth,StopDay,0,0)

testPeriod() => true

isLong  = barsFromUp == bar_counter
isShort = barsFromDn == bar_counter

long_entry_price    = valuewhen(isLong, close, 0)
short_entry_price   = valuewhen(isShort, close, 0)

sinceNUP = barssince(isLong)
sinceNDN = barssince(isShort)

buy_trend   = sinceNDN > sinceNUP
sell_trend  = sinceNDN < sinceNUP

//////////////////////////
//* Profit Component *//
//////////////////////////

//////////////////////////// MinTick ///////////////////////////
fx_pips_value = syminfo.type == "forex" ? syminfo.mintick*10 : 1

input_tp_pips = input(60, "Backtest Profit Goal (in USD)",minval=0)*fx_pips_value
input_sl_pips = input(30, "Backtest STOP Goal (in USD)",minval=0)*fx_pips_value

tp = buy_trend? long_entry_price + input_tp_pips : short_entry_price - input_tp_pips
sl = buy_trend? long_entry_price - input_sl_pips : short_entry_price + input_sl_pips

plot_tp = buy_trend and high[1] <= tp ? tp : sell_trend and low[1] <= tp ? tp : na
plot_sl = buy_trend and low[1] >= sl ? sl : sell_trend and high[1] >= sl ? sl : na

plot(plot_tp, title="TP", style=plot.style_circles, linewidth=3, color=color.blue)
plot(plot_sl, title="SL", style=plot.style_circles, linewidth=3, color=color.red)

longClose   = isShort
shortClose  = isLong

if testPeriod()
    strategy.entry("Long", 1, when=isLong)
    strategy.close("Long", when=longClose )
    strategy.exit("XL","Long", limit=tp,  when=buy_trend, stop=sl)

if testPeriod()
    strategy.entry("Short", 0,  when=isShort)
    strategy.close("Short", when=shortClose )
    strategy.exit("XS","Short", when=sell_trend, limit=tp, stop=sl)