// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Monthly Pivot Points", overlay=true)

// --- Function to get monthly OHLC ---
var float last_month_high = na
var float last_month_low = na
var float last_month_close = na
var float this_month_open = na

var float P = na
var float S1 = na
var float R1 = na
var float S2 = na
var float R2 = na
var float S3 = na
var float R3 = na

var int lastMonth = na
newMonth = (month != month[1])

// Track highest/lowest of previous month
if newMonth
    last_month_close := close[1]
    this_month_open := open
    last_month_high := high[1]
    last_month_low := low[1]
    for i = 1 to 500
        if (month[i] != month)
            last_month_high := math.max(last_month_high, high[i])
            last_month_low := math.min(last_month_low, low[i])
        else
            break
    P := (last_month_high + last_month_low + this_month_open + last_month_close) / 4
    R1 := (2 * P) - last_month_low
    S1 := (2 * P) - last_month_high
    R2 := P + (last_month_high - last_month_low)
    S2 := P - (last_month_high - last_month_low)
    R3 := (2 * P) + (last_month_high - 2 * last_month_low)
    S3 := (2 * P) - ((2 * last_month_high) - last_month_low)

// Extend pivots through the month
Pline = P
S1line = S1
R1line = R1
S2line = S2
R2line = R2
S3line = S3
R3line = R3

// Plot lines
plot(Pline, title="Monthly Pivot", color=color.red, linewidth=2)
plot(S1line, title="S1", color=color.blue, linewidth=1)
plot(R1line, title="R1", color=color.green, linewidth=1)
plot(S2line, title="S2", color=color.blue, linewidth=1)
plot(R2line, title="R2", color=color.green, linewidth=1)
plot(S3line, title="S3", color=color.orange, linewidth=1)
plot(R3line, title="R3", color=color.orange, linewidth=1)
