# ThinkScript Architect - Universal Pivot Location Label
# Author: TheInvestorToolkit.com
# Description: Custom Column to display price location relative to Pivots (S1-S5, R1-R5).
# --- Inputs ---
input thresholdPercent = 1.0;
# --- Data Fetch (Implicit Timeframe) ---
# Note: The timeframe is determined by the Column Settings in the Watchlist.
def PH = high[1];
def PL = low[1];
def PC = close[1];
# --- Pivot Math ---
def P = (PH + PL + PC) / 3;
# --- Level Calculations ---
# Using the specific formulas from your Pivot Scan/Chart
def R1 = P * 2 - PL;
def S1 = P * 2 - PH;
def R2 = P + (PH - PL);
def S2 = P - (PH - PL);
def R3 = P * 2 + (PH - 2 * PL);
def S3 = P * 2 - (2 * PH - PL);
def R4 = P * 3 + (PH - 3 * PL);
def S4 = P * 3 - (3 * PH - PL);
def R5 = P * 4 + (PH - 4 * PL);
def S5 = P * 4 - (4 * PH - PL);
# --- Logic ---
# Check proximity (using the user-defined threshold)
def pct = thresholdPercent / 100;
def nearR5 = AbsValue(close - R5) <= close * pct;
def nearR4 = AbsValue(close - R4) <= close * pct;
def nearR3 = AbsValue(close - R3) <= close * pct;
def nearR2 = AbsValue(close - R2) <= close * pct;
def nearR1 = AbsValue(close - R1) <= close * pct;
def nearPP = AbsValue(close - P) <= close * pct;
def nearS1 = AbsValue(close - S1) <= close * pct;
def nearS2 = AbsValue(close - S2) <= close * pct;
def nearS3 = AbsValue(close - S3) <= close * pct;
def nearS4 = AbsValue(close - S4) <= close * pct;
def nearS5 = AbsValue(close - S5) <= close * pct;
# --- Label Output ---
AddLabel(yes,
if nearR5 then "Near R5"
else if nearR4 then "Near R4"
else if nearR3 then "Near R3"
else if nearR2 then "Near R2"
else if nearR1 then "Near R1"
else if nearPP then "Near Pivot"
else if nearS1 then "Near S1"
else if nearS2 then "Near S2"
else if nearS3 then "Near S3"
else if nearS4 then "Near S4"
else if nearS5 then "Near S5"
else if close > R5 then "> R5"
else if close < S5 then "< S5"
# --- Zone Identification (Context) ---
else if close > R4 then "Zone: R4-R5"
else if close > R3 then "Zone: R3-R4"
else if close > R2 then "Zone: R2-R3"
else if close > R1 then "Zone: R1-R2"
else if close > P then "Zone: P-R1"
else if close > S1 then "Zone: P-S1"
else if close > S2 then "Zone: S1-S2"
else if close > S3 then "Zone: S2-S3"
else if close > S4 then "Zone: S3-S4"
else "Zone: S4-S5",
# --- Color Logic ---
if nearR5 or nearR4 or nearR3 or nearR2 or nearR1 then Color.RED
else if nearS5 or nearS4 or nearS3 or nearS2 or nearS1 then Color.GREEN
else if nearPP then Color.YELLOW
else Color.GRAY
);