'Consecutive Red Candles then Consecutive green candles

I want to mark (plotshape) two consecutive red candles. Then two Consecutive green candles, after that again two consecutive red candles then two consecutive green candles. please see the picture, I need a pattern like this in pine script.

This is plotting I need please

 //@version=4
study(title="Highlight red candles", overlay=true)

twoRedCandles = (close[1] < open[1]) and (close < open)

twoGreenCandles = (close[1] > open[1]) and (close > open)


Solution 1:[1]

Use a var counter to count if there are consecutive green/red bars.

Reset this counter when the bar is of opposite color or if it reaches to number you are looking for.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius

//@version=5
indicator("My script", overlay=true)

green_th = input.int(2)
red_th = input.int(3)

is_green = close > open
is_red = not is_green

var cnt_green = 0
var cnt_red = 0

cnt_green := is_green ? cnt_green + 1 : 0
cnt_red := is_red ? cnt_red + 1 : 0

is_green_th_hit = cnt_green == green_th
is_red_th_hit = cnt_red == red_th

cnt_green := is_green_th_hit ? 0 : cnt_green
cnt_red := is_red_th_hit ? 0 : cnt_red

plotshape(is_green_th_hit, "G", shape.triangleup, location.belowbar, color.green)
plotshape(is_red_th_hit, "R", shape.triangledown, location.abovebar, color.red)

enter image description here

Edit

You can use another var to see if the last one was a green formation.

//@version=5
indicator("My script", overlay=true)

green_th = input.int(2)
red_th = input.int(3)

is_green = close > open
is_red = not is_green

var last_one_was_green = false
var cnt_green = 0
var cnt_red = 0

cnt_green := is_green ? cnt_green + 1 : 0
cnt_red := is_red ? cnt_red + 1 : 0

is_green_th_hit = not last_one_was_green and (cnt_green == green_th)
is_red_th_hit = last_one_was_green and (cnt_red == red_th)

last_one_was_green := is_green_th_hit ? true : is_red_th_hit ? false : last_one_was_green
cnt_green := is_green_th_hit ? 0 : cnt_green
cnt_red := is_red_th_hit ? 0 : cnt_red

plotshape(is_green_th_hit, "G", shape.triangleup, location.belowbar, color.green)
plotshape(is_red_th_hit, "R", shape.triangledown, location.abovebar, color.red)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1