Sentiment Estimator [AstrideUnicorn]
// This work is licensed under the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// (c) AstrideUnicorn. All rights reserved.

//@version=5
indicator('Sentiment Estimator', precision=2, timeframe='')

length = input.int(defval=50, title='Look-back Window', minval=1)

// Define extreme sentiment level above which reveral is expected 
extreme_sentiment = input.float( defval=61.5, title="Extreme Sentiment Level")

// initialize red and green candles counters
count_green = 0
count_red = 0

// Count green and red candles
for i = 0 to length - 1 by 1
    if open[i] < close[i]
        count_green := count_green + 1
        count_green
    if open[i] > close[i]
        count_red := count_red + 1
        count_red

// Calcule percentages of green and rend candles within the lookback window
green_perc = count_green / length * 100
red_perc = count_red / length * 100

// Define extreme sentiment conditions
extreme_bullish = ta.crossover(green_perc, 61.8)
extreme_bearish = ta.crossover(red_perc, 61.8)

// Plot the neutral sentiment level and the extreme sentiment one
neutral_line = hline(50, linestyle=hline.style_solid, linewidth=2, color=color.blue)
extreme_line = hline(extreme_sentiment, linestyle=hline.style_solid, linewidth=2, color=color.red)

// Plot bullish and bearish sentiment vaules
plot(green_perc, title='% Bullish', color=color.new(color.green, 0), linewidth=5, style=plot.style_circles)
plot(red_perc, title='% Bearish', color=color.new(color.red, 0), linewidth=5, style=plot.style_circles)

//Plot labels with signal messages
plotshape(extreme_bullish and ta.barssince(extreme_bullish[1]) > 20 ? green_perc : na, style=shape.labeldown, text='reversal expected', location=location.absolute, size=size.large, textcolor=color.new(color.white, 0))
plotshape(extreme_bearish and ta.barssince(extreme_bearish[1]) > 20 ? red_perc : na, style=shape.labeldown, text='reversal expected', location=location.absolute, size=size.large, textcolor=color.new(color.white, 0))

