Ichimoku Yin Yang Candlestick Breakout Strategy

Author: ChaoZhang, Date: 2023-12-21 10:44:37
Tags:

img

Overview

This strategy is based on a very famous indicator in technical analysis - the Ichimoku Kinko Hyo, using the cloud shapes and the relationship between price and cloud to determine the trend direction and discover trading opportunities. Trading signals are generated when the price breaks through the cloud layers. This strategy is suitable for medium-long term positional trading.

Strategy Principle

The strategy uses several components of the Ichimoku Kinko Hyo indicator, including the Tenkan-Sen (Conversion Line), Kijun-Sen (Base Line), Senkou Span A (Leading Span A), Senkou Span B (Leading Span B) and Chikou Span (Lagging Span). These lines converge to form the so-called Ichimoku cloud. When the price breaks through the cloud layers, buy and sell signals are generated.

Specifically, the strategy judges whether the price breaks through the cloud layer mainly based on the Senkou Span A and Senkou Span B lines. The area between these two lines constitutes the cloud layer. When the closing price breaks through the upper edge of the cloud layer, a buy signal is generated; when the closing price breaks through the lower edge of the cloud layer, a sell signal is generated.

In addition, the strategy also sets stop loss and take profit prices. It uses syminfo.pointvalue and position information of the strategy to calculate points of profit and loss, and then converts them into specific prices.

Advantage Analysis

The strategy has the following advantages:

  1. Using Ichimoku indicator to determine the trend direction can effectively filter market noise and identify medium-long term trends
  2. Breaking through the cloud layer forms signals which can avoid losses caused by false breakouts
  3. Incorporating stop loss and take profit settings can limit single loss and lock in profits
  4. Adjustable parameters allow testing the impact of different parameters on strategy performance
  5. Visualized cloud layer and other Ichimoku components form intuitive graphical trading signals

Risk Analysis

The strategy also has some risks:

  1. Medium to long term positions may lead to larger floating losses
  2. Breakout signals may lag, missing the best entry point
  3. False breakouts may cause wrong signals and losses
  4. Excessively long holding periods incur higher expenses
  5. The set stop loss and take profit prices may be broken through

Countermeasures:

  1. Appropriately shorten the holding period to reduce the risk of single floating loss
  2. Incorporate other indicators to determine the effectiveness of breakout signals
  3. Improve the effectiveness of stop loss and take profit to avoid being caught in wrong positions
  4. Optimize the holding period to reduce expenses

Optimization Directions

The strategy can be optimized in the following aspects:

  1. Test different parameter combinations to find the optimal parameters
  2. Incorporate other indicators for signal filtering to avoid false breakouts
  3. Dynamically adjust stop loss and take profit levels, trails stop loss
  4. Customize exit criteria: reverse signal breaking cloud layer, price retracement triggers
  5. Add position management mechanisms

Conclusion

In general, the Ichimoku Yin Yang Candlestick Breakout Strategy is a typical strategy that uses the Ichimoku Kinko Hyo indicator to determine the medium-long term trend direction for breakouts. It has advantages like adjustable parameters, intuitive shapes, and visualizable signals. It also has some risks such as false breakouts and holding risks. By parameter optimization, signal filtering, stop loss/take profit setting, etc., risks can be reduced and strategy stability improved. The strategy is suitable for medium-long term positional trading, especially efficiently entering the trend direction when signals are formed by breaking cloud layers. Overall, this is a quant strategy with practical value.


