Okay, here is a Pine Script indicator that identifies Break of Structure (BOS) and Change of Character (CHOCH) events based on pivot highs and pivot lows.
Concepts Used:
Pivots: Uses ta.pivotHigh and ta.pivotLow to identify significant swing highs and lows. The leftBars and rightBars parameters determine how many bars must confirm the pivot.
Structure Tracking: Keeps track of the most recent pivot high and pivot low using ta.valuewhen.
Trend Context: Infers the potential trend direction based on the sequence of the most recent pivots (e.g., if the last significant event was a low followed by a high, the structure is considered bullish).
Break Identification: Checks if the current price action (specifically the high or low of the pivot bar itself, or potentially the close of the current bar) breaks the level of the relevant preceding pivot point.
BOS: Break occurs in the direction of the established structure (Higher High in uptrend, Lower Low in downtrend).
CHOCH: Break occurs against the established structure (Low breaks previous Low in uptrend, High breaks previous High in downtrend).
pinescript
//@version=5
indicator(title="BOS / CHOCH Detector", shorttitle="BOS/CHOCH", overlay=true)
// === INPUTS ===
leftBars = input.int(3, title="Pivot Left Bars", minval=1)
rightBars = input.int(3, title="Pivot Right Bars", minval=1)
showLines = input.bool(true, title="Show Pivot Levels")
showSignals = input.bool(true, title="Show BOS/CHOCH Signals")
bosColor = input.color(color.green, title="BOS Signal Color")
chochColor = input.color(color.red, title="CHOCH Signal Color")
uptrendColor = input.color(color.new(color.green, 85), title="Uptrend Color")
downtrendColor = input.color(color.new(color.red, 85), title="Downtrend Color")
// === PIVOT DETECTION ===
// ta.pivotHigh/Low returns the price of the pivot if detected on the current bar, otherwise na
float pivotHighPrice = ta.pivotHigh(high, leftBars, rightBars)
float pivotLowPrice = ta.pivotLow(low, leftBars, rightBars)
// === TRACKING MOST RECENT PIVOTS ===
// Use ta.valuewhen to find the price and index of the most recent pivots
// The '0' means the most recent occurrence.
float lastPivotHighPrice = ta.valuewhen(pivotHighPrice != na, pivotHighPrice, 0)
int lastPivotHighIndex = int(ta.valuewhen(pivotHighPrice != na, bar_index, 0))
float lastPivotLowPrice = ta.valuewhen(pivotLowPrice != na, pivotLowPrice, 0)
int lastPivotLowIndex = int(ta.valuewhen(pivotLowPrice != na, pivotLowPrice, 0))
// === DETERMINE STRUCTURE ===
// Simple approach: Compare the indices of the last high and low pivots
// If lastPivotLowIndex > lastPivotHighIndex, the last significant event was a low, suggesting an uptrend structure.
// If lastPivotHighIndex > lastPivotLowIndex, the last significant event was a high, suggesting a downtrend structure.
bool structureIsBullish = lastPivotLowIndex > lastPivotHighIndex
bool structureIsBearish = lastPivotHighIndex > lastPivotLowIndex
// === IDENTIFY BOS / CHOCH ===
// Variables to hold the event types for the current bar
bool isBOSBullish = false
bool isBOSBearish = false
bool isCHOCHBullish = false // CHOCH from Bullish to Bearish
bool isCHOCHBearish = false // CHOCH from Bearish to Bullish
// --- Check on bars where pivots are confirmed ---
if pivotHighPrice != na and pivotLowPrice != na // Both pivots confirmed on the same bar (rare, but possible)
// Handle ambiguity or prioritize one based on price action relative to previous structure
// For simplicity, we might skip checks if both occur, or prioritize based on which pivot confirms a structure change/continuation
// Let's prioritize checks based on the structure context derived from previous pivots.
if structureIsBullish and not na(lastPivotHighPrice) and pivotHighPrice > lastPivotHighPrice // Higher High confirmed in bullish structure
isBOSBullish := true
if structureIsBearish and not na(lastPivotLowPrice) and pivotLowPrice < lastPivotLowPrice // Lower Low confirmed in bearish structure
isBOSBearish := true
// CHOCH checks (break against structure)
if structureIsBullish and not na(lastPivotLowPrice) and pivotLowPrice < lastPivotLowPrice // Low breaks previous low in bullish structure
isCHOCHBullish := true
if structureIsBearish and not na(lastPivotHighPrice) and pivotHighPrice > lastPivotHighPrice // High breaks previous high in bearish structure
isCHOCHBearish := true
else if pivotHighPrice != na // Only Pivot High confirmed on this bar
if structureIsBullish and not na(lastPivotHighPrice) and pivotHighPrice > lastPivotHighPrice // Higher High confirmed in bullish structure
isBOSBullish := true
if structureIsBearish and not na(lastPivotHighPrice) and pivotHighPrice > lastPivotHighPrice // High breaks previous high in bearish structure
isCHOCHBearish := true // Potential Bearish -> Bullish CHOCH
else if pivotLowPrice != na // Only Pivot Low confirmed on this bar
if structureIsBearish and not na(lastPivotLowPrice) and pivotLowPrice < lastPivotLowPrice // Lower Low confirmed in bearish structure
isBOSBearish := true
if structureIsBullish and not na(lastPivotLowPrice) and pivotLowPrice < lastPivotLowPrice // Low breaks previous low in bullish structure
isCHOCHBullish := true // Potential Bullish -> Bearish CHOCH
// --- Additional Contextual Checks (Optional but Recommended) ---
// Sometimes, the BOS/CHOCH is confirmed by the *close* price breaking the level, not just the pivot high/low itself.
// Let's refine: A BOS/CHOCH happens when price breaks the *level* of the *previous* opposing pivot.
// Bullish Structure Context (last event was a low, then a high)
if structureIsBullish and not na(lastPivotHighPrice) and not na(lastPivotLowPrice)
// BOS Bullish: Price breaks the last resistance level (higher high)
// Check if the pivot high itself is higher than the previous pivot high
if pivotHighPrice != na and pivotHighPrice > lastPivotHighPrice
isBOSBullish := true // Confirm BOS
// Reset CHOCH flags if this happens
isCHOCHBullish := false
isCHOCHBearish := false
// CHOCH Bullish->Bearish: Price breaks the last support level (lower low)
// Check if the pivot low itself is lower than the previous pivot low
if pivotLowPrice != na and pivotLowPrice < lastPivotLowPrice
isCHOCHBullish := true // Confirm CHOCH
// Reset BOS flags if this happens
isBOSBullish := false
isBOSBearish := false
// Bearish Structure Context (last event was a high, then a low)
if structureIsBearish and not na(lastPivotHighPrice) and not na(lastPivotLowPrice)
// BOS Bearish: Price breaks the last support level (lower low)
// Check if the pivot low itself is lower than the previous pivot low
if pivotLowPrice != na and pivotLowPrice < lastPivotLowPrice
isBOSBearish := true // Confirm BOS
// Reset CHOCH flags
isCHOCHBullish := false
isCHOCHBearish := false
// CHOCH Bearish->Bullish: Price breaks the last resistance level (higher high)
// Check if the pivot high itself is higher than the previous pivot high
if pivotHighPrice != na and pivotHighPrice > lastPivotHighPrice
isCHOCHBearish := true // Confirm CHOCH
// Reset BOS flags
isBOSBullish := false
isBOSBearish := false
// --- Plotting Signals ---
plotshape(showSignals and isBOSBullish, title="BOS Bullish", location=location.belowbar, color=bosColor, style=shape.labelup, size=size.tiny, text="BOS")
plotshape(showSignals and isBOSBearish, title="BOS Bearish", location=location.abovebar, color=bosColor, style=shape.labeldown, size=size.tiny, text="BOS")
plotshape(showSignals and isCHOCHBullish, title="CHOCH Bullish->Bearish", location=location.abovebar, color=chochColor, style=shape.triangledown, size=size.small, text="CHOCH")
plotshape(showSignals and isCHOCHBearish, title="CHOCH Bearish->Bullish", location=location.belowbar, color=chochColor, style=shape.triangleup, size=size.small, text="CHOCH")
// === Plotting Pivot Levels ===
// Plot the level of the last confirmed high and low for context
var line resistanceLine = na
var line supportLine = na
if showLines
// Remove previous lines if they exist and are no longer relevant (or just redraw)
line.delete(resistanceLine)
line.delete(supportLine)
if structureIsBullish and not na(lastPivotHighPrice) and not na(lastPivotLowPrice)
// Bullish structure: last resistance is the last pivot high
resistanceLine := line.new(lastPivotHighIndex, lastPivotHighPrice, bar_index, lastPivotHighPrice, color=uptrendColor, style=line.style_dashed)
// Support level is the last pivot low
supportLine := line.new(lastPivotLowIndex, lastPivotLowPrice, bar_index, lastPivotLowPrice, color=uptrendColor, style=line.style_solid)
else if structureIsBearish and not na(lastPivotHighPrice) and not na(lastPivotLowPrice)
// Bearish structure: last support is the last pivot low
supportLine := line.new(lastPivotLowIndex, lastPivotLowPrice, bar_index, lastPivotLowPrice, color=downtrendColor, style=line.style_dashed)
// Resistance level is the last pivot high
resistanceLine := line.new(lastPivotHighIndex, lastPivotHighPrice, bar_index, lastPivotHighPrice, color=downtrendColor, style=line.style_solid)
// === Background Coloring (Optional) ===
bgcolor(structureIsBullish ? uptrendColor : structureIsBearish ? downtrendColor : na, title="Structure Background")
// === ALERTS ===
alertcondition(isBOSBullish, title="BOS Bullish Alert", message="Bullish BOS detected!")
alertcondition(isBOSBearish, title="BOS Bearish Alert", message="Bearish BOS detected!")
alertcondition(isCHOCHBullish, title="CHOCH Bullish->Bearish Alert", message="Bullish to Bearish CHOCH detected!")
alertcondition(isCHOCHBearish, title="CHOCH Bearish->Bullish Alert", message="Bearish to Bullish CHOCH detected!")
How to Use:
Add to Chart: Open TradingView, go to the Pine Editor, paste the script, and click "Add to Chart".
Configure Inputs:
Pivot Left/Right Bars: Adjust these values (e.g., 2, 3, 5) to define what constitutes a significant pivot. Higher values mean more bars are needed, resulting in fewer, more significant pivots.
Show Lines: Enables/disables drawing lines connecting the relevant structure levels.
Show Signals: Enables/disables the BOS/CHOCH labels/shapes.
Colors: Customize the appearance.
Interpret Signals:
BOS (Green Label/Shape): Indicates a continuation of the presumed trend. A green "BOS" below the bar suggests a bullish BOS (higher high formed). A green "BOS" above the bar suggests a bearish BOS (lower low formed).
CHOCH (Red Label/Shape): Indicates a potential reversal. A red "CHOCH" pointing up (triangle up) below the bar suggests a potential bearish to bullish CHOCH (price broke a prior resistance level). A red "CHOCH" pointing down (triangle down) above the bar suggests a potential bullish to bearish CHOCH (price broke a prior support level).
Context: Always use these signals within the broader context of market structure, support/resistance zones, and other indicators. The ta.pivot functions rely on a fixed lookback window, which might miss structures formed over longer periods or adapt slowly. The inferred trend is also a simplification.
Important Notes:
Pivot Definition: The leftBars and rightBars parameters are crucial. Experiment with different values based on the timeframe and asset you are trading.
Confirmation: This script identifies potential BOS/CHOCH events when pivots are confirmed. Some traders prefer waiting for a close confirmation beyond the pivot level on the next bar. This script primarily uses the pivot point itself. You could modify the logic to check close against lastPivotHighPrice/lastPivotLowPrice on the bar after the pivot confirmation for stricter confirmation.
Lag: Pivot detection inherently involves lag because rightBars need to pass to confirm a pivot.
Structure Simplification: The trend context (bullish/bearish structure) is based purely on the sequence of the last two detected pivots. More complex methods could involve moving averages or other trend indicators.
Multiple Pivots: The script uses ta.valuewhen to get the most recent pivot. If multiple significant pivots occur close together, the logic might need refinement depending on your specific definition.