/*backtest
start: 2022-12-14 00:00:00
end: 2023-12-20 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © moneyofthegame
// Basado en estrategias con el indicador ICHIMOKU KINKO HIYO
// El tiempo es oro colega :)

//@version=5
strategy('Ichimoku Cloud Estrategia Ruptura Nubes SWING TRADER  (By Insert Cheese)', shorttitle='Ichimoku Cloud Estrategia Ruptura Nubes SWING TRADER  (By Insert Cheese)',

         overlay=true,
         initial_capital=500,
         process_orders_on_close=true,
         default_qty_type=strategy.percent_of_equity,
         default_qty_value=100,
         commission_type=strategy.commission.percent,
         commission_value=0.05,
         currency=currency.NONE)
         




// Inputs: Ichimoku parametros
ts_bars =   input.int(9,  minval=1, title='Tenkan-Sen ',          group='Parámetros Ichimoku')
ks_bars =   input.int(26, minval=1, title='Kijun-Sen ',           group='Parámetros Ichimoku')
ssb_bars =  input.int(52, minval=1, title='Senkou-Span B ',       group='Parámetros Ichimoku')
cs_offset = input.int(26, minval=1, title='Chikou-Span',          group='Parámetros Ichimoku')
ss_offset = input.int(26, minval=1, title='Senkou-Span A',        group='Parámetros Ichimoku')

middle(len) => // LONGITITUD Ichimoku (SenkouB)
    math.avg(ta.lowest(len), ta.highest(len))

// Ichimoku Componentes
tenkan = middle (ts_bars)
kijun   = middle (ks_bars)
senkouA = math.avg(tenkan, kijun)
senkouB = middle (ssb_bars)


// Plot Ichimoku Kinko Hyo
plot(tenkan,                                     color=color.rgb(171, 128, 0),                              title="Tenkan-Sen",    display = display.none)
plot(kijun,                                      color=color.rgb(39, 0, 112),                               title="Kijun-Sen",     display = display.none)
plot(close, offset=-cs_offset+1,                 color=color.rgb(224, 200, 251),                            title="Chikou-Span",   display = display.none)
sa=plot(senkouA, offset=ss_offset-1,             color=color.rgb(68, 128, 0),                               title="Senkou-Span A", display = display.none)
sb=plot(senkouB, offset=ss_offset-1,             color=color.rgb(131, 0, 120),                              title="Senkou-Span B", display = display.none)
fill(sa, sb, color = senkouA > senkouB ?         color.rgb(0, 211, 11, 82) : color.rgb(75, 0, 126, 82),   title="Cloud color")

// Calculating 
ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1])  //parte alta de la nube
ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1])   //parte baja de la nube
ss_medium = ss_low + (ss_high - ss_low) / 2                         //parte intermedia


// Input para seleccionar largos o cortos
long_entry_enable =  input.bool(true, title='Entradas Largo',   group='Backtest Operativa', inline='SP20')
short_entry_enable = input.bool(true, title='Entradas Corto',   group='Backtest Operativa', inline='SP20')

// Input backtest rango de fechas 
fromMonth =  input.int  (defval=1,     title='Desde Mes',  minval=1,     maxval=12,      group='Backtest rango de fechas')
fromYear  =  input.int  (defval=2000,  title='Desde Año',  minval=1970,                  group='Backtest rango de fechas')
fromDay   =  input.int  (defval=1,     title='Desde Día',  minval=1,     maxval=31,      group='Backtest rango de fechas')
thruDay   =  input.int  (defval=1,     title='Hasta Día',  minval=1,     maxval=31,      group='Backtest rango de fechas')
thruMonth =  input.int  (defval=1,     title='Hasta Mes',  minval=1,     maxval=12,      group='Backtest rango de fechas')
thruYear  =  input.int  (defval=2099,  title='Hasta Año',  minval=1970,                  group='Backtest rango de fechas')

inDataRange = time >= timestamp(syminfo.timezone, fromYear, fromMonth, fromDay, 0, 0) and time < timestamp(syminfo.timezone, thruYear, thruMonth, thruDay, 0, 0)


//Estrategia

// Señales de entrada y salida

price_above_kumo = close  > ss_high // precio cierra arriba de la nube
price_below_kumo = close  < ss_low // precio cierra abajo de la nube
price_cross_above_kumo = ta.crossover  (close  , ss_high )   //precio cruza la nube parte alta
price_cross_below_kumo = ta.crossunder (close  , ss_low )     // precio cruza la nube parte baja

bullish = (price_above_kumo and price_cross_above_kumo)
bearish = (price_below_kumo and price_cross_below_kumo)

comprado = strategy.position_size > 0
vendido = strategy.position_size  < 0

sl_long =  price_above_kumo
sl_short = price_below_kumo


if ( not comprado and bullish and inDataRange and long_entry_enable)
//realizar compra
    strategy.entry("Buy", strategy.long)

//realizar salida long
if (comprado and bearish and inDataRange and long_entry_enable)
    strategy.close ("Buy", comment = "cerrado")

if ( not vendido and bearish and inDataRange and short_entry_enable)
//realizar venta
    strategy.entry("Sell", strategy.short)
    
//realizar salida long
if (vendido  and bullish and inDataRange and short_entry_enable)
    strategy.close ("Buy", comment = "cerrado")

// Función Calcular TP y SL

// Inputs para SL y TP


tpenable = input.bool(true, title =  "SL y TP metodo")



moneyToSLPoints(money)  =>
    strategy.position_size !=0 and tpenable ?  (money / syminfo.pointvalue / math.abs (strategy.position_size)) / syminfo.mintick : na

p = moneyToSLPoints(input.float(  100.0, minval=0.1, step=10.0, title = "Take Profit $$"))
l = moneyToSLPoints(input.float(  100.0, minval=0.1, step=10.0, title = "Stop Loss $$"))
strategy.exit("Close", profit = p, loss = l)



// debug plots for visualize SL & TP levels
pointsToPrice(pp) =>
    na(pp) ? na : strategy.position_avg_price + pp * math.sign(strategy.position_size) * syminfo.mintick
    
pp = plot(pointsToPrice(p),color = color.rgb(76, 175, 79, 96), style = plot.style_linebr )
lp = plot(pointsToPrice(-l),color = color.rgb(76, 175, 79, 96), style = plot.style_linebr )
avg = plot( strategy.position_avg_price, color = color.rgb(76, 175, 79, 96), style = plot.style_linebr )
fill(pp, avg, color = color.rgb(76, 175, 79, 96))
fill(avg, lp, color = color.rgb(255, 82, 82, 97))

More