> ## Documentation Index
> Fetch the complete documentation index at: https://takeprofit.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Built-in indicators

## Accumulation/Distribution

```py Accumulation/Distribution theme={null}
# indie:lang_version = 5
from indie import indicator, format, plot, color
from indie.algorithms import CumSum, Mfv


@indicator('Accum/Dist', format=format.VOLUME)  # Accumulation/Distribution
@plot.line(color=color.OLIVE)
def Main(self):
    return CumSum.new(Mfv.new())[0]
```

## Accelerator Oscillator

```py Accelerator Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, plot, color, MutSeriesF
from indie.algorithms import Sma


@indicator('AC')  # Accelerator Oscillator
@plot.columns(title='AC')
def Main(self):
    ao = MutSeriesF.new(Sma.new(self.hl2, 5)[0] - Sma.new(self.hl2, 34)[0])
    ac = MutSeriesF.new(ao[0] - Sma.new(ao, 5)[0])
    c = color.MAROON if ac[0] - ac[1] <= 0 else color.GREEN
    return plot.Columns(ac[0], color=c)
```

## Advance/Decline Ratio (Bars)

```py Advance/Decline Ratio (Bars) theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot, MutSeriesF
from indie.algorithms import Sum
from indie.math import divide


@indicator('ADR_B', format=format.PRICE)  # Advance/Decline Ratio (Bars)
@param.int('length', default=9, min=1)
@level(1, line_color=color.GRAY, title='Equality Line')
@plot.line(color=color.BLUE, title='ADR_B')
def Main(self, length):
    is_up = (self.close[0] - self.open[0]) >= 0.0

    is_down_ints = MutSeriesF.new(0 if is_up else 1)
    is_up_ints = MutSeriesF.new(1 if is_up else 0)

    down_bars = Sum.new(is_down_ints, length)
    up_bars = Sum.new(is_up_ints, length)

    return divide(up_bars[0], down_bars[0], up_bars[0])
```

## Arnaud Legoux Moving Average

```py Arnaud Legoux Moving Average theme={null}
# indie:lang_version = 5
from math import exp, pow
from indie import indicator, param, plot, color
from indie.math import divide


@indicator('ALMA', overlay_main_pane=True)  # Arnaud Legoux Moving Average
@param.int('window_size', default=9, min=1, title='Window Size')
@param.float('offset', default=0.85)
@param.float('sigma', default=6.0, min=0.001)
@plot.line(color=color.BLUE)
def Main(self, window_size, offset, sigma):
    m = offset * (window_size - 1)
    s = window_size / sigma
    sum, norm = 0.0, 0.0
    for i in range(window_size):
        weight = exp(-1 * pow(i - m, 2) / (2 * pow(s, 2)))
        norm += weight
        sum += self.close[window_size - i - 1] * weight
    return divide(sum, norm)
```

## Aroon

```py Aroon theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color
from indie.algorithms import SinceLowest, SinceHighest


@indicator('Aroon', format=format.PRICE)  # TODO: format=format.PERCENT
@param.int('length', default=14, min=1)
@plot.line(color=color.BLUE, title='Aroon Down')
@plot.line(color=color.YELLOW, title='Aroon Up')
def Main(self, length):
    lo_offset = SinceLowest.new(self.low, length)
    hi_offset = SinceHighest.new(self.high, length)

    down = 100 * (length - lo_offset[0]) / length
    up = 100 * (length - hi_offset[0]) / length

    return down, up
```

## Average Day Range

```py Average Day Range theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color
from indie.algorithms import Sma


@indicator('ADR')  # Average Day Range
@param.int('length', default=14, min=1)
@plot.line(color=color.BLUE)
def Main(self, length):
    sma_high = Sma.new(self.high, length)
    sma_low = Sma.new(self.low, length)
    return sma_high[0] - sma_low[0]
```

## Average Directional Index

```py Average Directional Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color
from indie.algorithms import Adx


@indicator('ADX', format=format.PRICE)  # Average Directional Index
@param.int('adx_len', default=14, min=1, title='ADX Smoothing')
@param.int('di_len', default=14, min=1, title='DI Length')
@plot.line(color=color.RED)
def Main(self, adx_len, di_len):
    _, adx, _ = Adx.new(adx_len, di_len)
    return adx[0]
```

## Average True Range

```py Average True Range theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color
from indie.algorithms import Atr


@indicator('ATR')  # Average True Range
@param.int('length', default=14, min=1)
@param.str('smoothing', default='RMA', options=['RMA', 'SMA', 'EMA', 'WMA'], title='Smoothing')
@plot.line(color=color.RED)
def Main(self, length, smoothing):
    return Atr.new(length, smoothing)[0]
```

## Awesome Oscillator

```py Awesome Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, plot, color, MutSeriesF
from indie.algorithms import Sma


# TODO: Support palettes of colors in indicators
@indicator('AO')  # Awesome Oscillator
@plot.columns()
def Main(self):
    ao = MutSeriesF.new(Sma.new(self.hl2, 5)[0] - Sma.new(self.hl2, 34)[0])
    d = ao[0] - ao[1]
    c = color.MAROON if d <= 0 else color.GREEN
    return plot.Columns(ao[0], color=c)
```

## Balance of Power

```py Balance of Power theme={null}
# indie:lang_version = 5
from indie import indicator, format, plot, color
from indie.math import divide


@indicator('BoP', format=format.PRICE)  # Balance of Power
@plot.line(color=color.RED)
def Main(self):
    return divide(self.close[0] - self.open[0], self.high[0] - self.low[0])
```

## Bar Stats

```py Bar Stats theme={null}
# indie:lang_version = 5
from math import floor, isnan, nan
from indie import (
    IndieError, MainContext, MutSeries, Optional, TimeFrame, color, indicator, param, plot, request_series,
    time_frame_unit,
)
from indie.data import VolumeFootprintProfile, sources
from indie.data.sources import session_types


def detail_time_frame(chart: TimeFrame) -> Optional[str]:
    if chart.unit == TimeFrame.from_str('1T').unit or chart.to_seconds() < 60:
        return None
    if chart.unit == time_frame_unit.SECOND and chart.count % 60 != 0:
        return None
    candidates = ['1m', '5m', '15m']
    if chart.unit == time_frame_unit.WEEK or chart.unit == time_frame_unit.MONTH:
        candidates = ['1D', '1M']
    elif chart.to_seconds() >= 1800:
        candidates = ['30m', '1h', '4h', '1m', '5m', '15m']
    for name in candidates:
        candidate = TimeFrame.from_str(name)
        if candidate > chart:
            continue
        aligned = False
        count = 0
        if candidate.unit == time_frame_unit.MONTH:
            aligned = chart.unit == time_frame_unit.MONTH and chart.count % candidate.count == 0
            count = chart.count // candidate.count
        elif chart.unit == time_frame_unit.MONTH:
            aligned = 86400 % candidate.to_seconds() == 0
            count = chart.count * 31 * 86400 // candidate.to_seconds()
        else:
            aligned = chart.to_seconds() % candidate.to_seconds() == 0
            count = chart.to_seconds() // candidate.to_seconds()
        if aligned and count <= 96:
            return name
    return None


def resolve_reset(chart: TimeFrame, reset: str) -> str:
    if reset != 'Auto':
        return reset
    if chart.to_seconds() < 86400:
        return 'Session'
    return 'Continuous'


def total_delta(profiles: list[VolumeFootprintProfile]) -> float:
    buy = 0.0
    sell = 0.0
    for profile in profiles:
        buy += profile.total_volume_buy
        sell += profile.total_volume_sell
    return buy - sell


@indicator('Bar Stats')
@param.str('reset', default='Auto', options=['Auto', 'Session', 'Day'], title='Cuml. Delta reset')
@param.str('row_size', default='Auto', options=['Auto', 'Manual'], title='Row Size')
@param.int('levels_per_row', default=1, min=1, title='Levels per Row')
@plot.data_grid('bar_stats', title='Bar Stats', rows=[
    plot.GridRow('volume', 'Vol', 'Volume', colors=[color.hex('#2F89FF')],
                 format=plot.GridFormat(plot.grid_format.VOLUME),
                 description='Total traded volume in the bar.'),
    plot.GridRow('poc', 'POC', 'POC Volume', colors=[color.hex('#FBDA00')],
                 format=plot.GridFormat(plot.grid_format.VOLUME),
                 detail=plot.GridRowDetail(plot.GridFormat(plot.grid_format.PRICE), ' @ '),
                 description='Volume traded at the POC, the price level with the highest volume in the bar.'),
    plot.GridRow('delta', 'Δ', 'Delta', colors=[color.hex('#00B41F'), color.hex('#EB4814')],
                 signed=True, format=plot.GridFormat(plot.grid_format.VOLUME),
                 description='Aggressive buying minus aggressive selling.'),
    plot.GridRow('delta_pct', 'Δ %', 'Delta %', colors=[color.hex('#00B41F'), color.hex('#EB4814')],
                 signed=True, format=plot.GridFormat(plot.grid_format.PERCENT, precision=1),
                 domain=plot.GridDomain(-100.0, 100.0),
                 description="Delta as a share of the bar's volume."),
    plot.GridRow('cuml_delta', 'Cuml Δ', 'Cuml. Delta', colors=[color.hex('#00B41F'), color.hex('#EB4814')],
                 signed=True, format=plot.GridFormat(plot.grid_format.VOLUME),
                 description='Running total of Delta since the reset point.'),
    plot.GridRow('buy', 'Buy', 'Buy Volume', colors=[color.hex('#E2FF8E')],
                 format=plot.GridFormat(plot.grid_format.VOLUME),
                 visible=False, description='Volume of trades where the buyer was the aggressor.'),
    plot.GridRow('sell', 'Sell', 'Sell Volume', colors=[color.hex('#FFA09E')],
                 format=plot.GridFormat(plot.grid_format.VOLUME),
                 visible=False, description='Volume of trades where the seller was the aggressor.'),
    plot.GridRow('max_delta', 'Max Δ', 'Max Delta', colors=[color.hex('#00B41F'), color.hex('#EB4814')],
                 signed=True, format=plot.GridFormat(plot.grid_format.VOLUME),
                 description='Highest running Delta reached inside the bar.'),
    plot.GridRow('min_delta', 'Min Δ', 'Min Delta', colors=[color.hex('#00B41F'), color.hex('#EB4814')],
                 signed=True, format=plot.GridFormat(plot.grid_format.VOLUME), visible=False,
                 description='Lowest running Delta reached inside the bar.'),
    plot.GridRow('delta_chg', 'Δ Chg', 'Delta Change', colors=[color.hex('#00B41F'), color.hex('#EB4814')],
                 signed=True, format=plot.GridFormat(plot.grid_format.VOLUME), visible=False,
                 description='Change of Delta versus the previous bar.'),
    plot.GridRow('trades', 'Trades', 'Trades', colors=[color.hex('#2F89FF')],
                 format=plot.GridFormat(plot.grid_format.NUMBER, precision=0), visible=False,
                 description='Number of trades in the bar.'),
    plot.GridRow('buy_trades', 'Buy T', 'Buy Trades', colors=[color.hex('#E2FF8E')],
                 format=plot.GridFormat(plot.grid_format.VOLUME, precision=0),
                 description='Number of trades where the buyer was the aggressor.'),
    plot.GridRow('sell_trades', 'Sell T', 'Sell Trades', colors=[color.hex('#FFA09E')],
                 format=plot.GridFormat(plot.grid_format.VOLUME, precision=0),
                 description='Number of trades where the seller was the aggressor.'),
])
class Main(MainContext):
    def __init__(self, row_size):
        if self.time_frame.unit == TimeFrame.from_str('1T').unit:
            raise IndieError('Volume Footprint data is unavailable for tick charts; choose a time-based chart')
        chosen = detail_time_frame(self.time_frame)
        if chosen is None:
            raise IndieError('No compatible footprint detail; choose a minute or longer time-based chart')
        types = [session_types.MAIN_SESSION]
        if self.extended_hours:
            types = [session_types.MAIN_SESSION, session_types.PRE_MARKET, session_types.POST_MARKET]
        ticks = 0 if row_size == 'Auto' else 1
        self._footprints = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=types, row_size_ticks=ticks),
            time_frame=TimeFrame.from_str(chosen.value()))

    # Bars outside the schedule never start a period, else is_same_period would reset on each of them.
    def _starts_period(self, reset: str) -> bool:
        if reset == 'Continuous':
            return False
        if self.bar_index == 0:
            return True
        current = self.time[0]
        previous = self.time[1]
        if reset == 'Session':
            return self.trading_session.is_regular(current) and not (
                self.trading_session.is_regular(previous)
                and self.trading_session.regular.is_same_period(current, previous))
        return current in self.trading_session and not self.trading_session.is_same_period(current, previous)

    def calc(self, reset, row_size, levels_per_row):
        cuml_open = MutSeries[float].new(0.0)
        footprints = self._footprints
        footprints.request_subperiods(2)
        profiles = footprints.subperiods()
        # Re-read every calc: the closed bar's last profile may arrive after the next bar opened.
        previous = footprints.subperiods(1)
        previous_delta = nan
        if previous is not None and len(previous.value()) > 0:
            previous_delta = total_delta(previous.value())
        marks: list[str] = []
        if self._starts_period(resolve_reset(self.time_frame, reset)):
            marks.append('cuml_delta')
        elif isnan(previous_delta):
            cuml_open[0] = cuml_open.get(1, 0.0)
        else:
            cuml_open[0] = cuml_open.get(1, 0.0) + previous_delta
        volume = nan
        poc = nan
        poc_price = nan
        delta = nan
        delta_pct = nan
        cuml_delta = nan
        buy = nan
        sell = nan
        max_delta = nan
        min_delta = nan
        delta_chg = nan
        trades = nan
        buy_trades = nan
        sell_trades = nan
        cells: list[plot.GridCell] = []
        na_reason = ''
        if profiles is None or len(profiles.value()) == 0:
            na_reason = 'No order flow data for this bar.'
        else:
            buy = 0.0
            sell = 0.0
            max_delta = 0.0
            min_delta = 0.0
            buy_trades_count = 0
            sell_trades_count = 0
            low = nan
            high = nan
            level_size = nan
            for grid_profile in profiles.value():
                for grid_row in grid_profile.rows:
                    if isnan(low) or grid_row.price < low:
                        low = grid_row.price
                    if isnan(high) or grid_row.price > high:
                        high = grid_row.price
                if isnan(level_size) and len(grid_profile.rows) > 0:
                    level_size = grid_profile.row_size
            merged = levels_per_row if row_size == 'Manual' else 1
            first_level = 0
            first_row = 0
            # Indexed on the shared row grid: a float-keyed dict is slow per row in WASM.
            levels: list[float] = []
            if level_size > 0.0:
                # Merged rows start at multiples of their height from zero, like the PVP and SVP histograms.
                raw_first = low / level_size
                first_level = floor(raw_first + max(1e-9, abs(raw_first) * 1e-12))
                first_row = first_level // merged
                for i in range((first_level + round((high - low) / level_size)) // merged - first_row + 1):
                    levels.append(0.0)
            for profile in profiles.value():
                buy += profile.total_volume_buy
                sell += profile.total_volume_sell
                buy_trades_count += profile.total_trades_count_buy
                sell_trades_count += profile.total_trades_count_sell
                max_delta = max(max_delta, buy - sell)
                min_delta = min(min_delta, buy - sell)
                if level_size > 0.0:
                    for row in profile.rows:
                        index = (first_level + round((row.price - low) / level_size)) // merged - first_row
                        level = levels[index] + row.volume_buy + row.volume_sell
                        levels[index] = level
                        if isnan(poc) or level > poc:
                            poc = level
                            poc_price = row.price
                            if merged > 1:
                                poc_price = (first_row + index) * merged * level_size
            volume = buy + sell
            delta = buy - sell
            if volume != 0.0:
                delta_pct = delta / volume * 100.0
            cuml_delta = cuml_open[0] + delta
            buy_trades = float(buy_trades_count)
            sell_trades = float(sell_trades_count)
            trades = buy_trades + sell_trades
            if not isnan(poc):
                cells.append(plot.GridCell('poc', detail=poc_price))
            if isnan(previous_delta):
                cells.append(plot.GridCell('delta_chg', na_reason='No previous bar to compare.'))
            else:
                delta_chg = delta - previous_delta
        return plot.GridValue(
            [volume, poc, delta, delta_pct, cuml_delta, buy, sell, max_delta, min_delta, delta_chg, trades,
             buy_trades, sell_trades],
            cells=cells, marks=marks, na_reason=na_reason)
```

## Bollinger Bands

```py Bollinger Bands theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Bb


@indicator('BB', overlay_main_pane=True)  # Bollinger Bands
@param.int('length', default=20, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.float('mult', default=2.0, min=0.001, max=50.0, title='StdDev')
@param.int('offset', default=0, min=-500, max=500)
@plot.line('lower', color=color.BLUE, title='Lower')
@plot.line(color=color.RED, title='Basis')
@plot.line('upper', color=color.BLUE, title='Upper')
@plot.fill('lower', 'upper', color=color.AQUA(0.05), title='Background')
def Main(self, length, src, mult, offset):
    (lower, middle, upper) = Bb.new(src, length, mult)
    return (
        plot.Line(lower[0], offset=offset),
        plot.Line(middle[0], offset=offset),
        plot.Line(upper[0], offset=offset),
        plot.Fill(offset=offset),
    )
```

## Bollinger Bands %B

```py Bollinger Bands %B theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, band, color, level, plot
from indie.algorithms import Bb
from indie.math import divide


@indicator('BB %B', format=format.PRICE)  # Bollinger Bands %B
@param.int('length', default=20, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.float('mult', default=2.0, min=0.001, max=50.0, title='StdDev')
@band(0, 1, line_color=color.GRAY, fill_color=color.AQUA(0.1), title='Background')
@level(0.5, line_color=color.GRAY, title='Middle Band')
@plot.line(color=color.AQUA, title='Bollinger Bands %B')
def Main(self, length, src, mult):
    (lower, _, upper) = Bb.new(src, length, mult)
    return divide(src[0] - lower[0], upper[0] - lower[0])
```

## Bollinger Bands Width

```py Bollinger Bands Width theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, plot, color
from indie.algorithms import Bb
from indie.math import divide


@indicator('BBW', format=format.PRICE)  # Bollinger Bands Width
@param.int('length', default=20, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.float('mult', default=2.0, min=0.001, max=50.0, title='StdDev')
@plot.line(color=color.TEAL)
def Main(self, length, src, mult):
    (lower, middle, upper) = Bb.new(src, length, mult)
    return divide(upper[0] - lower[0], middle[0])
```

## Bull Bear Power

```py Bull Bear Power theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color
from indie.algorithms import Ema


@indicator('BBP')  # Bull Bear Power
@param.int('length', default=13, min=1)
@plot.line(color=color.BLUE)
def Main(self, length):
    bear_power = self.low[0] - Ema.new(self.close, length)[0]
    bull_power = self.high[0] - Ema.new(self.close, length)[0]
    return bull_power + bear_power
```

## Chaikin Money Flow

```py Chaikin Money Flow theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot
from indie.algorithms import Sum, Mfv
from indie.math import divide


@indicator('CMF', format=format.PRICE)  # Chaikin Money Flow
@param.int('length', default=20, min=1, title='Length')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.GREEN, title='MF')
def Main(self, length):
    mfv_sum = Sum.new(Mfv.new(), length)[0]
    vol_sum = Sum.new(self.volume, length)[0]
    return divide(mfv_sum, vol_sum)
```

## Chaikin Oscillator

```py Chaikin Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot
from indie.algorithms import CumSum, Mfv, Ema


@indicator('Chaikin Osc', format=format.VOLUME)  # Chaikin Oscillator
@param.int('fast_length', default=3, min=1, title='Fast Length')
@param.int('slow_length', default=10, min=1, title='Slow Length')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.RED, title='Chaikin Oscillator')
def Main(self, fast_length, slow_length):
    ad = CumSum.new(Mfv.new())
    ch_osc = Ema.new(ad, fast_length)[0] - Ema.new(ad, slow_length)[0]
    return ch_osc
```

## Chande Kroll Stop

```py Chande Kroll Stop theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color, MutSeriesF
from indie.algorithms import Atr, Lowest, Highest


@indicator('Chande KS', overlay_main_pane=True)  # Chande Kroll Stop
@param.int('p', default=10, min=1)
@param.int('x', default=1, min=1)
@param.int('q', default=9, min=1)
@plot.line(color=color.BLUE, title='Stop Long')
@plot.line(color=color.MAROON, title='Stop Short')
def Main(self, p, x, q):
    atr = Atr.new(p)[0]
    first_low_stop = MutSeriesF.new(Lowest.new(self.low, p)[0] + x * atr)
    first_high_stop = MutSeriesF.new(Highest.new(self.high, p)[0] - x * atr)
    stop_long = Lowest.new(first_low_stop, q)
    stop_short = Highest.new(first_high_stop, q)
    return stop_long[0], stop_short[0]
```

## Chande Momentum Oscillator

```py Chande Momentum Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, level, color, plot, MutSeriesF
from indie.algorithms import Change, Sum
from indie.math import divide


@indicator('Chande MO', format=format.PRICE)  # Chande Momentum Oscillator
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.BLUE, title='Chande MO')
def Main(self, length, src):
    momm = Change.new(src)[0]

    m1 = momm if momm >= 0 else 0
    m2 = 0.0 if momm >= 0 else -momm

    sm1 = Sum.new(MutSeriesF.new(m1), length)[0]
    sm2 = Sum.new(MutSeriesF.new(m2), length)[0]

    return 100 * divide(sm1 - sm2, sm1 + sm2)
```

## Chop Zone

```py Chop Zone theme={null}
# indie:lang_version = 5
from math import nan, isnan, atan, pi
from indie import indicator, format, plot, color, Color
from indie.algorithms import Highest, Lowest, Ema
from indie.math import divide


@indicator('Chop Zone', format=format.PRICE, precision=0)
@plot.columns()
def Main(self):
    color_turquoise = color.rgba(38, 198, 218)
    color_dark_green = color.rgba(67, 160, 71)
    color_pale_green = color.rgba(165, 214, 167)
    color_lime = color.rgba(0, 150, 136)
    color_dark_red = color.rgba(213, 0, 0)
    color_red = color.rgba(233, 30, 99)
    color_orange = color.rgba(255, 109, 0)
    color_light_orange = color.rgba(255, 183, 77)
    color_yellow = color.rgba(253, 216, 53)

    periods = 30
    highest_high = Highest.new(self.high, periods)[0]
    lowest_low = Lowest.new(self.low, periods)[0]
    span = divide(25, highest_high - lowest_low) * lowest_low

    ema34 = Ema.new(self.close, 34)
    y2_ema34 = divide(ema34[1] - ema34[0], self.hlc3[0]) * span

    ema_angle_1 = nan
    if not isnan(y2_ema34):
        ema_angle_1 = round(180 * atan(abs(y2_ema34)) / pi)
    ema_angle = -ema_angle_1 if y2_ema34 > 0 else ema_angle_1

    chop_zone_color = color.BLACK  # default value
    if ema_angle >= 5:
        chop_zone_color = color_turquoise
    elif ema_angle >= 3.57:
        chop_zone_color = color_dark_green
    elif ema_angle >= 2.14:
        chop_zone_color = color_pale_green
    elif ema_angle >= 0.71:
        chop_zone_color = color_lime
    elif ema_angle <= -5:
        chop_zone_color = color_dark_red
    elif ema_angle <= -3.57:
        chop_zone_color = color_red
    elif ema_angle <= -2.14:
        chop_zone_color = color_orange
    elif ema_angle <= -0.71:
        chop_zone_color = color_light_orange
    else:  # ema_angle > -0.71 and ema_angle < 0.71
        chop_zone_color = color_yellow
    return plot.Columns(1, color=chop_zone_color)
```

## Choppiness Index

```py Choppiness Index theme={null}
# indie:lang_version = 5
from math import log10
from indie import indicator, format, param, band, color, level, plot
from indie.algorithms import Highest, Lowest, Sum, Atr
from indie.math import divide


@indicator('CHOP', format=format.PRICE)  # Choppiness Index
@param.int('length', default=14, min=1)
@param.int('offset', default=0, min=-500, max=500)
@band(38.2, 61.8, line_color=color.GRAY, fill_color=color.AQUA(0.1), title='Background')
@level(50, line_color=color.GRAY(0.5), title='Middle Band')
@plot.line(color=color.BLUE, title='CHOP')
def Main(self, length, offset):
    hl = Highest.new(self.high, length)[0] - Lowest.new(self.low, length)[0]
    res = 100 * divide(log10(divide(Sum.new(Atr.new(1), length)[0], hl)), log10(length))
    return plot.Line(res, offset=offset)
```

## Commodity Channel Index

```py Commodity Channel Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, band, color, level, plot
from indie.algorithms import Cci


@indicator('CCI', format=format.PRICE)  # Commodity Channel Index
@param.int('length', default=20, min=1)
@param.source('src', default=source.HLC3, title='Source')
@band(-100, 100, line_color=color.GRAY, fill_color=color.AQUA(0.1), title='Background')
@level(0, line_color=color.GRAY(0.5), title='Middle Band')
@plot.line(color=color.BLUE, title='CCI')
def Main(self, length, src):
    return Cci.new(src, length)[0]
    # TODO: implement smoothing when display.none is supported
```

## Connors RSI

```py Connors RSI theme={null}
# indie:lang_version = 5
from math import isnan
from indie import indicator, format, param, band, color, level, plot, MutSeriesF
from indie.algorithms import Rsi, PercentRank, Roc


def nan_to_zero(val: float) -> float:
    return 0 if isnan(val) else val


@indicator('CRSI', format=format.PRICE)  # Connors RSI
@param.int('len_rsi', default=3, min=1, title='RSI Length')
@param.int('len_up_down', default=2, min=1, title='UpDown Length')
@param.int('len_roc', default=100, min=1, title='ROC Length')
@band(30, 70, line_color=color.GRAY, fill_color=color.AQUA(0.1), title='Background')
@level(50, line_color=color.GRAY(0.5), title='Middle Band')
@plot.line(color=color.BLUE, title='CRSI')
def Main(self, len_rsi, len_up_down, len_roc):
    is_equal = self.close[0] == self.close[1]
    is_growing = self.close[0] > self.close[1]
    ud = MutSeriesF.new(0)  # why not mut_series(init=0)
    if is_growing:
        if nan_to_zero(ud[1]) <= 0:  # why not equal nan_to_zero(ud)[1]
            ud[0] = 1
        else:
            ud[0] = nan_to_zero(ud[1]) + 1
    elif not is_equal:
        if nan_to_zero(ud[1]) >= 0:
            ud[0] = -1
        else:
            ud[0] = nan_to_zero(ud[1]) - 1

    rsi = Rsi.new(self.close, len_rsi)[0]
    ud_rsi = Rsi.new(ud, len_up_down)[0]
    pr = PercentRank.new(Roc.new(self.close, 1), len_roc)[0]
    return (rsi + ud_rsi + pr) / 3
```

## Coppock Curve

```py Coppock Curve theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color, MutSeriesF
from indie.algorithms import Roc, Wma


@indicator('Coppock')  # Coppock Curve
@param.int('wma_length', default=10, min=1, title='WMA Length')
@param.int('long_roc_length', default=14, min=1, title='Long RoC Length')
@param.int('short_roc_length', default=11, min=1, title='Short RoC Length')
@plot.line(color=color.BLUE)
def Main(self, wma_length, long_roc_length, short_roc_length):
    l_roc = Roc.new(self.close, long_roc_length)[0]
    s_roc = Roc.new(self.close, short_roc_length)[0]
    curve = Wma.new(MutSeriesF.new(l_roc + s_roc), wma_length)[0]
    return curve
```

## Correlation Coefficient

```py Correlation Coefficient theme={null}
# indie:lang_version = 5
from indie import indicator, MainContext, sec_context, format, param, source, param_ref, level, color, plot
from indie.algorithms import Corr


@sec_context
@param_ref('source')
def SecContext(self, source):
    return source[0]


@indicator('CC', format=format.PRICE)  # Correlation Coefficient
@param.str('exchange', default='NASDAQ')
@param.str('ticker', default='GOOG')
@param.source('source', default=source.CLOSE)
@param.int('length', default=20, min=1)
@level(1, line_color=color.GRAY)
@level(0)
@level(-1, line_color=color.GRAY)
@plot.line(color=color.BLUE, title='Correlation')
class Main(MainContext):
    def __init__(self, exchange, ticker):
        self.ctx_other = self.calc_on(SecContext, exchange=exchange, ticker=ticker)

    def calc(self, source, length):
        corr = Corr.new(source, self.ctx_other, length)
        return corr[0]
```

## Cumulative Volume Delta (CVD)

```py Cumulative Volume Delta (CVD) theme={null}
# indie:lang_version = 5
from math import floor, isnan, nan
from datetime import datetime
from indie import (
    IndieError, MainContext, MutSeries, Optional, Var, TimeFrame, color, format, indicator, level, param, plot,
    request_series, time_frame_unit,
)
from indie.data import VolumeFootprintProfile, sources
from indie.data.sources import session_types


def detail_time_frame(chart: TimeFrame, detail: str) -> Optional[str]:
    if chart.unit == TimeFrame.from_str('1T').unit or chart.to_seconds() < 60:
        return None
    if chart.unit == time_frame_unit.SECOND and chart.count % 60 != 0:
        return None
    candidates = ['1m', '5m', '15m']
    if chart.unit == time_frame_unit.WEEK or chart.unit == time_frame_unit.MONTH:
        candidates = ['1D', '1M']
    elif chart.to_seconds() >= 1800:
        candidates = ['30m', '1h', '4h', '1m', '5m', '15m']
    if detail != 'Auto':
        candidates = [detail]
    for name in candidates:
        candidate = TimeFrame.from_str(name)
        if candidate > chart:
            continue
        aligned = False
        count = 0
        if candidate.unit == time_frame_unit.MONTH:
            aligned = chart.unit == time_frame_unit.MONTH and chart.count % candidate.count == 0
            count = chart.count // candidate.count
        elif chart.unit == time_frame_unit.MONTH:
            aligned = 86400 % candidate.to_seconds() == 0
            count = chart.count * 31 * 86400 // candidate.to_seconds()
        else:
            aligned = chart.to_seconds() % candidate.to_seconds() == 0
            count = chart.to_seconds() // candidate.to_seconds()
        if aligned and count <= 96:
            return name
    return None


def whole_profile_row_size_ticks() -> int:
    return 1000000000


def intraday_reset_seconds(anchor: str) -> int:
    if (anchor == '15m' or anchor == '30m' or anchor == '1h' or anchor == '2h' or anchor == '4h'
            or anchor == '6h' or anchor == '12h'):
        return TimeFrame.from_str(anchor).to_seconds()
    return 0


def auto_anchor(chart: TimeFrame) -> str:
    if chart.unit == time_frame_unit.WEEK or chart.unit == time_frame_unit.MONTH:
        return 'Continuous'
    seconds = chart.to_seconds()
    if seconds < 30:
        return '1h'
    if seconds < 60:
        return '4h'
    if seconds < 3600:
        return 'Trading day'
    if seconds < 86400:
        return 'Week'
    if seconds < 604800:
        return 'Month'
    return 'Continuous'


def resolve_anchor(chart: TimeFrame, anchor: str) -> str:
    if anchor != 'Auto':
        return anchor
    return auto_anchor(chart)


def profile_delta(profile: VolumeFootprintProfile, measure: str) -> float:
    if measure == 'Trades':
        return float(profile.total_trades_count_buy - profile.total_trades_count_sell)
    return profile.total_volume_buy - profile.total_volume_sell


@indicator('CVD', format=format.VOLUME)
@param.str('view', default='Candles', options=['Candles', 'Line'], title='View')
@param.str('measure', default='Volume', options=['Volume', 'Trades'], title='Measure')
@param.str('anchor', default='Auto',
           options=['Auto', 'Continuous', '15m', '30m', '1h', '2h', '4h', '6h', '12h', 'Trading day', 'Session',
                    'Week', 'Month'],
           title='Reset')
@param.str('session', default='Regular', options=['Regular', 'Pre-market', 'Post-market'], title='Session for session reset')
@param.bool('extended_hours', default=False, title='Include pre/post market')
@param.str('detail', default='Auto', options=['Auto', '1m', '5m', '15m', '30m', '1h', '4h', '1D', '1M'], title='Footprint detail')
@param.color('up_color', default=color.GREEN, title='Up color')
@param.color('down_color', default=color.RED, title='Down color')
@param.color('partial_color', default=color.GRAY, title='Incomplete accumulation color')
@level(0.0)
@plot.candles('cvd_candles', title='CVD candles')
@plot.line('cvd_line', title='CVD line')
class Main(MainContext):
    def __init__(self, anchor, session, extended_hours, detail):
        if self.time_frame.unit == TimeFrame.from_str('1T').unit:
            raise IndieError('Volume Footprint data is unavailable for tick charts; choose a time-based chart')
        chosen = detail_time_frame(self.time_frame, detail)
        if chosen is None:
            suggested = detail_time_frame(self.time_frame, 'Auto')
            if suggested is not None:
                raise IndieError('Footprint detail ' + detail + ' is not supported on this chart; choose Auto (' + suggested.value() + ')')
            raise IndieError('No compatible footprint detail; choose a minute or longer time-based chart')
        reset = resolve_anchor(self.time_frame, anchor)
        self._reset_seconds = float(intraday_reset_seconds(reset))
        types = [session_types.MAIN_SESSION]
        if extended_hours:
            types = [session_types.MAIN_SESSION, session_types.PRE_MARKET, session_types.POST_MARKET]
        if reset == 'Session':
            types = [session_types.MAIN_SESSION]
            if session == 'Pre-market':
                types = [session_types.PRE_MARKET]
            elif session == 'Post-market':
                types = [session_types.POST_MARKET]
        self._footprints = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=types, row_size_ticks=whole_profile_row_size_ticks()),
            time_frame=TimeFrame.from_str(chosen.value()))

    def _trading_day_start(self, timestamp: float) -> float:
        before = timestamp - 86400.0
        start = timestamp
        for step in range(17):
            middle = float(floor((before + start) / 2.0))
            if self.trading_session.is_same_period(timestamp, middle):
                start = middle
            else:
                before = middle
        return start

    # Every comparison is on bar open times, so a bar straddling a boundary stays in the period it
    # opened in and the reset lands on the next bar. That is what lets any reset run on any chart.
    def _same_period(self, current: float, previous: float, anchor: str, session: str, day_start: float) -> bool:
        if isnan(previous):
            return False
        if self._reset_seconds > 0.0:
            if not self.trading_session.is_same_period(current, previous):
                return False
            period = self._reset_seconds
            return floor((current - day_start) / period) == floor((previous - day_start) / period)
        if anchor == 'Trading day':
            return self.trading_session.is_same_period(current, previous)
        if anchor == 'Session':
            if session == 'Pre-market':
                return self.trading_session.pre_market.is_same_period(current, previous)
            if session == 'Post-market':
                return self.trading_session.after_hours.is_same_period(current, previous)
            return self.trading_session.regular.is_same_period(current, previous)
        if anchor == 'Week':
            return floor((current + 259200.0) / 604800.0) == floor((previous + 259200.0) / 604800.0)
        if anchor == 'Month':
            now = datetime.utcfromtimestamp(current)
            before = datetime.utcfromtimestamp(previous)
            return now.year == before.year and now.month == before.month
        return True

    def calc(self, view, measure, anchor, session, up_color, down_color, partial_color):
        reset = resolve_anchor(self.time_frame, anchor)
        base = MutSeries[float].new(nan)
        partial = MutSeries[bool].new(True)
        started = Var[bool].new(False)
        day_start = Var[float].new(nan)
        base.request_size(9)
        partial.request_size(9)
        self.time.request_size(9)
        base[0] = nan
        partial[0] = True
        opening = nan
        high = nan
        low = nan
        value = nan
        footprints = self._footprints
        footprints.request_subperiods(9)
        profiles = footprints.subperiods()
        if self._reset_seconds > 0.0 and (
                isnan(day_start.get()) or not self.trading_session.is_same_period(self.time[0], day_start.get())):
            day_start.set(self._trading_day_start(self.time[0]))
        if reset != 'Continuous' and not self._same_period(
                self.time[0], self.time.get(1, self.time[0] - 1.0), reset, session, day_start.get()):
            base[0] = 0.0
            partial[0] = False
        else:
            delta = 0.0
            for offset in range(1, 9):
                if offset > self.bar_index or not self._same_period(
                        self.time[0], self.time[offset], reset, session, day_start.get()):
                    break
                previous = footprints.subperiods(offset)
                if previous is None:
                    break
                for previous_profile in previous.value():
                    delta += profile_delta(previous_profile, measure)
                if not isnan(base[offset]):
                    base[0] = base[offset] + delta
                    partial[0] = partial[offset]
                    break
        if profiles is not None:
            if isnan(base[0]):
                base[0] = 0.0
                partial[0] = reset != 'Continuous' or started.get()
            started.set(True)
            opening = base[0]
            value = opening
            high = opening
            low = opening
            for profile in profiles.value():
                value += profile_delta(profile, measure)
                high = max(high, value)
                low = min(low, value)
        body_color = up_color if value >= opening else down_color
        if partial[0]:
            body_color = partial_color
        if view == 'Line':
            return plot.Candles(nan, nan, nan, nan), plot.Line(value, color=body_color)
        return plot.Candles(opening, high, low, value, color=body_color,
                            wick_color=body_color, border_color=body_color), plot.Line(nan)
```

## Delta Volume

```py Delta Volume theme={null}
# indie:lang_version = 5
from math import isnan, nan
from indie import (
    IndieError, MainContext, Optional, TimeFrame, color, format, indicator, level, param, plot,
    request_series, time_frame_unit,
)
from indie.data import VolumeFootprintProfile, sources
from indie.data.sources import session_types


def detail_time_frame(chart: TimeFrame, detail: str) -> Optional[str]:
    if chart.unit == TimeFrame.from_str('1T').unit or chart.to_seconds() < 60:
        return None
    if chart.unit == time_frame_unit.SECOND and chart.count % 60 != 0:
        return None
    candidates = ['1m', '5m', '15m']
    if chart.unit == time_frame_unit.WEEK or chart.unit == time_frame_unit.MONTH:
        candidates = ['1D', '1M']
    elif chart.to_seconds() >= 1800:
        candidates = ['30m', '1h', '4h', '1m', '5m', '15m']
    if detail != 'Auto':
        candidates = [detail]
    for name in candidates:
        candidate = TimeFrame.from_str(name)
        if candidate > chart:
            continue
        aligned = False
        count = 0
        if candidate.unit == time_frame_unit.MONTH:
            aligned = chart.unit == time_frame_unit.MONTH and chart.count % candidate.count == 0
            count = chart.count // candidate.count
        elif chart.unit == time_frame_unit.MONTH:
            aligned = 86400 % candidate.to_seconds() == 0
            count = chart.count * 31 * 86400 // candidate.to_seconds()
        else:
            aligned = chart.to_seconds() % candidate.to_seconds() == 0
            count = chart.to_seconds() // candidate.to_seconds()
        if aligned and count <= 96:
            return name
    return None


def whole_profile_row_size_ticks() -> int:
    return 1000000000


def buy_sell_time_frame(chart: TimeFrame) -> Optional[str]:
    if chart.unit == TimeFrame.from_str('1T').unit or chart.to_seconds() < 60:
        return None
    if chart.unit == time_frame_unit.SECOND:
        if chart.count % 60 != 0:
            return None
        return str(chart.count // 60) + 'm'
    if chart.unit == time_frame_unit.DAY or chart.unit == time_frame_unit.WEEK or chart.unit == time_frame_unit.MONTH:
        return '1D'
    if chart.unit == time_frame_unit.HOUR:
        return str(chart.count) + 'h'
    if chart.unit == time_frame_unit.MINUTE:
        return str(chart.count) + 'm'
    return None


@indicator('Delta Vol', format=format.VOLUME)
@param.bool('extended_hours', default=False, title='Include pre/post market')
@param.str('mode', default='Delta', options=['Delta', 'Buy/Sell'], title='Mode')
@param.str('detail', default='Auto', options=['Auto', '1m', '5m', '15m', '30m', '1h', '4h', '1D', '1M'], title='Delta candle detail')
@param.color('buy_col', default=color.GREEN, title='Buy color')
@param.color('sell_col', default=color.RED, title='Sell color')
@level(0.0)
@plot.candles('delta_candles', title='Delta')
@plot.columns('delta', title='Buy volume')
@plot.columns('sell', title='Sell volume')
class Main(MainContext):
    def __init__(self, extended_hours, detail, mode):
        if self.time_frame.unit == TimeFrame.from_str('1T').unit:
            raise IndieError('Volume Footprint data is unavailable for tick charts; choose a time-based chart')
        chosen = detail_time_frame(self.time_frame, detail)
        if mode == 'Buy/Sell':
            chosen = buy_sell_time_frame(self.time_frame)
        if chosen is None:
            suggested = detail_time_frame(self.time_frame, 'Auto')
            if suggested is not None:
                raise IndieError('Footprint detail ' + detail + ' is not supported on this chart; choose Auto (' + suggested.value() + ')')
            raise IndieError('No compatible footprint detail; choose a minute or longer time-based chart')
        types = [session_types.MAIN_SESSION]
        if extended_hours:
            types = [session_types.MAIN_SESSION, session_types.PRE_MARKET, session_types.POST_MARKET]
        self._footprints = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=types, row_size_ticks=whole_profile_row_size_ticks()),
            time_frame=TimeFrame.from_str(chosen.value()))

    def calc(self, mode, buy_col, sell_col):
        buy = nan
        sell = nan
        value = nan
        high = nan
        low = nan
        footprints = self._footprints
        footprints.request_subperiods(1)
        profiles = footprints.subperiods()
        if profiles is not None:
            buy = 0.0
            sell = 0.0
            value = 0.0
            high = 0.0
            low = 0.0
            for profile in profiles.value():
                buy += profile.total_volume_buy
                sell += profile.total_volume_sell
                value = buy - sell
                high = max(high, value)
                low = min(low, value)
        body_color = buy_col if value >= 0.0 else sell_col
        if mode == 'Buy/Sell':
            return plot.Candles(nan, nan, nan, nan), plot.Columns(buy, color=buy_col), plot.Columns(-sell, color=sell_col)
        opening = nan if isnan(value) else 0.0
        return plot.Candles(opening, high, low, value, color=body_color,
                            wick_color=body_color, border_color=body_color), plot.Columns(nan), plot.Columns(nan)
```

## Double EMA

```py Double EMA theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Ema


@indicator('DEMA', overlay_main_pane=True)  # Double EMA
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@plot.line(color=color.GREEN)
def Main(self, length, src):
    ema1 = Ema.new(src, length)
    ema2 = Ema.new(ema1, length)
    return 2 * ema1[0] - ema2[0]
```

## Detrended Price Oscillator

```py Detrended Price Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot
from indie.algorithms import Sma


@indicator('DPO', format=format.PRICE)  # Detrended Price Oscillator
@param.int('length', default=21, min=1)
@param.bool('centered', default=False, title='Centered')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.GREEN, title='Detrended Price Oscillator')
def Main(self, length, centered):
    bars_back = length // 2 + 1
    ma = Sma.new(self.close, length)
    dpo = self.close[bars_back] - ma[0] if centered else self.close[0] - ma[bars_back]
    return plot.Line(dpo, offset=-bars_back if centered else 0)
```

## Directional Movement Index

```py Directional Movement Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color
from indie.algorithms import Adx


@indicator('DMI', format=format.PRICE, precision=4)  # Directional Movement Index
@param.int('adx_len', default=14, min=1, title='ADX Smoothing')
@param.int('di_len', default=14, min=1, title='DI Length')
@plot.line(color=color.MAROON, title='-DI')
@plot.line(color=color.RED, title='ADX')
@plot.line(color=color.BLUE, title='+DI')
def Main(self, adx_len, di_len):
    minus, adx, plus = Adx.new(adx_len, di_len)
    return minus[0], adx[0], plus[0]
```

## Donchian Channels

```py Donchian Channels theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color
from indie.algorithms import Lowest, Highest, Donchian


@indicator('DC', overlay_main_pane=True)  # Donchian Channels
@param.int('length', default=20, min=1)
@plot.line('lower', color=color.BLUE, title='Lower')
@plot.line(color=color.RED, title='Basis')
@plot.line('upper', color=color.BLUE, title='Upper')
@plot.fill('lower', 'upper', color=color.AQUA(0.05), title='Background')
def Main(self, length):
    lower = Lowest.new(self.low, length)
    upper = Highest.new(self.high, length)
    basis = Donchian.new(length)
    return lower[0], basis[0], upper[0], plot.Fill()
```

## Ease of Movement

```py Ease of Movement theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color, MutSeriesF
from indie.algorithms import Change, Sma
from indie.math import divide


@indicator('EOM', format=format.VOLUME)  # Ease of Movement
@param.int('length', default=14, min=1)
@param.int('divisor', default=10000, min=1)
@plot.line(color=color.GREEN)
def Main(self, length, divisor):
    eom = divisor * Change.new(self.hl2)[0] * divide(self.high[0] - self.low[0], self.volume[0])
    return Sma.new(MutSeriesF.new(eom), length)[0]
```

## Elders Force Index

```py Elders Force Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot, MutSeriesF
from indie.algorithms import Change, Ema


@indicator('EFI', format=format.VOLUME)  # Elders Force Index
@param.int('length', default=13, min=1)
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.RED, title='Elders Force Index')
def Main(self, length):
    efi = Change.new(self.close)[0] * self.volume[0]
    return Ema.new(MutSeriesF.new(efi), length)[0]
```

## Exponential Moving Average

```py Exponential Moving Average theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Ema


@indicator('EMA', overlay_main_pane=True)  # Moving Average Exponential
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.int('offset', default=0, min=-500, max=500, title='Offset')
@plot.line(color=color.BLUE)
def Main(self, length, src, offset):
    ema = Ema.new(src, length)
    return plot.Line(ema[0], offset=offset)
    # TODO: implement smoothing when display.none is supported
```

## Envelope

```py Envelope theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Ema, Sma


@indicator('Env', overlay_main_pane=True)  # Envelope
@param.int('length', default=20, min=1)
@param.float('percent', default=10.0)
@param.source('src', default=source.CLOSE, title='Source')
@param.bool('exponential', default=False)
@plot.line('lower', color=color.BLUE, title='Lower')
@plot.line('basis', color=color.RED, title='Basis')
@plot.line('upper', color=color.BLUE, title='Upper')
@plot.fill('lower', 'upper', color=color.AQUA(0.05), title='Background')
def Main(self, length, percent, src, exponential):
    basis = 0.0
    if exponential:
        basis = Ema.new(src, length)[0]
    else:
        basis = Sma.new(src, length)[0]
    k = percent / 100.0
    upper = basis * (1 + k)
    lower = basis * (1 - k)
    return lower, basis, upper, plot.Fill()
```

## Fisher Transform

```py Fisher Transform theme={null}
# indie:lang_version = 5
from math import isnan, nan, log
from indie import indicator, format, param, level, color, plot, MutSeriesF
from indie.algorithms import Highest, Lowest
from indie.math import divide


def nan_to_zero(val: float) -> float:
    return 0 if isnan(val) else val


def round(val: float) -> float:
    if val > 0.99:
        val = 0.999
    elif val < -0.99:
        val = -0.999
    return val


@indicator('Fisher', format=format.PRICE)  # Fisher Transform
@param.int('length', default=9, min=1)
@level(-1.5, line_color=color.RED, title='-1.5')
@level(-0.75, line_color=color.GRAY, title='-0.75')
@level(0, line_color=color.RED, title='0')
@level(0.75, line_color=color.GRAY, title='0.75')
@level(1.5, line_color=color.RED, title='1.5')
@plot.line(color=color.BLUE, title='Fisher')
@plot.line(color=color.MAROON, title='Trigger')
def Main(self, length):
    high = Highest.new(self.hl2, length)[0]
    low = Lowest.new(self.hl2, length)[0]

    value = MutSeriesF.new(init=0)
    value[0] = round(0.66 * (divide(self.hl2[0] - low, high - low) - 0.5) + \
                     0.67 * nan_to_zero(value[1]))
    fish = MutSeriesF.new(init=nan)
    fish[0] = 0.5 * log(divide(1 + value[0], 1 - value[0])) + 0.5 * nan_to_zero(fish[1])
    return fish[0], fish[1]
```

## Historical Volatility

```py Historical Volatility theme={null}
# indie:lang_version = 5
from math import log, sqrt
from indie import indicator, format, param, plot, color, MutSeriesF
from indie.algorithms import StdDev


@indicator('HV', format=format.PRICE, precision=2)  # Historical Volatility
@param.int('length', default=10, min=1, title='Length')
@plot.line(color=color.BLUE, title='HV')
def Main(self, length):
    log_return = MutSeriesF.new(log(self.close[0] / self.close[1]))
    # Intraday and daily bars annualize with 365 periods, larger time frames with 365 / 7 (TradingView rule).
    periods = 365.0
    if self.time_frame.to_seconds() > 86400:
        periods = 365.0 / 7.0
    return 100.0 * StdDev.new(log_return, length)[0] * sqrt(periods)
```

## Hull Moving Average

```py Hull Moving Average theme={null}
# indie:lang_version = 5
from math import floor, sqrt
from indie import indicator, param, source, plot, color, MutSeriesF
from indie.algorithms import Wma


@indicator('HMA', overlay_main_pane=True)  # Hull Moving Average
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@plot.line(color=color.BLUE)
def Main(self, length, src):
    wma_l2 = Wma.new(src, length // 2)[0]
    wma_l = Wma.new(src, length)[0]
    return Wma.new(MutSeriesF.new(2 * wma_l2 - wma_l), floor(sqrt(length)))[0]
```

## Ichimoku Cloud

```py Ichimoku Cloud theme={null}
# indie:lang_version = 5
from indie import SeriesF, MutSeriesF, indicator, param, plot, color
from indie.algorithms import Donchian


def mean(price1: SeriesF, price2: SeriesF) -> float:
    # TODO: implement @algorithm avg with variable number of arguments in indie.algorithms
    return (price1[0] + price2[0]) / 2


# TODO: Add palette of colors
@indicator('Ichimoku', overlay_main_pane=True)  # Ichimoku Cloud
@param.int('conversion_periods', default=9, min=1, title='Conversion Line Length')
@param.int('base_periods', default=26, min=1, title='Base Line Length')
@param.int('lagging_span_2_periods', default=52, min=1, title='Leading Span B Length')
@param.int('displacement', default=26, min=1, title='Lagging Span')
@plot.line(color=color.BLUE, title='Conversion Line')
@plot.line(color=color.RED, title='Base Line')
@plot.line(color=color.GREEN, title='Lagging Span')
@plot.line('ls_a', color=color.GREEN(0.6), title='Leading Span A')
@plot.line('ls_b', color=color.RED(0.6), title='Leading Span B')
@plot.fill('ls_a', 'ls_b', title='Background Up', color=color.GREEN(0.1))
@plot.fill('ls_a', 'ls_b', title='Background Down', color=color.RED(0.1))
def Main(self, conversion_periods, base_periods, lagging_span_2_periods, displacement):
    conversion_line = Donchian.new(conversion_periods)
    base_line = Donchian.new(base_periods)
    lead_line1 = mean(conversion_line, base_line)
    lead_line2 = Donchian.new(lagging_span_2_periods)[0]

    fill_up_color = None if lead_line1 > lead_line2 else color.TRANSPARENT
    fill_down_color = color.TRANSPARENT if lead_line1 > lead_line2 else None
    return (
        conversion_line[0],
        base_line[0],
        plot.Line(self.close[0], offset=-displacement + 1),
        plot.Line(lead_line1, offset=displacement - 1),
        plot.Line(lead_line2, offset=displacement - 1),
        plot.Fill(offset=displacement - 1, color=fill_up_color),
        plot.Fill(offset=displacement - 1, color=fill_down_color),
    )
```

## Keltner Channels

```py Keltner Channels theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color, MutSeriesF
from indie.algorithms import Ma, Tr, Atr, Rma


@indicator('KC', overlay_main_pane=True)  # Keltner Channels
@param.int('length', default=20, min=1)
@param.float('mult', default=2.0, title='Multiplier')
@param.source('src', default=source.CLOSE, title='Source')
@param.bool('exp', default=True, title='Use Exponential MA')
@param.str('bands_style', default='Average True Range', title='Bands Style',
           options=['Average True Range', 'True Range', 'Range'])
@param.int('atr_length', default=10, min=1, title='ATR Length')
@plot.line('lower', color=color.BLUE, title='Lower')
@plot.line(color=color.BLUE, title='Basis')
@plot.line('upper', color=color.BLUE, title='Upper')
@plot.fill('lower', 'upper', color=color.AQUA(0.05), title='Background')
def Main(self, length, mult, src, exp, bands_style, atr_length):
    ma = Ma.new(src, length, 'EMA' if exp else 'SMA')[0]
    range_ma = 0.0
    if bands_style == 'True Range':
        range_ma = Tr.new(True)[0]
    elif bands_style == 'Average True Range':
        range_ma = Atr.new(atr_length)[0]
    else:  # bands_style == 'Range'
        range_ma = Rma.new(MutSeriesF.new(self.high[0] - self.low[0]), length)[0]
    upper = ma + range_ma * mult
    lower = ma - range_ma * mult
    return lower, ma, upper, plot.Fill()
```

## Klinger Oscillator

```py Klinger Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, plot, color, MutSeriesF
from indie.algorithms import Change, Ema


@indicator('Klinger Osc', format=format.VOLUME)  # Klinger Oscillator
@plot.line(color=color.BLUE, title='KO')
@plot.line(color=color.GREEN, title='Signal')
def Main(self):
    sv = MutSeriesF.new(self.volume[0] if Change.new(self.hlc3)[0] >= 0 else -self.volume[0])
    kvo = MutSeriesF.new(Ema.new(sv, 34)[0] - Ema.new(sv, 55)[0])
    sig = Ema.new(kvo, 13)
    return kvo[0], sig[0]
```

## Know Sure Thing

```py Know Sure Thing theme={null}
# indie:lang_version = 5
from indie import algorithm, MutSeriesF, SeriesF, indicator, format, param, level, color, plot
from indie.algorithms import Sma, Roc


@algorithm
def SmaRoc(self, roc_len: int, sma_len: int) -> SeriesF:
    return Sma.new(Roc.new(self.ctx.close, roc_len), sma_len)


@indicator('KST', format=format.PRICE, precision=4)  # Know Sure Thing
@param.int('roc_len1', default=10, min=1, title='ROC Length #1')
@param.int('roc_len2', default=15, min=1, title='ROC Length #2')
@param.int('roc_len3', default=20, min=1, title='ROC Length #3')
@param.int('roc_len4', default=30, min=1, title='ROC Length #4')
@param.int('sma_len1', default=10, min=1, title='SMA Length #1')
@param.int('sma_len2', default=10, min=1, title='SMA Length #2')
@param.int('sma_len3', default=10, min=1, title='SMA Length #3')
@param.int('sma_len4', default=15, min=1, title='SMA Length #4')
@param.int('sig_len', default=9, min=1, title='Signal Line Length')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.GREEN, title='KST')
@plot.line(color=color.RED, title='Signal')
def Main(self, roc_len1, roc_len2, roc_len3, roc_len4, sma_len1, sma_len2, sma_len3, sma_len4, sig_len):
    kst = 1 * SmaRoc.new(roc_len1, sma_len1)[0] + \
          2 * SmaRoc.new(roc_len2, sma_len2)[0] + \
          3 * SmaRoc.new(roc_len3, sma_len3)[0] + \
          4 * SmaRoc.new(roc_len4, sma_len4)[0]
    sig = Sma.new(MutSeriesF.new(kst), sig_len)[0]
    return kst, sig
```

## Linear Regression Channel

```py Linear Regression Channel theme={null}
# indie:lang_version = 5
from math import sqrt, isnan, nan
from indie import indicator, param, source, color, MainContext, SeriesF
from indie.drawings import LineSegment, LabelAbs, AbsolutePosition, extend_type, callout_position
from indie.math import divide


def calc_slope(src: SeriesF, length: int) -> tuple[float, float, float]:
    sum_x = 0.0
    sum_y = 0.0
    sum_x_sqr = 0.0
    sum_xy = 0.0

    for i in range(length):
        val = src[i]
        per = i + 1.0
        sum_x += per
        sum_y += val
        sum_x_sqr += per * per
        sum_xy += val * per

    slope = divide(length * sum_xy - sum_x * sum_y, length * sum_x_sqr - sum_x * sum_x)
    average = sum_y / length
    intercept = average - slope * sum_x / length + slope

    return slope, average, intercept


def calc_dev(slope: float, average: float, intercept: float,
             src: SeriesF, high: SeriesF, low: SeriesF, length: int) -> tuple[float, float, float, float]:
    up_dev = 0.0
    dn_dev = 0.0
    std_dev_acc = 0.0
    dsxx = 0.0
    dsyy = 0.0
    dsxy = 0.0
    periods = length - 1
    day_y = intercept + slope * periods / 2
    val = intercept

    for j in range(length):
        price = high[j] - val
        if price > up_dev:
            up_dev = price

        price = val - low[j]
        if price > dn_dev:
            dn_dev = price

        price = src[j]
        dxt = price - average
        dyt = val - day_y
        price -= val
        std_dev_acc += price * price
        dsxx += dxt * dxt
        dsyy += dyt * dyt
        dsxy += dxt * dyt
        val += slope

    std_dev = sqrt(std_dev_acc / (periods if periods != 0 else 1))
    pearson_r = divide(dsxy, sqrt(dsxx * dsyy), 0.0)

    return std_dev, pearson_r, up_dev, dn_dev


@indicator('Linear Regression Channel', overlay_main_pane=True)
@param.int('length_input', default=100, min=1, max=5000, title='Length')
@param.source('source_input', default=source.CLOSE, title='Source')
@param.bool('use_upper_dev_input', default=True, title='Upper Deviation')
@param.float('upper_mult_input', default=2.0, title='Upper Multiplier')
@param.bool('use_lower_dev_input', default=True, title='Lower Deviation')
@param.float('lower_mult_input', default=2.0, title='Lower Multiplier')
@param.bool('show_pearson_input', default=True, title="Show Pearson's R")
@param.bool('extend_left_input', default=False, title='Extend Lines Left')
@param.bool('extend_right_input', default=True, title='Extend Lines Right')
class Main(MainContext):
    def __init__(self, extend_left_input, extend_right_input):
        # Determine extend type
        extend_style = extend_type.NONE
        if extend_left_input and extend_right_input:
            extend_style = extend_type.BOTH
        elif extend_left_input:
            extend_style = extend_type.LEFT
        elif extend_right_input:
            extend_style = extend_type.RIGHT

        self._base_line = LineSegment(
            AbsolutePosition(0, 0),
            AbsolutePosition(0, 0),
            extend_type=extend_style,
            color=color.RED,
        )
        self._upper_line = LineSegment(
            AbsolutePosition(0, 0),
            AbsolutePosition(0, 0),
            extend_type=extend_style,
            color=color.BLUE,
        )
        self._lower_line = LineSegment(
            AbsolutePosition(0, 0),
            AbsolutePosition(0, 0),
            extend_type=extend_style,
            color=color.BLUE,
        )
        self._pearson_label = LabelAbs(
            '',
            AbsolutePosition(0, 0),
            text_color=color.BLUE,
            callout_position=callout_position.BOTTOM_LEFT,
            bg_color=color.TRANSPARENT,
        )

    def calc(self,
             length_input, source_input,
             use_upper_dev_input, upper_mult_input,
             use_lower_dev_input, lower_mult_input,
             show_pearson_input):
        if not self.is_last_bar:
            return

        # Calculate regression parameters
        slope, average, intercept = calc_slope(source_input, length_input)

        if isnan(slope):
            return

        start_price = intercept + slope * (length_input - 1)
        end_price = intercept

        # Calculate deviations
        std_dev, pearson_r, up_dev, dn_dev = calc_dev(slope, average, intercept, source_input,
                                                      self.high, self.low, length_input)

        upper_start_price = start_price + (upper_mult_input * std_dev if use_upper_dev_input else up_dev)
        upper_end_price = end_price + (upper_mult_input * std_dev if use_upper_dev_input else up_dev)
        lower_start_price = start_price + (-lower_mult_input * std_dev if use_lower_dev_input else -dn_dev)
        lower_end_price = end_price + (-lower_mult_input * std_dev if use_lower_dev_input else -dn_dev)

        # Draw lines
        if not isnan(start_price) and not isnan(upper_start_price) and not isnan(lower_start_price):
            start_x = self.time[length_input - 1]
            end_x = self.time[0]

            # Update base line coordinates
            self._base_line.point_a = AbsolutePosition(start_x, start_price)
            self._base_line.point_b = AbsolutePosition(end_x, end_price)
            self.chart.draw(self._base_line)

            # Update upper line coordinates
            self._upper_line.point_a = AbsolutePosition(start_x, upper_start_price)
            self._upper_line.point_b = AbsolutePosition(end_x, upper_end_price)
            self.chart.draw(self._upper_line)

            # Update lower line coordinates
            self._lower_line.point_a = AbsolutePosition(start_x, lower_start_price)
            self._lower_line.point_b = AbsolutePosition(end_x, lower_end_price)
            self.chart.draw(self._lower_line)

            # Update Pearson's R label text and position
            if show_pearson_input and not isnan(pearson_r):
                self._pearson_label.text = str(round(pearson_r, 8))
                self._pearson_label.position = AbsolutePosition(start_x, lower_start_price)
                self.chart.draw(self._pearson_label)
```

## Least Squares Moving Average

```py Least Squares Moving Average theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot
from indie.algorithms import LinReg


@indicator('LSMA', overlay_main_pane=True)  # Least Squares Moving Average
@param.int('length', default=25, min=1)
@param.int('offset', default=0)
@param.source('src', default=source.CLOSE)
@plot.line(title='LSMA')
def Main(self, length, offset, src):
    return LinReg.new(src, length, offset)[0]
```

## MA Cross

```py MA Cross theme={null}
# indie:lang_version = 5
from math import nan
from indie import indicator, param, plot, color
from indie.algorithms import Sma
from indie.math import cross


@indicator('MA Cross', overlay_main_pane=True)  # MA Cross
@param.int('short_len', default=9, min=1, title='Short MA Length')
@param.int('long_len', default=21, min=1, title='Long MA Length')
@plot.line(color=color.MAROON, title='Short')
@plot.line(color=color.GREEN, title='Long')
@plot.marker(color=color.BLUE, style=plot.marker_style.CROSS,
             position=plot.marker_position.CENTER, size=7, title='MA Cross')
def Main(self, short_len, long_len):
    short = Sma.new(self.close, short_len)
    long = Sma.new(self.close, long_len)
    return short[0], long[0], short[0] if cross(short, long) else nan
```

## Moving Average Ribbon

```py Moving Average Ribbon theme={null}
# indie:lang_version = 5
from math import nan
from indie import indicator, param, source, plot, color
from indie.algorithms import Ma


@indicator('MA Ribbon', overlay_main_pane=True)  # Moving Average Ribbon
@param.bool('ma1', default=True, title='Show MA №1')
@param.str('ma1_type', default='SMA', title='MA №1 Type', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'])
@param.source('ma1_source', default=source.CLOSE, title='MA №1 Source')
@param.int('ma1_length', default=20, min=1, title='MA №1 Length')
@param.bool('ma2', default=True, title='Show MA №2')
@param.str('ma2_type', default='SMA', title='MA №2 Type', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'])
@param.source('ma2_source', default=source.CLOSE, title='MA №2 Source')
@param.int('ma2_length', default=50, min=1, title='MA №2 Length')
@param.bool('ma3', default=True, title='Show MA №3')
@param.str('ma3_type', default='SMA', title='MA №3 Type', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'])
@param.source('ma3_source', default=source.CLOSE, title='MA №3 Source')
@param.int('ma3_length', default=100, min=1, title='MA №3 Length')
@param.bool('ma4', default=True, title='Show MA №4')
@param.str('ma4_type', default='SMA', title='MA №4 Type', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'])
@param.source('ma4_source', default=source.CLOSE, title='MA №4 Source')
@param.int('ma4_length', default=200, min=1, title='MA №4 Length')
@plot.line(color=color.rgba(246, 195, 9), title='MA №1')
@plot.line(color=color.rgba(251, 152, 0), title='MA №2')
@plot.line(color=color.rgba(251, 101, 0), title='MA №3')
@plot.line(color=color.rgba(246, 12, 12), title='MA №4')
def Main(self, ma1, ma1_type, ma1_source, ma1_length, \
         ma2, ma2_type, ma2_source, ma2_length, \
         ma3, ma3_type, ma3_source, ma3_length, \
         ma4, ma4_type, ma4_source, ma4_length):
    ma1_val = Ma.new(ma1_source, ma1_length, ma1_type)[0]
    ma2_val = Ma.new(ma2_source, ma2_length, ma2_type)[0]
    ma3_val = Ma.new(ma3_source, ma3_length, ma3_type)[0]
    ma4_val = Ma.new(ma4_source, ma4_length, ma4_type)[0]
    return ma1_val if ma1 else nan, \
           ma2_val if ma2 else nan, \
           ma3_val if ma3 else nan, \
           ma4_val if ma4 else nan
```

## Moving Average Convergence Divergence

```py Moving Average Convergence Divergence theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, level, color, plot, Color
from indie.algorithms import Macd


@indicator('MACD')  # Moving Average Convergence Divergence
@param.int('fast_length', default=12, min=1, title='Fast Length')
@param.int('slow_length', default=26, min=1, title='Slow Length')
@param.source('src', default=source.CLOSE, title='Source')
@param.int('signal_length', default=9, min=1, max=50, title='Signal Smoothing')
@param.str('sma_source', default='EMA', title='Oscillator MA Type', options=['SMA', 'EMA'])
@param.str('sma_signal', default='EMA', title='Signal Line MA Type', options=['SMA', 'EMA'])
@level(0, line_color=color.GRAY(0.5))
@plot.columns(title='Histogram')
@plot.line(color=color.BLUE, title='MACD')
@plot.line(color=color.MAROON, title='Signal')
def Main(self, fast_length, slow_length, src, signal_length, sma_source, sma_signal):
    macd, signal, hist = Macd.new(src, fast_length, slow_length, signal_length, sma_source, sma_signal)

    hist_color = color.BLACK  # default value
    if hist[0] >= 0:
        if hist[1] < hist[0]:
            hist_color = color.GREEN
        else:
            hist_color = color.LIME
    else:
        if hist[1] < hist[0]:
            hist_color = color.RED
        else:
            hist_color = color.MAROON

    return (
        plot.Columns(hist[0], color=hist_color),
        macd[0],
        signal[0],
    )
```

## Majority Rule

```py Majority Rule theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, level, plot, color, MutSeriesF
from indie.algorithms import Sum


@indicator('MR', format=format.PRICE, precision=2)  # Majority Rule
@param.int('length', default=10, min=1, title='Length')
@param.source('source', default=source.CLOSE, title='Source')
@level(50, line_color=color.GRAY, title='Middle')
@plot.line(color=color.BLUE, title='MR')
def Main(self, length, source):
    up = 1.0 if source[0] > source[1] else 0.0
    up_bars = MutSeriesF.new(up)
    return 100.0 * Sum.new(up_bars, length)[0] / float(length)
```

## Mass Index

```py Mass Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color, MutSeriesF
from indie.algorithms import Ema, Sum
from indie.math import divide


@indicator('Mass Index', format=format.PRICE)
@param.int('length', default=10, min=1)
@plot.line(color=color.BLUE)
def Main(self, length):
    span = MutSeriesF.new(self.high[0] - self.low[0])
    ema1 = Ema.new(span, 9)
    ema2 = Ema.new(ema1, 9)
    return Sum.new(MutSeriesF.new(divide(ema1[0], ema2[0])), length)[0]
```

## McGinley Dynamic

```py McGinley Dynamic theme={null}
# indie:lang_version = 5
from math import isnan, pow
from indie import indicator, param, plot, color, MutSeriesF
from indie.algorithms import Ema
from indie.math import divide


@indicator('McGinley', overlay_main_pane=True)  # McGinley Dynamic
@param.int('length', default=14, min=1)
@plot.line(color=color.BLUE)
def Main(self, length):
    mg = MutSeriesF.new(init=0)
    if isnan(mg[1]):
        mg[0] = Ema.new(self.close, length)[0]
    else:
        mg[0] = mg[1] + divide(self.close[0] - mg[1], length * pow(divide(self.close[0], mg[1]), 4))
    return mg[0]
```

## Median

```py Median theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color, MutSeriesF
from indie.algorithms import Median, Atr, Ema


@indicator('Median', overlay_main_pane=True)
@param.source('src', default=source.HL2, title='Source')
@param.int('length', default=3, min=1, title='Median Length')
@param.int('atr_length', default=14, min=1, title='ATR Length')
@param.int('atr_mult', default=2, min=1, title='ATR Multiplier')
@plot.line('ema', color=color.BLUE, title='Median EMA')
@plot.line(color=color.FUCHSIA, title='Lower Band')
@plot.line('median', color=color.RED, line_width=3, title='Median')
@plot.line(color=color.LIME, title='Upper Band')
@plot.fill('median', 'ema', title='Background')
def Main(self, src, length, atr_length, atr_mult):
    median = Median.new(src, length)[0]

    atr = atr_mult * Atr.new(atr_length)[0]

    median_ema = Ema.new(MutSeriesF.new(median), length)[0]

    fill_color = color.LIME(0.9) if median > median_ema else color.FUCHSIA(0.9)
    return (
        median_ema,
        median - atr,
        median,
        median + atr,
        plot.Fill(color=fill_color),
    )
```

## Momentum

```py Momentum theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Change


@indicator('Mom')  # Momentum
@param.int('length', default=10, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@plot.line(color=color.BLUE)
def Main(self, length, src):
    return Change.new(src, length)[0]
```

## Money Flow Index

```py Money Flow Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, band, color, level, plot
from indie.algorithms import Mfi


@indicator('MFI', format=format.PRICE)  # Money Flow Index
@param.int('length', default=14, min=1)
@param.source('src', default=source.HLC3, title='Source')
@band(20, 80, line_color=color.GRAY, fill_color=color.PURPLE(0.1), title='Background')
@level(50, line_color=color.GRAY, title='Middle Band')
@plot.line(color=color.PURPLE, title='MF')
def Main(self, length, src):
    return Mfi.new(src, length)[0]
```

## Net Volume

```py Net Volume theme={null}
# indie:lang_version = 5
from indie import indicator, format, plot, color
from indie.algorithms import NetVolume


@indicator('Net Volume', format=format.VOLUME)
@plot.line(color=color.BLUE)
def Main(self):
    return NetVolume.new(self.close)[0]
```

## On Balance Volume

```py On Balance Volume theme={null}
# indie:lang_version = 5
from indie import indicator, format, plot, color
from indie.algorithms import CumSum, NanToZero, NetVolume


@indicator('OBV', format=format.VOLUME)  # On Balance Volume
@plot.line(color=color.BLUE)
def Main(self):
    return CumSum.new(NanToZero.new(NetVolume.new(self.close)))[0]
    # TODO: implement smoothing when display.none is supported
```

## Parabolic Stop And Reverse

```py Parabolic Stop And Reverse theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color
from indie.algorithms import Sar


@indicator('SAR', overlay_main_pane=True)  # Parabolic Stop And Reverse
@param.float('start', default=0.02)
@param.float('increment', default=0.02)
@param.float('maximum', default=0.2)
@plot.marker(style=plot.marker_style.CROSS, color=color.BLUE, title='ParabolicSAR')
def Main(self, start, increment, maximum):
    return Sar.new(start, increment, maximum)[0]
```

## Periodic Volume Profile

```py Periodic Volume Profile theme={null}
# indie:lang_version = 5
from datetime import datetime
from math import ceil, inf, isnan, nan
from indie import (
    IndieError, MainContext, TimeFrame, color, format, indicator, line_style, param, plot, request_series,
)
from indie.data import VolumeFootprintProfile, sources
from indie.data.sources import session_types
from indie.drawings import price_histogram_display_mode, secondary_histogram_display_mode


def footprint_time_frame(period: TimeFrame) -> TimeFrame:
    # Bound retained source profiles, using minute storage for intraday profiles.
    if period <= TimeFrame.from_str('1h'):
        return TimeFrame.from_str('1m')
    if period <= TimeFrame.from_str('4h'):
        return TimeFrame.from_str('5m')
    if period <= TimeFrame.from_str('12h') or period.unit == TimeFrame.from_str('1h').unit:
        return TimeFrame.from_str('15m')
    if period <= TimeFrame.from_str('1D'):
        return TimeFrame.from_str('20m')
    if period <= TimeFrame.from_str('1W'):
        return TimeFrame.from_str('3h')
    # Keep overnight trading days intact at calendar boundaries.
    return TimeFrame.from_str('1D')


@indicator('PVP', overlay_main_pane=True, format=format.VOLUME)
@param.calc_time_frame(
    'period', default='Auto', title='Period',
    options={'Auto': '', 'Minute': '1m', 'Hour': '1h', 'Day': '1D', 'Week': '1W', 'Month': '1M'},
    count_param='period_count', extended_hours=False,
    auto={0: '15m', 30: '1h', 61: '2h', 181: '4h', 301: '8h', 601: '12h', 901: '1D', 3601: '1W', 14401: '1M'},
)
@param.int('period_count', default=1, min=1, max=59, title='Count')
@param.str('row_size', default='Auto', options=['Auto', 'Auto Merge', 'Manual'], title='Row Size')
@param.float('row_size_price', default=0.0, min=0.0, title='Price per Row (0 = minimum)')
@plot.price_histogram_series(
    'vp', title='Volume Profile',
    layers=[plot.ProfileLayer('Buy', color.LIME(0.3), color.LIME(0.12), outline_color=color.LIME(0.5)),
            plot.ProfileLayer('Sell', color.RED(0.3), color.RED(0.12), outline_color=color.RED(0.5))],
    display_mode=price_histogram_display_mode.TOTAL, width_fraction=0.3,
    values_visible=True, totals_visible=True, value_color=color.GRAY,
    total_color=color.BLUE(0.35), total_color_outside_value_area=color.BLUE(0.14),
    total_outline_color=color.BLUE(0.5),
    value_area=0.7, poc_visible=True, poc_color=color.GRAY, poc_line_style=line_style.SOLID,
    secondary_histogram=plot.SecondaryHistogram(
        secondary_histogram_display_mode.DELTA, visible=True, width=0.1,
        layers=[plot.SecondaryHistogramLayer(color.GREEN(0.3), color.GREEN(0.12), outline_color=color.GREEN(0.5)),
                plot.SecondaryHistogramLayer(color.ORANGE(0.3), color.ORANGE(0.12),
                                             outline_color=color.ORANGE(0.5))]),
)
class Main(MainContext):
    def __init__(self, period, period_count, row_size):
        if period.unit == TimeFrame.from_str('1h').unit and period.count > 24:
            raise IndieError('Count is at most 24 for an Hour period')
        if period > TimeFrame.from_str('1D') and period.count > 1:
            raise IndieError('Count above 1 is not available yet for a calendar period')
        ticks = 0 if row_size == 'Auto' else 1
        self._profiles = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=[session_types.MAIN_SESSION], row_size_ticks=ticks,
                                          row_size_scope='Profile'),
            time_frame=footprint_time_frame(period))

    def calc(self, row_size, row_size_price):
        self._profiles.request_subperiods(1)
        profiles = self._profiles.subperiods()
        if profiles is None or len(profiles.value()) == 0:
            return plot.PriceHistogramSeries(nan)
        duration = float(self.time_frame.to_seconds())
        if self.time_frame.unit == TimeFrame.from_str('1M').unit:
            date = datetime.utcfromtimestamp(self.time[0])
            month = date.month % 12 + 1
            year = date.year + (1 if month == 1 else 0)
            duration = (datetime(year, month, 1) -
                        datetime(date.year, date.month, date.day, date.hour, date.minute, date.second)).total_seconds()
        elif self.time_frame.unit == TimeFrame.from_str('1W').unit:
            week_date = datetime.utcfromtimestamp(self.time[0])
            duration = float((7 - week_date.weekday()) * 86400 -
                             week_date.hour * 3600 - week_date.minute * 60 - week_date.second)
        time_to = self.time[0] + duration
        selected = profiles.value()
        count = len(selected)
        while count > 0 and selected[count - 1].profile_start_unix_seconds >= time_to:
            count -= 1
        selected = selected[:count]
        if len(selected) == 0:
            return plot.PriceHistogramSeries(nan)
        step = selected[0].row_size
        for profile in selected:
            step = profile.common_row_size(step)
        if isnan(step):
            return plot.PriceHistogramSeries(nan)
        levels = max(1, ceil(round(row_size_price / step, 9))) if row_size == 'Manual' else 1
        low = inf
        high = -inf
        for footprint in selected:
            for level in footprint.rows:
                low = min(low, level.price)
                high = max(high, level.price)
        if high >= low:
            levels = max(levels, ceil((high - low) / (2046 * step)))
        result = plot.PriceHistogramSeries(levels * step)
        result.time_to = time_to
        result.merge_rows_on_zoom = row_size == 'Auto Merge'
        for contribution in selected:
            for row in contribution.rows:
                result.add(row.price, [row.volume_buy, row.volume_sell])
        return result
```

## Pivot Points High/Low

```py Pivot Points High/Low theme={null}
# indie:lang_version = 5
from math import isnan
from indie import indicator, param, Optional, MainContext, color
from indie.algorithms import PivotHighLow, SinceHighest, SinceLowest
from indie.drawings import LabelAbs, AbsolutePosition, callout_position


@indicator('Pivots High/Low', overlay_main_pane=True)
@param.int('length_high_left', default=10, min=1, title='High left length')
@param.int('length_low_left', default=10, min=1, title='Low left length')
@param.int('length_high_right', default=10, min=1, title='High right length')
@param.int('length_low_right', default=10, min=1, title='Low right length')
# Display potential pivot points in real-time before right-side confirmation
@param.bool('show_unconfirmed', default=True, title='Show potential pivot points')
class Main(MainContext):
    def __init__(self):
        none_label: Optional[LabelAbs] = None
        self._prev_high_pivot = self.new_var(none_label)
        self._prev_high_pivot_bar_index = self.new_var(0)
        self._prev_low_pivot = self.new_var(none_label)
        self._prev_low_pivot_bar_index = self.new_var(0)

    def calc(self, length_high_left, length_low_left, length_high_right, length_low_right, show_unconfirmed):
        if show_unconfirmed:
            sh = SinceHighest.new(self.high, length_high_left + 1)
            sl = SinceLowest.new(self.low, length_low_left + 1)

            if sh[0] == 0:
                # we have a new high pivot candidate
                new_h_pivot_candidate_y = self.high[0]
                hp_opt: Optional[LabelAbs] = self._prev_high_pivot.get()
                if hp_opt is not None:  # we have a previous high pivot, must decide which one is better
                    if self.bar_index - self._prev_high_pivot_bar_index.get() > length_high_right:
                        self._prev_high_pivot.set(None)  # prev_high_pivot is too far away in history, forget about it
                    elif hp_opt.value().position.price < new_h_pivot_candidate_y:
                        self._update_high_pivot()  # new pivot candidate is better, update previous pivot
                    # else new pivot candidate is worse, keep the previous pivot
                if self._prev_high_pivot.get() is None:
                    self._update_high_pivot()  # create new low pivot
            if sl[0] == 0:
                new_l_pivot_candidate_y = self.low[0]
                lp_opt: Optional[LabelAbs] = self._prev_low_pivot.get()
                if lp_opt is not None:  # we have a previous low pivot, must decide which one is better
                    if self.bar_index - self._prev_low_pivot_bar_index.get() > length_low_right:
                        self._prev_low_pivot.set(None)  # prev_low_pivot is too far away in history, forget about it
                    elif lp_opt.value().position.price > new_l_pivot_candidate_y:
                        self._update_low_pivot()  # new pivot candidate is better, update previous pivot
                    # else new pivot candidate is worse, keep the previous pivot
                if self._prev_low_pivot.get() is None:
                    self._update_low_pivot()  # create new low pivot
        else:
            ph, _ = PivotHighLow.new(self.high, left_bars=length_high_left, right_bars=length_high_right)
            _, pl = PivotHighLow.new(self.low, left_bars=length_low_left, right_bars=length_low_right)

            if not isnan(ph[0]):
                new_pivot_y = self.high[length_high_right]
                new_pivot_x = self.time[length_high_right]
                self.chart.draw(self._create_new_label(new_pivot_x, new_pivot_y, is_high=True))  # create and draw

            if not isnan(pl[0]):
                new_pivot_y = self.low[length_low_right]
                new_pivot_x = self.time[length_low_right]
                self.chart.draw(self._create_new_label(new_pivot_x, new_pivot_y, is_high=False))  # create and draw

    def _update_high_pivot(self) -> None:
        new_pivot_y = self.high[0]
        new_pivot_x = self.time[0]
        new_pivot_bar_index = self.bar_index

        if self._prev_high_pivot.get() is None:  # create and draw
            self._prev_high_pivot.set(self._create_new_label(new_pivot_x, new_pivot_y, is_high=True))
        else:  # update field values and redraw
            hp = self._prev_high_pivot.get().value()
            hp.position = AbsolutePosition(new_pivot_x, new_pivot_y)
            hp.text = str(round(new_pivot_y, self.info.price_precision))

        self._prev_high_pivot_bar_index.set(new_pivot_bar_index)
        self.chart.draw(self._prev_high_pivot.get().value())

    def _update_low_pivot(self) -> None:
        new_pivot_y = self.low[0]
        new_pivot_x = self.time[0]
        new_pivot_bar_index = self.bar_index

        if self._prev_low_pivot.get() is None:  # create and draw
            self._prev_low_pivot.set(self._create_new_label(new_pivot_x, new_pivot_y, is_high=False))
        else:  # update field values and redraw
            lp = self._prev_low_pivot.get().value()
            lp.position = AbsolutePosition(new_pivot_x, new_pivot_y)
            lp.text = str(round(new_pivot_y, self.info.price_precision))

        self._prev_low_pivot_bar_index.set(new_pivot_bar_index)
        self.chart.draw(self._prev_low_pivot.get().value())

    def _create_new_label(self, time: float, price: float, is_high: bool) -> LabelAbs:
        text_color = color.GREEN if is_high else color.RED
        callout_pos = callout_position.TOP_RIGHT if is_high else callout_position.BOTTOM_LEFT
        return LabelAbs(
            str(round(price, self.info.price_precision)),
            AbsolutePosition(time, price),
            callout_position=callout_pos,
            bg_color=color.TRANSPARENT,
            text_color=text_color,
            font_size=11,
        )
```

## Pivot Points Standard

```py Pivot Points Standard theme={null}
# indie:lang_version = 5
from indie import indicator, param, sec_context, Optional, MainContext, MutSeriesF, Var, color, TimeFrame
from indie.drawings import LineSegment, LabelAbs, AbsolutePosition, callout_position
from math import isnan


@sec_context
def HigherTfMain(self):
    return self.high[1], self.low[1], self.close[1]

@indicator('Pivot Points Standard', overlay_main_pane=True)
@param.str('higher_tf', default='Auto',
           options=['Auto', '1m', '3m', '5m', '15m', '30m', '45m',
                    '1h', '2h', '3h', '4h',
                    '1D', '1W', '1M', '12M'])
@param.bool('show_labels', default=True, title='Show Labels')
@param.bool('show_prices', default=True, title='Show Prices')
@param.bool('lookahead', default=True, title='Lookahead on history bars')
@param.int('levels_number', default=3, min=1, max=3, title='Levels Number')
class Main(MainContext):
    def __init__(self, higher_tf, lookahead, levels_number):
        chosen_higher_tf = TimeFrame.from_str('12M')  # default value
        if higher_tf == 'Auto':
            if self.time_frame <= TimeFrame.from_str('15m'):
                chosen_higher_tf = TimeFrame.from_str('1D')
            elif self.time_frame < TimeFrame.from_str('1D'):
                chosen_higher_tf = TimeFrame.from_str('1W')
            elif self.time_frame == TimeFrame.from_str('1D'):
                chosen_higher_tf = TimeFrame.from_str('1M')
            else:
                chosen_higher_tf = TimeFrame.from_str('12M')
        else:
            chosen_higher_tf = TimeFrame.from_str(higher_tf)
        self._prev_high, self._prev_low, self._prev_close = self.calc_on(HigherTfMain, time_frame=chosen_higher_tf, lookahead=lookahead)
        none_line: Optional[LineSegment] = None
        self._pivot_line = self.new_var(none_line)
        self._resistance_lines: list[Var[Optional[LineSegment]]] = []
        self._support_lines: list[Var[Optional[LineSegment]]] = []
        for _ in range(levels_number):
            self._resistance_lines.append(self.new_var(none_line))
            self._support_lines.append(self.new_var(none_line))

    def calc(self, show_labels, show_prices):
        pivot_level = MutSeriesF.new((self._prev_high[0] + self._prev_low[0] + self._prev_close[0]) / 3)
        if isnan(pivot_level[0]):
            return
        resistance_levels = [
            pivot_level[0] * 2 - self._prev_low[0],
            pivot_level[0] + (self._prev_high[0] - self._prev_low[0]),
            self._prev_high[0] + 2 * (pivot_level[0] - self._prev_low[0]),
        ]
        support_levels = [
            pivot_level[0] * 2 - self._prev_high[0],
            pivot_level[0] - (self._prev_high[0] - self._prev_low[0]),
            self._prev_low[0] - 2 * (self._prev_high[0] - pivot_level[0]),
        ]

        pivot_line = self._pivot_line.get()
        res_lines = self._resistance_lines
        sup_lines = self._support_lines
        if pivot_level[0] != pivot_level[1]:
            if pivot_line is not None:  # updating the previous lines if exist
                pivot_line.value().point_b.time = self.time[0]
                self.chart.draw(pivot_line.value())

                for res_line in res_lines:
                    res_line.get().value().point_b.time = self.time[0]
                    self.chart.draw(res_line.get().value())

                for sup_line in sup_lines:
                    sup_line.get().value().point_b.time = self.time[0]
                    self.chart.draw(sup_line.get().value())

            # creating new pivot line and label
            time_to = self.time[0] + (self.time[0] - self.time[1]) * 3
            new_pivot_line = LineSegment(
                AbsolutePosition(self.time[0], pivot_level[0]),
                AbsolutePosition(time_to, pivot_level[0]),
                line_width=1, color=color.GRAY,
            )
            self._pivot_line.set(new_pivot_line)
            self.chart.draw(self._pivot_line.get().value())
            if show_labels or show_prices:
                text = 'P ' if show_labels else ''
                text += ('(' + str(round(pivot_level[0], self.info.price_precision)) + ')') if show_prices else ''
                new_pivot_label = LabelAbs(
                    text,
                    AbsolutePosition(self.time[0], pivot_level[0]),
                    bg_color=color.TRANSPARENT,
                    text_color=color.rgba(187, 187, 187),
                    font_size=11,
                    callout_position=callout_position.TOP_LEFT,  # TODO: callout_position.LEFT
                )
                self.chart.draw(new_pivot_label)

            for i in range(len(res_lines)):  # creating new support and resistance lines and labels
                res_line = res_lines[i]
                sup_line = sup_lines[i]
                time_to = self.time[0] + (self.time[0] - self.time[1]) * 3
                new_resistance_line = LineSegment(
                    AbsolutePosition(self.time[0], resistance_levels[i]),
                    AbsolutePosition(time_to, resistance_levels[i]),
                    color=color.GRAY, line_width=1,
                )
                res_line.set(new_resistance_line)
                self.chart.draw(res_line.get().value())
                time_to = self.time[0] + (self.time[0] - self.time[1]) * 3
                new_support_line = LineSegment(
                    AbsolutePosition(self.time[0], support_levels[i]),
                    AbsolutePosition(time_to, support_levels[i]),
                    color=color.GRAY, line_width=1,
                )
                sup_line.set(new_support_line)
                self.chart.draw(sup_line.get().value())
                if show_labels or show_prices:
                    text = 'R' + str(i + 1) if show_labels else ''
                    text += ('(' + str(round(resistance_levels[i], self.info.price_precision)) + ')') if show_prices else ''
                    new_resistance_label = LabelAbs(
                        text,
                        AbsolutePosition(self.time[0], resistance_levels[i]),
                        bg_color=color.TRANSPARENT,
                        text_color=color.rgba(187, 187, 187),
                        font_size=11,
                        callout_position=callout_position.TOP_LEFT,  # TODO: callout_position.LEFT
                    )
                    self.chart.draw(new_resistance_label)

                    text = 'S' + str(i + 1) if show_labels else ''
                    text += ('(' + str(round(support_levels[i], self.info.price_precision)) + ')') if show_prices else ''
                    new_support_label = LabelAbs(
                        text,
                        AbsolutePosition(self.time[0], support_levels[i]),
                        bg_color=color.TRANSPARENT,
                        text_color=color.rgba(187, 187, 187),
                        font_size=11,
                        callout_position=callout_position.TOP_LEFT,  # TODO: callout_position.LEFT
                    )
                    self.chart.draw(new_support_label)
        else:  # the same levels, just updating the right points of previous lines
            if (pivot_line is not None) and (pivot_line.value().point_b.time != self.time[0]):
                pivot_line.value().point_b.time = self.time[0]
                self.chart.draw(pivot_line.value())
                for res_line in res_lines:
                    res_line.get().value().point_b.time = self.time[0]
                    self.chart.draw(res_line.get().value())
                for sup_line in sup_lines:
                    sup_line.get().value().point_b.time = self.time[0]
                    self.chart.draw(sup_line.get().value())
        return
```

## Price Oscillator

```py Price Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, level, color, plot
from indie.algorithms import Ema, Sma
from indie.math import divide


@indicator('PPO', format=format.PRICE)  # Price Oscillator
@param.int('short_len', default=10, min=1, title='Short Length')
@param.int('long_len', default=21, min=1, title='Long Length')
@param.source('src', default=source.CLOSE, title='Source')
@param.bool('exponential', default=False)
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.GREEN, title='OSC')
def Main(self, short_len, long_len, src, exponential):
    short, long = 0.0, 0.0
    if exponential:
        short = Ema.new(src, short_len)[0]
        long = Ema.new(src, long_len)[0]
    else:
        short = Sma.new(src, short_len)[0]
        long = Sma.new(src, long_len)[0]
    return 100 * divide(short - long, long)
```

## Price Volume Trend

```py Price Volume Trend theme={null}
# indie:lang_version = 5
from indie import indicator, format, plot, color, MutSeriesF
from indie.algorithms import CumSum, NanToZero, Change
from indie.math import divide


@indicator('PVT', format=format.VOLUME)  # Price Volume Trend
@plot.line(color=color.BLUE)
def Main(self):
    return CumSum.new(NanToZero.new(MutSeriesF.new(
        divide(Change.new(self.close)[0], self.close[1]) * self.volume[0])))[0]
```

## Rank Correlation Index

```py Rank Correlation Index theme={null}
# indie:lang_version = 5
from math import isnan, nan
from indie import indicator, format, param, source, plot, color, band


@indicator('RCI', format=format.PRICE, precision=2)  # Rank Correlation Index
@param.int('length', default=10, min=2, max=100, title='Length')
@param.source('source', default=source.CLOSE, title='Source')
@band(-80, 80, fill_color=color.BLUE(0.05), title='Band')
@plot.line(color=color.BLUE, title='RCI')
def Main(self, length, source):
    if isnan(source[length - 1]):
        return nan
    window: list[float] = []
    for k in range(length):
        window.append(source[k])
    n = float(length)
    sum_sq = 0.0
    for i in range(length):
        less = 0.0
        equal = 0.0
        value = window[i]
        for j in range(length):
            if window[j] < value:
                less += 1.0
            elif window[j] == value:
                equal += 1.0
        # Ascending price rank with ties averaged; the oldest bar has time rank 1.
        price_rank = less + (equal + 1.0) / 2.0
        d = price_rank - (n - float(i))
        sum_sq += d * d
    return (1.0 - 6.0 * sum_sq / (n * (n * n - 1.0))) * 100.0
```

## Rate Of Change

```py Rate Of Change theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, level, color, plot
from indie.algorithms import Roc


@indicator('ROC', format=format.PRICE)  # Rate Of Change
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.BLUE, title='ROC')
def Main(self, length, src):
    return Roc.new(src, length)[0]
```

## Relative Vigor Index

```py Relative Vigor Index theme={null}
# indie:lang_version = 5
from indie import algorithm, SeriesF, MutSeriesF, indicator, format, param, plot, color
from indie.algorithms import Sum
from indie.math import divide


@algorithm  # Symmetrically Weighted Moving Average
def Swma(self, src: SeriesF) -> SeriesF:
    return MutSeriesF.new(src[3] / 6 + src[2] / 3 + src[1] / 3 + src[0] / 6)


@indicator('RVGI', format=format.PRICE, precision=4)  # Relative Vigor Index
@param.int('length', default=10, min=1)
@param.int('offset', default=0, min=-500, max=500)
@plot.line(color=color.GREEN, title='RVGI')
@plot.line(color=color.RED, title='Signal')
def Main(self, length, offset):
    cl_op_sum = Sum.new(Swma.new(MutSeriesF.new(self.close[0] - self.open[0])), length)[0]
    hi_lo_sum = Sum.new(Swma.new(MutSeriesF.new(self.high[0] - self.low[0])), length)[0]
    rvi = divide(cl_op_sum, hi_lo_sum)
    sig = Swma.new(MutSeriesF.new(rvi))[0]
    return plot.Line(rvi, offset=offset), plot.Line(sig, offset=offset)
```

## Relative Volatility Index

```py Relative Volatility Index theme={null}
# indie:lang_version = 5
from math import nan
from indie import indicator, format, param, band, color, level, plot, MutSeriesF
from indie.algorithms import StdDev, Ema, Change, Bb, Ma
from indie.math import divide


@indicator('RVI', format=format.PRICE)  # Relative Volatility Index
@param.int('length', default=10, min=1)
@param.int('offset', default=0, min=-500, max=500)
@param.str('ma_type', default='SMA', title='MA Type', options=['SMA', 'Bollinger Bands', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'])
@param.int('ma_length', default=14, title='MA Length', min=1)
@param.float('bb_mult', default=2.0, title='BB StdDev', min=0.001, max=50)
@band(20, 80, line_color=color.GRAY, fill_color=color.PURPLE(0.1))
@level(50, line_color=color.GRAY(0.5))
@plot.line(color=color.YELLOW, title='RVI-based MA')
@plot.line(color=color.PURPLE, title='RVI')
@plot.line('bb_lower', color=color.GREEN, title='Lower Bollinger Band')
@plot.line('bb_upper', color=color.GREEN, title='Upper Bollinger Band')
@plot.fill('bb_lower', 'bb_upper', color=color.GREEN(0.1), title='Bollinger Bands Background Fill')
def Main(self, length, offset, ma_type, ma_length, bb_mult):
    dev = StdDev.new(self.close, length)[0]
    upper = Ema.new(MutSeriesF.new(0 if Change.new(self.close)[0] <= 0 else dev), 14)[0]
    lower = Ema.new(MutSeriesF.new(0 if Change.new(self.close)[0] > 0 else dev), 14)[0]
    rvi = MutSeriesF.new(100 * divide(upper, upper + lower))

    low_value, rvi_ma, high_value = nan, nan, nan
    if ma_type == 'Bollinger Bands':
        (bb_lower, bb_middle, bb_upper) = Bb.new(rvi, ma_length, bb_mult)
        low_value = bb_lower[0]
        rvi_ma = bb_middle[0]
        high_value = bb_upper[0]
    else:
        rvi_ma = Ma.new(rvi, ma_length, ma_type)[0]

    return (
        plot.Line(rvi_ma, offset=offset),
        plot.Line(rvi[0], offset=offset),
        low_value,
        high_value,
        plot.Fill(),
    )
```

## Relative Volume at Time

```py Relative Volume at Time theme={null}
# indie:lang_version = 5
from math import isnan
from indie import indicator, param, plot, color, level, line_style, MainContext, format, IndieError, TimeFrame
from indie.math import divide


@indicator('RVAT', format=format.PRICE, precision=2)  # Relative Volume at Time
@param.int('length', default=10, min=1, max=50, title='Sessions to average')
@param.str('mode', default='Cumulative', options=['Cumulative', 'Regular'], title='Calculation mode')
@param.float('threshold', default=1.0, min=0.0, step=0.1, title='Highlight level')
@level(1, line_color=color.GRAY, line_style=line_style.DASHED)
@plot.columns(title='Relative Volume')
class Main(MainContext):
    def __init__(self, length, mode, threshold):
        # History is kept per time of day: second and tick bars would make it too large and meaningless.
        if self.time_frame.unit == TimeFrame.from_str('1T').unit or self.time_frame.to_seconds() < 60:
            raise IndieError('Relative Volume at Time needs a time-based chart of 1 minute or longer')
        self._hist: dict[int, list[float]] = {}
        self._cum_mode = mode == 'Cumulative'
        self._length = length
        self._threshold = threshold
        self._day: int = -1
        self._cum_prev: float = 0.0
        self._has_pending: bool = False
        self._pending_key: int = 0
        self._pending_val: float = 0.0

    def calc(self):
        t = int(self.time[0])
        day = t // 86400
        key = t - day * 86400
        if self.is_new_bar:
            if self._has_pending:
                if self._pending_key in self._hist:
                    vals = self._hist[self._pending_key]
                    vals.append(self._pending_val)
                    if len(vals) > self._length:
                        vals.pop(0)
                else:
                    self._hist[self._pending_key] = [self._pending_val]
                if self._cum_mode:
                    self._cum_prev = self._pending_val
            if day != self._day:
                self._day = day
                self._cum_prev = 0.0
        vol = self.volume[0]
        if isnan(vol):
            vol = 0.0
        cur = vol
        if self._cum_mode:
            cur = self._cum_prev + vol
        self._has_pending = True
        self._pending_key = key
        self._pending_val = cur

        ratio = float('nan')
        if key in self._hist:
            past = self._hist[key]
            total = 0.0
            for v in past:
                total += v
            ratio = divide(cur, total / len(past))
        bar_color = color.TEAL if ratio >= self._threshold else color.GRAY(0.6)
        return plot.Columns(ratio, color=bar_color)
```

## Relative Strength Index

```py Relative Strength Index theme={null}
# indie:lang_version = 5
from math import nan
from indie import indicator, format, param, source, band, color, level, plot
from indie.algorithms import Rsi, Ma, StdDev


@indicator('RSI', format=format.PRICE)  # Relative Strength Index
@param.int('rsi_length', default=14, title='RSI Length', min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.str('ma_type', default='SMA', title='MA Type',
           options=['SMA', 'Bollinger Bands', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'])
@param.int('ma_length', default=14, title='MA Length', min=1)
@param.float('bb_mult', default=2.0, title='BB StdDev', min=0.001, max=50)
@band(30, 70, line_color=color.GRAY, fill_color=color.PURPLE(0.1))
@level(50, line_color=color.GRAY(0.5))
@plot.line(color=color.YELLOW, title='RSI-based MA')
@plot.line(color=color.PURPLE, title='RSI')
@plot.line('bb_lower', color=color.GREEN, title='RSI Lower Band')
@plot.line('bb_upper', color=color.GREEN, title='RSI Upper Band')
@plot.fill('bb_lower', 'bb_upper', color=color.GREEN(0.1), title='Bollinger Bands Background Fill')
def Main(self, rsi_length, src, ma_type, ma_length, bb_mult):
    rsi = Rsi.new(src, rsi_length)

    is_bb = ma_type == 'Bollinger Bands'

    ma_algorithm = 'SMA' if is_bb else ma_type
    rsi_ma = Ma.new(rsi, ma_length, ma_algorithm)

    std_dev = StdDev.new(rsi, ma_length)
    bb_lower = rsi_ma[0] - std_dev[0] * bb_mult if is_bb else nan
    bb_upper = rsi_ma[0] + std_dev[0] * bb_mult if is_bb else nan
    return rsi_ma[0], rsi[0], bb_lower, bb_upper, plot.Fill()
```

## Session Volume Profile

```py Session Volume Profile theme={null}
# indie:lang_version = 5
from math import ceil, inf, isnan, nan
from indie import MainContext, TimeFrame, color, format, indicator, line_style, param, plot, request_series
from indie.data import VolumeFootprintProfile, sources
from indie.data.sources import session_types
from indie.drawings import price_histogram_display_mode, secondary_histogram_display_mode


@indicator('SVP', overlay_main_pane=True, format=format.VOLUME)
@param.calc_time_frame('calc_tf', options={'Session': '1D'}, extended_hours_param='extended_hours')
@param.str('row_size', default='Auto', options=['Auto', 'Auto Merge', 'Manual'], title='Row Size')
@param.float('row_size_price', default=0.0, min=0.0, title='Price per Row (0 = minimum)')
@param.bool('extended_hours', default=False, title='Include pre/post market')
@plot.price_histogram_series(
    'vp', title='Volume Profile',
    layers=[plot.ProfileLayer('Buy', color.LIME(0.3), color.LIME(0.12), outline_color=color.LIME(0.5)),
            plot.ProfileLayer('Sell', color.RED(0.3), color.RED(0.12), outline_color=color.RED(0.5))],
    display_mode=price_histogram_display_mode.TOTAL, width_fraction=0.3,
    values_visible=True, totals_visible=True, value_color=color.GRAY,
    total_color=color.BLUE(0.35), total_color_outside_value_area=color.BLUE(0.14),
    total_outline_color=color.BLUE(0.5),
    value_area=0.7, poc_visible=True, poc_color=color.GRAY, poc_line_style=line_style.SOLID,
    secondary_histogram=plot.SecondaryHistogram(
        secondary_histogram_display_mode.DELTA, visible=True, width=0.1,
        layers=[plot.SecondaryHistogramLayer(color.GREEN(0.3), color.GREEN(0.12), outline_color=color.GREEN(0.5)),
                plot.SecondaryHistogramLayer(color.ORANGE(0.3), color.ORANGE(0.12),
                                             outline_color=color.ORANGE(0.5))]),
)
class Main(MainContext):
    def __init__(self, calc_tf, row_size, extended_hours):
        types = [session_types.MAIN_SESSION]
        if extended_hours:
            types = [session_types.MAIN_SESSION, session_types.PRE_MARKET, session_types.POST_MARKET]
        ticks = 0 if row_size == 'Auto' else 1
        self._profiles = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=types, row_size_ticks=ticks,
                                          row_size_scope='Request' if row_size == 'Auto' else 'Profile'),
            time_frame=TimeFrame.from_str('20m'))
        # Session bounds stay fixed while fine footprints arrive, including empty edge buckets.
        self._profile_bounds = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=types, row_size_ticks=0), time_frame=calc_tf)

    def calc(self, row_size, row_size_price):
        self._profiles.request_subperiods(1)
        profiles = self._profiles.subperiods()
        self._profile_bounds.request_subperiods(1)
        bounds = self._profile_bounds.subperiods()
        if profiles is None or bounds is None or len(profiles.value()) == 0 or len(bounds.value()) == 0:
            return plot.PriceHistogramSeries(nan)
        step = profiles.value()[0].row_size
        for profile in profiles.value():
            step = profile.common_row_size(step)
        if isnan(step):
            return plot.PriceHistogramSeries(nan)
        levels = max(1, ceil(round(row_size_price / step, 9))) if row_size == 'Manual' else 1
        low = inf
        high = -inf
        for footprint in profiles.value():
            for level in footprint.rows:
                low = min(low, level.price)
                high = max(high, level.price)
        if high >= low:
            levels = max(levels, ceil((high - low) / (2046 * step)))
        result = plot.PriceHistogramSeries(levels * step)
        result.time_to = float(bounds.value()[len(bounds.value()) - 1].profile_end_unix_seconds)
        result.merge_rows_on_zoom = row_size == 'Auto Merge'
        for contribution in profiles.value():
            for row in contribution.rows:
                result.add(row.price, [row.volume_buy, row.volume_sell])
        return result
```

## Simple Moving Average

```py Simple Moving Average theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Sma


@indicator('SMA', overlay_main_pane=True)  # Simple Moving Average
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.int('offset', default=0, min=-500, max=500, title='Offset')
@plot.line(color=color.BLUE)
def Main(self, length, src, offset):
    sma = Sma.new(src, length)
    return plot.Line(sma[0], offset=offset)
    # TODO: implement smoothing when display.none is supported
```

## Smart Money Concepts

```py Smart Money Concepts theme={null}
# indie:lang_version = 5
# Smart Money Concepts. Contract (inputs, outputs, confirmation model): docs/specs/smart-money-concepts.md.
#
# Sections are owned by work packages so that they can be edited independently:
# §0 constants · §1 Config + presets · §2 style and Draw · §3 records · §4 StructureEngine ·
# §5 ObEngine · §6 FvgEngine · §7 LiquidityEngine · §8 RangeEngine · §9 HtfEngine · §10 outputs · §11 Main.
#
# State rules: every mutable engine state lives in a Var holding a dataclass; it is mutated only while a
# bar is processed (closed bars and catch-up, see Main.calc). Records in state are never shared between
# two places of one state: Python deep copies keep aliasing on commit, the Go clone does not.
from dataclasses import dataclass
from datetime import datetime
from math import floor, isnan, nan
from indie import indicator, param, plot, color, line_style, sec_context, MainContext, SecContext, Context, Var, \
    Optional, Color, SeriesF, TimeFrame, time_frame_unit
from indie.drawings import LineSegment, LabelAbs, Rectangle, AbsolutePosition, Chart, callout_position, extend_type
from indie.algorithms import Atr, PivotHighLow


# §0 header, imports, constants ------------------------------------------------------------------------------

G_GEN = 'General'
G_MS = 'Market structure'
G_OB = 'Order blocks'
G_FVG = 'Fair value gaps'
G_LIQ = 'Liquidity'
G_PD = 'Premium / discount'
G_HTF = 'Key levels'
G_STY = 'Style'
G_ALR = 'Alerts'

# show_if of the inputs a preset sets (spec "Presets"): the Settings dialog shows them only for Preset = Custom.
CUSTOM = 'gen_preset == Custom'
ALR_CUSTOM = 'alr_any_events == Custom'

BULL = 1
BEAR = -1

L_INT = 0
L_SWING = 1

K_BOS = 1
K_CHOCH = 2
K_CHOCH_PLUS = 3

SRC_PIVOT = 0
SRC_BREAK = 1

ST_ACTIVE = 0
ST_MITIGATED = 1
ST_BREAKER = 2
ST_FILLED = 3
ST_DONE = 4
ST_INVERSE = 5
ST_PIERCED = 6

POOL_EQ = 0
POOL_SWING = 1
POOL_HTF = 2

A_ORIGIN = 0
A_CONFIRM = 1
A_GHOST = 2

TEXT_OFF = 0
TEXT_SHORT = 1
TEXT_FULL = 2

# Event slots of BarEvents.bull / BarEvents.bear, one per alert event output (§10).
# For liquidity and zones "bull" is the bullish side: equal lows, sell-side sweep, discount.
E_INT_BOS = 0
E_INT_CHOCH = 1
E_SWING_BOS = 2
E_SWING_CHOCH = 3
E_MSS = 4
E_OB_NEW = 5
E_OB_ENTER = 6
E_OB_MITIGATED = 7
E_OB_BROKEN = 8
E_FVG_NEW = 9
E_FVG_ENTER = 10
E_FVG_FILLED = 11
E_IFVG = 12
E_EQ = 13
E_SWEEP = 14
E_PD = 15
E_COUNT = 16

# Deepest bar offset any engine reads (leg scans); registered by dummy reads for the Go series trim.
MAX_LOOKBACK = 1000
# Drawing changes allowed per bar update before ops are deferred; the runner's hard limit is 100.
DRAW_BUDGET = 90
# A realtime calc's own share: a key-level update after the closed update recalculates the bar, and the runner counts
# the rollback of the first calc's changes plus the re-run's, so each may use only half (Draw).
DRAW_BUDGET_RT = 45
# Present mode draws nothing in history until this many bars' worth of time before the last bar; the drawings
# alive then are drawn at once, spread over a few bars by the budget (Main.calc).
TAIL_BARS = 500
# How far point B of a ray extended right lies after its start (400 days, in seconds); see ray_end.
RAY_SPAN = 34560000.0
SWING_RING = 4
POOL_CAP = 10


# §1 Config dataclass + apply_preset() ---------------------------------------------------------------------

class Config:
    # The defaults are the Standard preset, which is also what Custom starts from (the input defaults match).
    def __init__(self):
        self.preset = 'Standard'
        self.history = False
        self.anchoring = A_ORIGIN
        self.strict = False
        self.atr_len = 14

        self.ms_int_show = False
        self.ms_int_left = 5
        self.ms_int_right = 5
        self.ms_int_filter = 'All'
        self.ms_int_hide_at_swing = True
        self.ms_swing_show = True
        self.ms_swing_left = 50
        self.ms_swing_right = 10
        self.ms_swing_filter = 'All'
        self.ms_confirm_close = True
        self.ms_break_buffer_atr = 0.0
        self.ms_mss_disp_atr = 1.0
        self.ms_choch_plus = True
        self.ms_swing_labels = False
        self.ms_strong_weak = True
        self.ms_max_events = 3
        self.ms_candle_color = 'Swing'

        self.ob_int_show = True
        self.ob_int_last = 5
        self.ob_swing_show = True
        self.ob_swing_last = 5
        self.ob_max_dist_atr = 8.0
        self.ob_leg_extreme = False
        self.ob_require_displacement = False
        self.ob_mitigation = 'Wick'
        self.ob_mitigated_action = 'Keep'
        self.ob_invalidation_close = True
        self.ob_breakers = False
        self.ob_hide_older = True
        self.ob_show_mid = False

        self.fvg_show = True
        self.fvg_threshold_atr = 0.5
        self.fvg_last = 2
        self.fvg_fill = 'Wick (full)'
        self.fvg_shrink = True
        self.fvg_ce = False
        self.fvg_ifvg = False

        self.liq_eq_show = False
        self.liq_eq_len = 3
        self.liq_eq_tol_atr = 0.1
        self.liq_eq_min_touches = 2
        self.liq_sweeps_show = False
        self.liq_sweep_window = 0
        self.liq_sweep_eq = True
        self.liq_sweep_swing = True
        self.liq_sweep_htf = True

        self.pd_show = False
        self.pd_eq_band_pct = 0.0

        self.htf_daily = True
        self.htf_weekly = False
        self.htf_monthly = False
        self.htf_style = 'Dashed'

        self.label_size = 'Small'
        self.label_text = TEXT_SHORT
        # Inputs: bull, bear (always shown), neutral and the FVG pair (Custom); the rest is derived in finish_config.
        self.bull_color = color.rgba(8, 153, 129, 1.0)
        self.bear_color = color.rgba(242, 54, 69, 1.0)
        self.neutral_color = color.rgba(128, 128, 128, 1.0)
        self.fvg_bull_color = color.rgba(0, 188, 212, 0.25)
        self.fvg_bear_color = color.rgba(233, 30, 99, 0.25)
        self.int_bull_color = color.rgba(8, 153, 129, 0.7)
        self.int_bear_color = color.rgba(242, 54, 69, 0.7)
        self.ob_bull_color = color.rgba(8, 153, 129, 0.12)
        self.ob_bear_color = color.rgba(242, 54, 69, 0.12)
        self.ob_mitigated_color = color.rgba(128, 128, 128, 0.1)
        self.breaker_bull_color = color.rgba(8, 153, 129, 0.06)
        self.breaker_bear_color = color.rgba(242, 54, 69, 0.06)
        self.ifvg_bull_color = color.rgba(0, 188, 212, 0.1)
        self.ifvg_bear_color = color.rgba(233, 30, 99, 0.1)
        self.liq_bsl_color = color.rgba(242, 54, 69, 0.9)
        self.liq_ssl_color = color.rgba(8, 153, 129, 0.9)
        self.pd_premium_color = color.rgba(242, 54, 69, 0.06)
        self.pd_discount_color = color.rgba(8, 153, 129, 0.06)
        self.pd_eq_color = color.rgba(128, 128, 128, 0.6)
        self.htf_color = color.rgba(128, 128, 128, 0.9)
        self.text_color = color.rgba(128, 128, 128, 1.0)

        self.alr_any_direction = 'Both'
        # Whether internal BOS / CHoCH count for alert_any's BOS and CHoCH (families and Custom): off under Standard
        # and Structure, on under ICT Strict, Scalper and Full, an input under Custom. Never a show toggle.
        self.alr_any_internal = False
        self.alr_any_bos = True
        self.alr_any_choch = True
        self.alr_any_ob_new = False
        self.alr_any_ob_enter = True
        self.alr_any_ob_mitigated = False
        self.alr_any_ob_broken = False
        self.alr_any_fvg_new = False
        self.alr_any_fvg_enter = True
        self.alr_any_fvg_filled = False
        self.alr_any_ifvg = False
        self.alr_any_eq = False
        self.alr_any_sweep = False
        self.alr_any_pd = False

        # Derived in finish() and pre_calc.
        self.font = 12
        self.font_int = 11
        self.tick = 0.0
        self.price_precision = 2


def apply_preset(cfg: Config, preset: str) -> None:
    # A preset other than Custom sets every input the dialog hides behind Custom (show_if=CUSTOM); Main never
    # reads the user's values of those inputs then. Config() is Standard; the other presets start from it.
    # The show toggles only decide what is drawn: every feature is detected and feeds the alert and data outputs
    # under every preset, so each preset also sets the detection inputs of the features it doesn't draw.
    if preset == 'Structure':
        # Draws structure only: swing BOS / CHoCH, strong / weak high and low, previous day high / low.
        cfg.strict = False
        set_internal(cfg, False, 5, 5)
        set_swing(cfg, True, 50, 10)
        cfg.ms_confirm_close = True
        cfg.ms_mss_disp_atr = 1.0
        cfg.ms_swing_labels = False
        cfg.ms_strong_weak = True
        cfg.ms_max_events = 3
        set_ob(cfg, False, 5, False, 5, 8.0)
        set_ob_rules(cfg, False, False, 'Wick', True, False)
        set_fvg(cfg, False, 0.5, 2, 'Wick (full)', False)
        set_eq(cfg, False, 3, 0.1)
        set_sweeps(cfg, False, 0)
        cfg.pd_show = False
        set_htf(cfg, True, False, False)
    elif preset == 'ICT Strict':
        set_classic(cfg)
        cfg.strict = True
        set_internal(cfg, True, 5, 5)
        cfg.alr_any_internal = True
        set_swing(cfg, True, 50, 10)
        cfg.ms_confirm_close = True
        cfg.ms_mss_disp_atr = 1.0
        cfg.ms_swing_labels = True
        cfg.ms_strong_weak = True
        cfg.ms_max_events = 5
        set_ob(cfg, True, 3, True, 3, 0.0)
        set_ob_rules(cfg, False, True, '50%', True, True)
        set_fvg(cfg, True, 0.25, 5, 'CE (50%)', True)
        set_eq(cfg, True, 3, 0.1)
        set_sweeps(cfg, True, 1)
        cfg.pd_show = True
        set_htf(cfg, True, True, False)
    elif preset == 'Scalper':
        set_classic(cfg)
        cfg.strict = False
        set_internal(cfg, True, 3, 3)
        cfg.alr_any_internal = True
        set_swing(cfg, True, 20, 5)
        # Wick breaks: on low timeframes waiting for the close lags the move.
        cfg.ms_confirm_close = False
        cfg.ms_mss_disp_atr = 0.8
        cfg.ms_swing_labels = False
        cfg.ms_strong_weak = False
        cfg.ms_max_events = 5
        set_ob(cfg, True, 5, True, 5, 8.0)
        set_ob_rules(cfg, True, False, 'Wick', False, False)
        set_fvg(cfg, True, 0.1, 5, 'Wick (full)', False)
        set_eq(cfg, True, 2, 0.15)
        set_sweeps(cfg, True, 0)
        cfg.pd_show = False
        set_htf(cfg, True, False, False)
    elif preset == 'Full':
        set_classic(cfg)
        cfg.strict = False
        set_internal(cfg, True, 5, 5)
        cfg.alr_any_internal = True
        set_swing(cfg, True, 50, 10)
        cfg.ms_confirm_close = True
        cfg.ms_mss_disp_atr = 1.0
        cfg.ms_swing_labels = True
        cfg.ms_strong_weak = True
        cfg.ms_max_events = 10
        set_ob(cfg, True, 5, True, 5, 0.0)
        set_ob_rules(cfg, False, False, 'Wick', True, True)
        set_fvg(cfg, True, 0.25, 10, 'Wick (full)', True)
        set_eq(cfg, True, 3, 0.1)
        set_sweeps(cfg, True, 1)
        cfg.pd_show = True
        set_htf(cfg, True, True, True)


def set_classic(cfg: Config) -> None:
    # ICT Strict, Scalper and Full keep mitigated order blocks (grey) and the FVG CE line, as before Standard.
    cfg.ob_mitigated_action = 'Recolor'
    cfg.fvg_ce = True


def set_alert_events(cfg: Config, events: str) -> None:
    # The event families of the any-event alert; 'Custom' keeps the per-event inputs. Whether BOS / CHoCH include
    # the internal layer is cfg.alr_any_internal (preset or input), the same for families and Custom.
    if events == 'Custom':
        return
    structure = events == 'Structure breaks + zone entry' or events == 'Structure breaks' or events == 'All events'
    entry = events == 'Structure breaks + zone entry' or events == 'Zone entry' or events == 'All events'
    liquidity = events == 'Liquidity' or events == 'All events'
    every = events == 'All events'
    cfg.alr_any_bos = structure
    cfg.alr_any_choch = structure
    cfg.alr_any_ob_enter = entry
    cfg.alr_any_fvg_enter = entry
    cfg.alr_any_eq = liquidity
    cfg.alr_any_sweep = liquidity
    cfg.alr_any_ob_new = every
    cfg.alr_any_ob_mitigated = every
    cfg.alr_any_ob_broken = every
    cfg.alr_any_fvg_new = every
    cfg.alr_any_fvg_filled = every
    cfg.alr_any_ifvg = every
    cfg.alr_any_pd = every


def set_internal(cfg: Config, show: bool, left: int, right: int) -> None:
    cfg.ms_int_show = show
    cfg.ms_int_left = left
    cfg.ms_int_right = right


def set_swing(cfg: Config, show: bool, left: int, right: int) -> None:
    cfg.ms_swing_show = show
    cfg.ms_swing_left = left
    cfg.ms_swing_right = right


def set_ob(cfg: Config, int_show: bool, int_last: int, swing_show: bool, swing_last: int, max_dist_atr: float) -> None:
    # max_dist_atr > 0: the last N per layer are candidates, the nearest OB_NEAR per side are drawn (ObEngine._select).
    cfg.ob_int_show = int_show
    cfg.ob_int_last = int_last
    cfg.ob_swing_show = swing_show
    cfg.ob_swing_last = swing_last
    cfg.ob_max_dist_atr = max_dist_atr


def set_ob_rules(cfg: Config, leg_extreme: bool, require_displacement: bool, mitigation: str,
                 invalidation_close: bool, breakers: bool) -> None:
    cfg.ob_leg_extreme = leg_extreme
    cfg.ob_require_displacement = require_displacement
    cfg.ob_mitigation = mitigation
    cfg.ob_invalidation_close = invalidation_close
    cfg.ob_breakers = breakers


def set_fvg(cfg: Config, show: bool, threshold_atr: float, last: int, fill: str, ifvg: bool) -> None:
    cfg.fvg_show = show
    cfg.fvg_threshold_atr = threshold_atr
    cfg.fvg_last = last
    cfg.fvg_fill = fill
    cfg.fvg_ifvg = ifvg


def set_eq(cfg: Config, show: bool, length: int, tol_atr: float) -> None:
    cfg.liq_eq_show = show
    cfg.liq_eq_len = length
    cfg.liq_eq_tol_atr = tol_atr


def set_sweeps(cfg: Config, show: bool, window: int) -> None:
    cfg.liq_sweeps_show = show
    cfg.liq_sweep_window = window


def set_htf(cfg: Config, daily: bool, weekly: bool, monthly: bool) -> None:
    cfg.htf_daily = daily
    cfg.htf_weekly = weekly
    cfg.htf_monthly = monthly


def timeframe_seconds(tf: TimeFrame) -> float:
    # Length of a bar in seconds, as float: an int product overflows int32 in Go wasm for 2M or 8W and up.
    # 0 for tick charts (Indie has no TICK unit; py to_seconds() gives count there, Go gives 0), which never hold.
    c = float(tf.count)
    if tf.unit == time_frame_unit.SECOND:
        return c
    if tf.unit == time_frame_unit.MINUTE:
        return c * 60.0
    if tf.unit == time_frame_unit.HOUR:
        return c * 3600.0
    if tf.unit == time_frame_unit.DAY:
        return c * 86400.0
    if tf.unit == time_frame_unit.WEEK:
        return c * 604800.0
    if tf.unit == time_frame_unit.MONTH:
        return c * 2592000.0
    return 0.0


def ray_end(start: float) -> float:
    # Point B of a horizontal ray extended right that starts at `start`: it only gives the direction. The chart
    # puts a time on the bar at or before it (a time past the last bar on the last bar), and a segment whose two
    # points share a bar has no direction, so the extended line draws nothing. One bar later is not enough: after
    # a session or weekend break (a Friday daily bar) that time falls back on the start's bar. RAY_SPAN passes any
    # break and is longer than one bar of every timeframe up to 12M, so B is on the next bar the chart has, or on
    # its last bar. It depends on the start alone: the final chart doesn't depend on the bar that last moved the
    # ray, and realtime ends with the same chart as history.
    return start + RAY_SPAN


def finish_config(cfg: Config) -> None:
    # Label font in px (Label font_size takes any int): Tiny 10, Small 12, Normal 14, Large 16. Internal
    # structure and OB / FVG labels are 1 px smaller.
    cfg.font = 12
    if cfg.label_size == 'Tiny':
        cfg.font = 10
    elif cfg.label_size == 'Normal':
        cfg.font = 14
    elif cfg.label_size == 'Large':
        cfg.font = 16
    cfg.font_int = cfg.font - 1
    # Derived colors: color(alpha) replaces the alpha of the input color.
    cfg.int_bull_color = cfg.bull_color(0.7)
    cfg.int_bear_color = cfg.bear_color(0.7)
    cfg.ob_bull_color = cfg.bull_color(0.12)
    cfg.ob_bear_color = cfg.bear_color(0.12)
    cfg.breaker_bull_color = cfg.bull_color(0.06)
    cfg.breaker_bear_color = cfg.bear_color(0.06)
    cfg.ifvg_bull_color = cfg.fvg_bull_color(0.1)
    cfg.ifvg_bear_color = cfg.fvg_bear_color(0.1)
    cfg.liq_bsl_color = cfg.bear_color(0.9)
    cfg.liq_ssl_color = cfg.bull_color(0.9)
    cfg.pd_premium_color = cfg.bear_color(0.06)
    cfg.pd_discount_color = cfg.bull_color(0.06)
    cfg.ob_mitigated_color = cfg.neutral_color(0.1)
    cfg.pd_eq_color = cfg.neutral_color(0.6)
    cfg.htf_color = cfg.neutral_color(0.9)
    cfg.text_color = cfg.neutral_color


# §2 Style: font size, colors, Draw (budget + deferred queue) -----------------------------------------------

OP_LINE_DRAW = 0
OP_LINE_ERASE = 1
OP_LABEL_DRAW = 2
OP_LABEL_ERASE = 3
OP_RECT_DRAW = 4
OP_RECT_ERASE = 5


@dataclass
class DrawQueue:
    ops: list[int]
    lines: list[LineSegment]
    labels: list[LabelAbs]
    rects: list[Rectangle]


def new_draw_queue() -> DrawQueue:
    ops: list[int] = []
    lines: list[LineSegment] = []
    labels: list[LabelAbs] = []
    rects: list[Rectangle] = []
    return DrawQueue(ops, lines, labels, rects)


class Draw:
    # Every chart change goes through here. Past DRAW_BUDGET changes in one bar update the op is queued and
    # replayed by flush() on the next processed bar; once anything is queued, later ops queue too, so the
    # chart sees every object's ops in their original order. new_line / new_label / new_rect draw an object
    # for the first time.
    #
    # The runner's limit (100) counts every change since the bar's last commit, not just this calc's. The
    # same bar is calculated again on the next tick and when a key-level bar arrives after it:
    # - in realtime the runner rolls the chart back first and the rollback commands count;
    # - in history it doesn't roll the chart back, so the earlier calcs' changes still count, and the objects
    #   they created are still drawn although the state that held them was rolled back.
    # begin() carries those changes into the budget and erases those orphans. In realtime a calc also keeps to
    # DRAW_BUDGET_RT: the re-run repeats the closed calc's ops after rolling back as many, so with a full budget
    # it would queue them again, and with a key-level update after every closed update the queue never drains.
    # All fields here are per calc, never state: they describe the runner's chart, which a state rollback
    # doesn't touch.
    def __init__(self, chart: Chart, queue: Var[DrawQueue], history: bool):
        self._chart = chart
        self._queue = queue
        self._history = history
        self.count = 0
        self._carried = 0
        self._bar = -1
        # True when this calc repeats the bar of the previous one, i.e. it runs on rolled-back state (Main.calc).
        self.same_bar = False
        self._realtime = False
        self._queue_owned = False
        self._new_lines: list[LineSegment] = []
        self._new_labels: list[LabelAbs] = []
        self._new_rects: list[Rectangle] = []
        # History before the tail (Main.calc): the ops on drawings that can still change are dropped. The engines
        # keep those drawings in their state and Main.materialize() draws them when the tail starts. Present mode
        # erases them again in most cases; History mode draws each once, when it is final (final_*). Drawings that
        # never change go through keep_* and are drawn at once in History mode.
        self.hold = False

    def begin(self, bar: int, history: bool) -> None:
        self.hold = False
        if bar == self._bar:
            if history:
                # Erasing an object drawn since the commit drops its draw command; after a realtime rollback
                # the objects are no longer drawn and erase is a no-op.
                for obj in self._new_lines:
                    self._chart.erase(obj)
                for obj in self._new_labels:
                    self._chart.erase(obj)
                for obj in self._new_rects:
                    self._chart.erase(obj)
                self._carried += self.count
            else:
                self._carried = self.count
        else:
            self._carried = 0
        self.same_bar = bar == self._bar
        self._realtime = not history
        self._queue_owned = False
        self._bar = bar
        self.count = 0
        # Fresh lists only when used: every allocation per bar scatters the heap (spec "Memory").
        if len(self._new_lines) > 0:
            new_lines: list[LineSegment] = []
            self._new_lines = new_lines
        if len(self._new_labels) > 0:
            new_labels: list[LabelAbs] = []
            self._new_labels = new_labels
        if len(self._new_rects) > 0:
            new_rects: list[Rectangle] = []
            self._new_rects = new_rects

    def _direct(self) -> bool:
        return self._carried + self.count < DRAW_BUDGET and not (self._realtime and self.count >= DRAW_BUDGET_RT) \
            and len(self._queue.get().ops) == 0

    def new_line(self, obj: LineSegment) -> None:
        if self.hold:
            return
        self._first_line(obj)

    def _first_line(self, obj: LineSegment) -> None:
        if self._direct():
            self._new_lines.append(obj)
        self._put_line(obj)

    def new_label(self, obj: LabelAbs) -> None:
        if self.hold:
            return
        self._first_label(obj)

    def _first_label(self, obj: LabelAbs) -> None:
        if self._direct():
            self._new_labels.append(obj)
        self._put_label(obj)

    def new_rect(self, obj: Rectangle) -> None:
        if self.hold:
            return
        self._first_rect(obj)

    def _first_rect(self, obj: Rectangle) -> None:
        if self._direct():
            self._new_rects.append(obj)
        self._put_rect(obj)

    def show_line(self, obj: LineSegment, created: bool) -> None:
        if created:
            self.new_line(obj)
        else:
            self.line(obj)

    def show_label(self, obj: LabelAbs, created: bool) -> None:
        if created:
            self.new_label(obj)
        else:
            self.label(obj)

    def show_rect(self, obj: Rectangle, created: bool) -> None:
        if created:
            self.new_rect(obj)
        else:
            self.rect(obj)

    def keep_line(self, obj: LineSegment) -> None:
        # A drawing that never changes and that History mode doesn't keep in state.
        if not self.hold or self._history:
            self._first_line(obj)

    def keep_label(self, obj: LabelAbs) -> None:
        if not self.hold or self._history:
            self._first_label(obj)

    def final_line(self, obj: LineSegment, changed: bool) -> None:
        # History mode: the drawing leaves the state with its last look. Held so far, it is drawn now.
        if self.hold:
            self._first_line(obj)
        elif changed:
            self._put_line(obj)

    def final_label(self, obj: LabelAbs, changed: bool) -> None:
        if self.hold:
            self._first_label(obj)
        elif changed:
            self._put_label(obj)

    def final_rect(self, obj: Rectangle, changed: bool) -> None:
        if self.hold:
            self._first_rect(obj)
        elif changed:
            self._put_rect(obj)

    def line(self, obj: LineSegment) -> None:
        if self.hold:
            return
        self._put_line(obj)

    def _put_line(self, obj: LineSegment) -> None:
        if self._direct():
            self._chart.draw(obj)
            self.count += 1
        else:
            q = self._writable_queue()
            q.ops.append(OP_LINE_DRAW)
            q.lines.append(obj)

    def erase_line(self, obj: LineSegment) -> None:
        if self.hold:
            return
        if self._direct():
            self._chart.erase(obj)
            self.count += 1
        else:
            q = self._writable_queue()
            q.ops.append(OP_LINE_ERASE)
            q.lines.append(obj)

    def label(self, obj: LabelAbs) -> None:
        if self.hold:
            return
        self._put_label(obj)

    def _put_label(self, obj: LabelAbs) -> None:
        if self._direct():
            self._chart.draw(obj)
            self.count += 1
        else:
            q = self._writable_queue()
            q.ops.append(OP_LABEL_DRAW)
            q.labels.append(obj)

    def erase_label(self, obj: LabelAbs) -> None:
        if self.hold:
            return
        if self._direct():
            self._chart.erase(obj)
            self.count += 1
        else:
            q = self._writable_queue()
            q.ops.append(OP_LABEL_ERASE)
            q.labels.append(obj)

    def rect(self, obj: Rectangle) -> None:
        if self.hold:
            return
        self._put_rect(obj)

    def _put_rect(self, obj: Rectangle) -> None:
        if self._direct():
            self._chart.draw(obj)
            self.count += 1
        else:
            q = self._writable_queue()
            q.ops.append(OP_RECT_DRAW)
            q.rects.append(obj)

    def erase_rect(self, obj: Rectangle) -> None:
        if self.hold:
            return
        if self._direct():
            self._chart.erase(obj)
            self.count += 1
        else:
            q = self._writable_queue()
            q.ops.append(OP_RECT_ERASE)
            q.rects.append(obj)

    def _writable_queue(self) -> DrawQueue:
        # After a rollback the queue's lists are the committed ones (see Main.own_state): copied before the first
        # append of a calc on the same bar.
        q = self._queue.get()
        if self.same_bar and not self._queue_owned:
            ops: list[int] = []
            for op in q.ops:
                ops.append(op)
            lines: list[LineSegment] = []
            for ln in q.lines:
                lines.append(ln)
            labels: list[LabelAbs] = []
            for lbl in q.labels:
                labels.append(lbl)
            rects: list[Rectangle] = []
            for r in q.rects:
                rects.append(r)
            q.ops = ops
            q.lines = lines
            q.labels = labels
            q.rects = rects
            self._queue_owned = True
        return q

    def pending(self) -> int:
        return len(self._queue.get().ops)

    def flush(self) -> None:
        q = self._queue.get()
        if len(q.ops) == 0:
            return
        done = 0
        n_lines = 0
        n_labels = 0
        n_rects = 0
        while done < len(q.ops) and self._carried + self.count < DRAW_BUDGET and \
                not (self._realtime and self.count >= DRAW_BUDGET_RT):
            op = q.ops[done]
            if op == OP_LINE_DRAW:
                self._chart.draw(q.lines[n_lines])
                n_lines += 1
            elif op == OP_LINE_ERASE:
                self._chart.erase(q.lines[n_lines])
                n_lines += 1
            elif op == OP_LABEL_DRAW:
                self._chart.draw(q.labels[n_labels])
                n_labels += 1
            elif op == OP_LABEL_ERASE:
                self._chart.erase(q.labels[n_labels])
                n_labels += 1
            elif op == OP_RECT_DRAW:
                self._chart.draw(q.rects[n_rects])
                n_rects += 1
            else:
                self._chart.erase(q.rects[n_rects])
                n_rects += 1
            self.count += 1
            done += 1
        ops: list[int] = []
        for i in range(done, len(q.ops)):
            ops.append(q.ops[i])
        lines: list[LineSegment] = []
        for i in range(n_lines, len(q.lines)):
            lines.append(q.lines[i])
        labels: list[LabelAbs] = []
        for i in range(n_labels, len(q.labels)):
            labels.append(q.labels[i])
        rects: list[Rectangle] = []
        for i in range(n_rects, len(q.rects)):
            rects.append(q.rects[i])
        q.ops = ops
        q.lines = lines
        q.labels = labels
        q.rects = rects


def text_for(cfg: Config, full: str, short: str) -> str:
    if cfg.label_text == TEXT_SHORT:
        return short
    return full


def new_text_label(text: str, time: float, price: float, text_color: Color, size: int, above: bool) -> LabelAbs:
    return LabelAbs(text, AbsolutePosition(time, price), font_size=size, text_color=text_color,
                    bg_color=color.TRANSPARENT,
                    callout_position=callout_position.TOP_RIGHT if above else callout_position.BOTTOM_RIGHT)


# §3 Records: Level, Swing, Leg, StructEvent, Ob, Fvg, Pool, HtfLevel, BarEvents -----------------------------

@dataclass
class Level:
    price: float
    anchor_bar: int
    anchor_time: float
    line: Optional[LineSegment]
    label: Optional[LabelAbs]


@dataclass
class Swing:
    price: float
    anchor_bar: int
    anchor_time: float
    confirmed_bar: int
    confirmed_time: float
    broken: bool
    source: int


@dataclass
class Leg:
    # The leg between the broken swing and the break bar: its extreme, the order block candle chosen by
    # ob_type, whether it displaced and whether it swept the previous opposite swing.
    extreme: float
    extreme_bar: int
    extreme_time: float
    ob_top: float
    ob_bottom: float
    ob_bar: int
    ob_time: float
    ob_volume: float
    displaced: bool
    swept: bool


@dataclass
class StructEvent:
    layer: int
    direction: int
    kind: int
    mss: bool
    level: float
    from_anchor_bar: int
    from_anchor_time: float
    from_confirmed_time: float
    bar: int
    time: float
    leg: Leg


@dataclass
class Ob:
    direction: int
    layer: int
    top: float
    bottom: float
    mid: float
    anchor_bar: int
    anchor_time: float
    confirmed_bar: int
    confirmed_time: float
    swept: bool
    displaced: bool
    volume: float
    touches: int
    inside: bool
    state: int
    # An internal block re-picked by a swing break (ObEngine._promote).
    promoted: bool
    box: Optional[Rectangle]
    label: Optional[LabelAbs]
    ghost: Optional[LineSegment]


@dataclass
class Fvg:
    direction: int
    top: float
    bottom: float
    ce: float
    filled_to: float
    anchor_bar: int
    anchor_time: float
    confirmed_bar: int
    confirmed_time: float
    entered: bool
    state: int
    box: Optional[Rectangle]
    ce_line: Optional[LineSegment]
    label: Optional[LabelAbs]
    ghost: Optional[LineSegment]


@dataclass
class Pool:
    side: int
    level: float
    touches: int
    first_anchor_time: float
    last_anchor_time: float
    confirmed_bar: int
    source: int
    state: int
    pierced_bar: int
    line: Optional[LineSegment]
    label: Optional[LabelAbs]
    ghost: Optional[LineSegment]


@dataclass
class HtfLevel:
    name: str
    is_high: bool
    price: float
    period_start: float
    start_time: float
    line: Optional[LineSegment]
    label: Optional[LabelAbs]
    # The current period's high (low) so far on the chart's bars and the time of the first bar that reached it
    # (HtfEngine._track), the bar index of the period's first chart bar, and whether that is the period's start.
    run_start: float
    run_extreme: float
    run_time: float
    run_bar: int
    run_full: bool


@dataclass
class BarEvents:
    # Rebuilt on every calc; collects the events of every bar processed in it (catch-up included).
    bull: list[bool]
    bear: list[bool]
    breaks: list[StructEvent]
    new_swing_hi: Optional[Swing]
    new_swing_lo: Optional[Swing]


def new_bar_events() -> BarEvents:
    bull: list[bool] = []
    bear: list[bool] = []
    for _ in range(E_COUNT):
        bull.append(False)
        bear.append(False)
    breaks: list[StructEvent] = []
    no_swing: Optional[Swing] = None
    return BarEvents(bull, bear, breaks, no_swing, no_swing)


def begin_bar(ev: BarEvents) -> None:
    # Per-bar parts are reset before each processed bar; the event slots accumulate over the update.
    if len(ev.breaks) > 0:
        breaks: list[StructEvent] = []
        ev.breaks = breaks
    no_swing: Optional[Swing] = None
    ev.new_swing_hi = no_swing
    ev.new_swing_lo = no_swing


def mark(ev: BarEvents, slot: int, direction: int) -> None:
    if direction == BULL:
        ev.bull[slot] = True
    else:
        ev.bear[slot] = True


@dataclass
class DataOut:
    # Data outputs; they change only on processed bars, so unclosed updates re-emit the held values.
    trend_swing: float
    trend_internal: float
    range_top: float
    range_bottom: float
    pd_position: float
    ob_bull_top: float
    ob_bear_bottom: float
    fvg_bull_top: float
    fvg_bear_bottom: float
    liq_bsl: float
    liq_ssl: float
    pdh: float
    pdl: float
    pwh: float
    pwl: float
    pmh: float
    pml: float


def new_data_out() -> DataOut:
    return DataOut(0.0, 0.0, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan)


def copy_swing(s: Swing) -> Swing:
    return Swing(s.price, s.anchor_bar, s.anchor_time, s.confirmed_bar, s.confirmed_time, s.broken, s.source)


# §4 StructureEngine -----------------------------------------------------------------------------------------

@dataclass
class StructDraw:
    line: LineSegment
    label: Optional[LabelAbs]
    ghost: Optional[LineSegment]


@dataclass
class LayerState:
    trend: int
    hi: Optional[Swing]
    lo: Optional[Swing]
    # Newest last; copies of the swings, never the hi / lo records themselves.
    hi_ring: list[Swing]
    lo_ring: list[Swing]
    # Present mode handles: structure events and swing labels still on the chart.
    draws: list[StructDraw]
    swing_labels: list[LabelAbs]


@dataclass
class StructState:
    internal: LayerState
    swing: LayerState


def new_layer_state() -> LayerState:
    no_swing: Optional[Swing] = None
    hi_ring: list[Swing] = []
    lo_ring: list[Swing] = []
    draws: list[StructDraw] = []
    labels: list[LabelAbs] = []
    return LayerState(0, no_swing, no_swing, hi_ring, lo_ring, draws, labels)


def new_struct_state() -> StructState:
    return StructState(new_layer_state(), new_layer_state())


def copy_swings(ring: list[Swing]) -> list[Swing]:
    result: list[Swing] = []
    for sw in ring:
        result.append(sw)
    return result


def own_layer(lay: LayerState) -> None:
    # See Main.own_state. hi / lo are changed in place (broken); ring entries, draws and labels never are, so
    # their lists are copied, not the records.
    if lay.hi is not None:
        lay.hi = copy_swing(lay.hi.value())
    if lay.lo is not None:
        lay.lo = copy_swing(lay.lo.value())
    lay.hi_ring = copy_swings(lay.hi_ring)
    lay.lo_ring = copy_swings(lay.lo_ring)
    draws: list[StructDraw] = []
    for d in lay.draws:
        draws.append(d)
    lay.draws = draws
    labels: list[LabelAbs] = []
    for lbl in lay.swing_labels:
        labels.append(lbl)
    lay.swing_labels = labels


def push_ring(ring: list[Swing], s: Swing) -> None:
    ring.append(copy_swing(s))
    if len(ring) > SWING_RING:
        ring.pop(0)


class StructureEngine:
    # BOS / CHoCH / CHoCH+ / MSS on two pivot layers (spec §3.3).
    def __init__(self, ctx: Context, st: Var[StructState], cfg: Config, draw: Draw):
        self._ctx = ctx
        self._st = st
        self._cfg = cfg
        self._draw = draw

    def own(self) -> None:
        st = self._st.get()
        own_layer(st.internal)
        own_layer(st.swing)

    def show_all(self) -> None:
        # Draws the Present mode handles the state holds (Main.materialize).
        st = self._st.get()
        self._show_layer(st.internal)
        self._show_layer(st.swing)

    def _show_layer(self, lay: LayerState) -> None:
        for d in lay.draws:
            self._draw.new_line(d.line)
            if d.label is not None:
                self._draw.new_label(d.label.value())
            if d.ghost is not None:
                self._draw.new_line(d.ghost.value())
        for lbl in lay.swing_labels:
            self._draw.new_label(lbl)

    def trend(self, layer: int) -> int:
        if layer == L_SWING:
            return self._st.get().swing.trend
        return self._st.get().internal.trend

    def breaks(self, k: int, atr: SeriesF, ev: BarEvents, data: DataOut) -> None:
        st = self._st.get()
        swing_bull_level = nan
        swing_bear_level = nan
        hi = st.swing.hi
        lo = st.swing.lo
        trend = st.swing.trend
        hi_open = hi is not None and not hi.value().broken
        lo_open = lo is not None and not lo.value().broken
        sw_up = self._break(k, atr, st.swing, L_SWING, BULL, hi, trend, nan, nan, ev)
        if sw_up is not None:
            swing_bull_level = sw_up.value().level
        sw_dn = self._break(k, atr, st.swing, L_SWING, BEAR, lo, trend, nan, nan, ev)
        if sw_dn is not None:
            swing_bear_level = sw_dn.value().level
        if hi_open and lo_open:
            self._outside(k, st.swing, hi, lo)
        unbroken_hi = nan
        if st.swing.hi is not None and not st.swing.hi.value().broken:
            unbroken_hi = st.swing.hi.value().price
        unbroken_lo = nan
        if st.swing.lo is not None and not st.swing.lo.value().broken:
            unbroken_lo = st.swing.lo.value().price
        if not self._cfg.ms_int_hide_at_swing:
            swing_bull_level = nan
            swing_bear_level = nan
            unbroken_hi = nan
            unbroken_lo = nan
        hi = st.internal.hi
        lo = st.internal.lo
        trend = st.internal.trend
        hi_open = hi is not None and not hi.value().broken
        lo_open = lo is not None and not lo.value().broken
        self._break(k, atr, st.internal, L_INT, BULL, hi, trend, swing_bull_level, unbroken_hi, ev)
        self._break(k, atr, st.internal, L_INT, BEAR, lo, trend, swing_bear_level, unbroken_lo, ev)
        if hi_open and lo_open:
            self._outside(k, st.internal, hi, lo)
        data.trend_swing = float(st.swing.trend)
        data.trend_internal = float(st.internal.trend)

    def new_pivots(self, k: int, int_ph: float, int_pl: float, swing_ph: float, swing_pl: float,
                   ev: BarEvents) -> None:
        st = self._st.get()
        self._pivot(k, st.swing, L_SWING, True, swing_ph, self._cfg.ms_swing_right, ev)
        self._pivot(k, st.swing, L_SWING, False, swing_pl, self._cfg.ms_swing_right, ev)
        self._pivot(k, st.internal, L_INT, True, int_ph, self._cfg.ms_int_right, ev)
        self._pivot(k, st.internal, L_INT, False, int_pl, self._cfg.ms_int_right, ev)

    def _outside(self, k: int, lay: LayerState, hi: Optional[Swing], lo: Optional[Swing]) -> None:
        # An outside bar that broke both swings of the layer emits both events; the trend follows the bar's
        # body (a doji: bull).
        if hi.value().broken and lo.value().broken:
            lay.trend = BEAR if self._ctx.close[k] < self._ctx.open[k] else BULL

    def _break(self, k: int, atr: SeriesF, lay: LayerState, layer: int, direction: int, target: Optional[Swing],
               trend_before: int, swing_level: float, unbroken_swing: float,
               ev: BarEvents) -> Optional[StructEvent]:
        # Breaks `target`, the layer's swing high (BULL) or swing low (BEAR) before this bar, if price got
        # through. Both sides are judged against the swings and trend from before the bar: a bull break replaces
        # the swing low with the bar's own low, which an outside bar's bear check must not compare against.
        ctx = self._ctx
        cfg = self._cfg
        result: Optional[StructEvent] = None
        if target is None:
            return result
        sw = target.value()
        if sw.broken:
            return result
        buf = 0.0
        if cfg.ms_break_buffer_atr > 0 and not isnan(atr[k]):
            buf = cfg.ms_break_buffer_atr * atr[k]
        crossed = False
        if direction == BULL:
            x = ctx.close[k] if cfg.ms_confirm_close else ctx.high[k]
            crossed = x > sw.price + buf
        else:
            x = ctx.close[k] if cfg.ms_confirm_close else ctx.low[k]
            crossed = x < sw.price - buf
        if not crossed:
            return result

        t = ctx.bar_index - k
        leg = self._leg(k, atr, lay, direction, sw.anchor_bar)
        kind = K_BOS
        if trend_before == -direction:
            kind = K_CHOCH
            ring = lay.lo_ring if direction == BULL else lay.hi_ring
            if cfg.ms_choch_plus and len(ring) >= 2:
                last = ring[len(ring) - 1].price
                prev = ring[len(ring) - 2].price
                # The opposite structure already failed: a higher low before a bull CHoCH, a lower high before
                # a bear one.
                if (direction == BULL and last > prev) or (direction == BEAR and last < prev):
                    kind = K_CHOCH_PLUS
        mss = False
        if kind != K_BOS:
            mss = leg.displaced and (leg.swept or not cfg.strict)

        sw.broken = True
        lay.trend = direction
        # Break-derived swing: the leg extreme that produced the break is the new opposite swing, known now.
        opposite: Optional[Swing] = lay.lo if direction == BULL else lay.hi
        if opposite is None or leg.extreme_bar > opposite.value().anchor_bar:
            derived = Swing(leg.extreme, leg.extreme_bar, leg.extreme_time, t, ctx.time[k], False, SRC_BREAK)
            self._set_swing(lay, layer, direction == BEAR, derived, ev)

        tick = cfg.tick if cfg.tick > 0 else 0.0
        dropped = layer == L_INT and ((not isnan(swing_level) and abs(sw.price - swing_level) <= tick) or
                                      (not isnan(unbroken_swing) and abs(sw.price - unbroken_swing) <= tick))
        if dropped:
            return result
        event = StructEvent(layer, direction, kind, mss, sw.price, sw.anchor_bar, sw.anchor_time, sw.confirmed_time,
                            t, ctx.time[k], leg)
        ev.breaks.append(event)
        if layer == L_SWING:
            mark(ev, E_SWING_BOS if kind == K_BOS else E_SWING_CHOCH, direction)
        else:
            mark(ev, E_INT_BOS if kind == K_BOS else E_INT_CHOCH, direction)
        if mss:
            mark(ev, E_MSS, direction)
        self._draw_event(lay, event)
        result = event
        return result

    def _leg(self, k: int, atr: SeriesF, lay: LayerState, direction: int, from_bar: int) -> Leg:
        # Scans the bars (from_bar, t], newest first, clipped to MAX_LOOKBACK.
        ctx = self._ctx
        cfg = self._cfg
        t = ctx.bar_index - k
        n = min(t - from_bar, MAX_LOOKBACK, t + 1)
        ext_off = k
        ext = ctx.low[k] if direction == BULL else ctx.high[k]
        for i in range(1, n):
            v = ctx.low[k + i] if direction == BULL else ctx.high[k + i]
            # Strict comparison keeps the latest bar on ties.
            if (direction == BULL and v < ext) or (direction == BEAR and v > ext):
                ext = v
                ext_off = k + i

        ob_off = ext_off
        if not cfg.ob_leg_extreme:
            off = ext_off
            while off < k + n:
                opposite = ctx.close[off] < ctx.open[off] if direction == BULL else ctx.close[off] > ctx.open[off]
                if opposite:
                    ob_off = off
                    break
                off += 1

        displaced = False
        for off in range(k, ext_off + 1):
            a = atr[off]
            if not isnan(a) and abs(ctx.close[off] - ctx.open[off]) >= cfg.ms_mss_disp_atr * a:
                displaced = True
                break
        if not displaced:
            for off in range(k, ext_off - 1):
                if fvg_at(ctx, off, direction, cfg, atr):
                    displaced = True
                    break

        ext_bar = ctx.bar_index - ext_off
        swept = False
        ring = lay.lo_ring if direction == BULL else lay.hi_ring
        for j in range(len(ring) - 1, -1, -1):
            if ring[j].anchor_bar < ext_bar:
                swept = ext < ring[j].price if direction == BULL else ext > ring[j].price
                break
        return Leg(ext, ext_bar, ctx.time[ext_off], ctx.high[ob_off], ctx.low[ob_off], ctx.bar_index - ob_off,
                   ctx.time[ob_off], ctx.volume[ob_off], displaced, swept)

    def _pivot(self, k: int, lay: LayerState, layer: int, is_high: bool, price: float, right: int,
               ev: BarEvents) -> None:
        if isnan(price):
            return
        ctx = self._ctx
        t = ctx.bar_index - k
        anchor = t - right
        current: Optional[Swing] = lay.hi if is_high else lay.lo
        # A newer (break-derived) swing on this side stays the level to break.
        if current is not None and current.value().anchor_bar >= anchor:
            return
        self._set_swing(lay, layer, is_high, Swing(price, anchor, ctx.time[k + right], t, ctx.time[k], False,
                                                   SRC_PIVOT), ev)

    def _set_swing(self, lay: LayerState, layer: int, is_high: bool, sw: Swing, ev: BarEvents) -> None:
        ring = lay.hi_ring if is_high else lay.lo_ring
        prev = nan
        if len(ring) > 0:
            prev = ring[len(ring) - 1].price
        if is_high:
            lay.hi = sw
        else:
            lay.lo = sw
        push_ring(ring, sw)
        if layer != L_SWING:
            return
        if is_high:
            ev.new_swing_hi = copy_swing(sw)
        else:
            ev.new_swing_lo = copy_swing(sw)
        cfg = self._cfg
        if not cfg.ms_swing_labels or not cfg.ms_swing_show or cfg.label_text == TEXT_OFF or isnan(prev):
            return
        up = sw.price > prev
        text = 'HL' if up else 'LL'
        if is_high:
            text = 'HH' if up else 'LH'
        when = sw.anchor_time if cfg.anchoring == A_ORIGIN else sw.confirmed_time
        lbl = new_text_label(text, when, sw.price, cfg.bull_color if up else cfg.bear_color, cfg.font, is_high)
        self._draw.keep_label(lbl)
        if not cfg.history:
            lay.swing_labels.append(lbl)
            if len(lay.swing_labels) > 2 * cfg.ms_max_events:
                self._draw.erase_label(lay.swing_labels[0])
                lay.swing_labels.pop(0)

    def _draw_event(self, lay: LayerState, e: StructEvent) -> None:
        cfg = self._cfg
        swing = e.layer == L_SWING
        if (swing and not cfg.ms_swing_show) or (not swing and not cfg.ms_int_show):
            return
        shown = cfg.ms_swing_filter if swing else cfg.ms_int_filter
        if (shown == 'BOS' and e.kind != K_BOS) or (shown == 'CHoCH' and e.kind == K_BOS):
            return
        col = cfg.bull_color
        if swing and e.direction == BEAR:
            col = cfg.bear_color
        elif not swing:
            col = cfg.int_bull_color if e.direction == BULL else cfg.int_bear_color
        start = e.from_anchor_time if cfg.anchoring == A_ORIGIN else e.from_confirmed_time
        style = line_style.SOLID
        if swing and e.kind != K_BOS:
            style = line_style.DASHED
        elif not swing:
            style = line_style.DASHED if e.kind == K_BOS else line_style.DOTTED
        ln = LineSegment(AbsolutePosition(start, e.level), AbsolutePosition(e.time, e.level), color=col,
                         line_style=style, line_width=2 if swing else 1)
        self._draw.keep_line(ln)
        lbl: Optional[LabelAbs] = None
        if cfg.label_text != TEXT_OFF:
            lbl = new_text_label(struct_text(cfg, e), (start + e.time) / 2, e.level, col,
                                 cfg.font if swing else cfg.font_int, e.direction == BULL)
            self._draw.keep_label(lbl.value())
        ghost: Optional[LineSegment] = None
        if cfg.anchoring == A_GHOST and e.from_anchor_time < e.from_confirmed_time:
            ghost = LineSegment(AbsolutePosition(e.from_anchor_time, e.level),
                                AbsolutePosition(e.from_confirmed_time, e.level), color=col,
                                line_style=line_style.DOTTED, line_width=1)
            self._draw.keep_line(ghost.value())
        if cfg.history:
            return
        lay.draws.append(StructDraw(ln, lbl, ghost))
        if len(lay.draws) > cfg.ms_max_events:
            old = lay.draws[0]
            self._draw.erase_line(old.line)
            if old.label is not None:
                self._draw.erase_label(old.label.value())
            if old.ghost is not None:
                self._draw.erase_line(old.ghost.value())
            lay.draws.pop(0)


def struct_text(cfg: Config, e: StructEvent) -> str:
    swing = e.layer == L_SWING
    plus = e.kind == K_CHOCH_PLUS
    f = 'BOS'
    if e.mss:
        f = 'MSS+' if plus else 'MSS'
    elif e.kind != K_BOS:
        f = 'CHoCH+' if plus else 'CHoCH'
    if cfg.label_text == TEXT_SHORT:
        # Swing breaks keep their names (they are short already); internal ones shrink to one letter.
        if swing:
            return f
        s = 'b'
        if e.mss:
            s = 'm+' if plus else 'm'
        elif e.kind != K_BOS:
            s = 'c+' if plus else 'c'
        return s
    return f if swing else 'i' + f


# §5 ObEngine ---------------------------------------------------------------------------------------------

# Fill alpha of a finished order block in History mode. Color has no alpha getter, so the fade can't be relative.
OB_FADED_ALPHA = 0.08
# Order blocks drawn per side when ob_max_dist_atr > 0 (ObEngine._select).
OB_NEAR = 2


@dataclass
class ObState:
    # Live order blocks (active, mitigated, breaker), oldest first.
    obs: list[Ob]


def new_ob_state() -> ObState:
    obs: list[Ob] = []
    return ObState(obs)


def ob_distance(ob: Ob, close: float) -> float:
    # Price distance from the close to the zone; 0 inside it.
    if close > ob.top:
        return close - ob.top
    if close < ob.bottom:
        return ob.bottom - close
    return 0.0


def ob_prefix(obs: list[Ob], n: int) -> list[Ob]:
    result: list[Ob] = []
    for i in range(n):
        result.append(obs[i])
    return result


class ObEngine:
    # Order block life cycle (spec §3.5): created from ev.breaks, then mitigated, invalidated, breakers.
    def __init__(self, ctx: Context, st: Var[ObState], cfg: Config, draw: Draw):
        self._ctx = ctx
        self._st = st
        self._cfg = cfg
        self._draw = draw

    def create(self, k: int, ev: BarEvents, data: DataOut) -> None:
        # Both layers always: ob_*_show only decides which blocks are drawn (_shown).
        cfg = self._cfg
        for e in ev.breaks:
            if (not cfg.ob_require_displacement or e.leg.displaced) and (not cfg.strict or e.leg.swept):
                self._create(k, e, ev)

    def update(self, k: int, atr: SeriesF, ev: BarEvents, data: DataOut) -> None:
        # Order blocks created on this bar are not updated on it.
        ctx = self._ctx
        cfg = self._cfg
        st = self._st.get()
        t = ctx.bar_index - k
        # Rebuilt only on a bar that finishes an order block.
        keep = st.obs
        rebuilt = False
        for i in range(len(st.obs)):
            ob = st.obs[i]
            alive = True
            if ob.confirmed_bar < t:
                alive = self._step(ob, ctx.high[k], ctx.low[k], ctx.close[k], ctx.time[k], ev)
            if not alive and not rebuilt:
                rebuilt = True
                keep = ob_prefix(st.obs, i)
            elif alive and rebuilt:
                keep.append(ob)
        st.obs = keep

        close = ctx.close[k]
        bull_top = nan
        bear_bottom = nan
        for ob in st.obs:
            if ob.state != ST_BREAKER:
                if ob.direction == BULL and ob.bottom <= close and (isnan(bull_top) or ob.top > bull_top):
                    bull_top = ob.top
                if ob.direction == BEAR and ob.top >= close and (isnan(bear_bottom) or ob.bottom < bear_bottom):
                    bear_bottom = ob.bottom
        data.ob_bull_top = bull_top
        data.ob_bear_bottom = bear_bottom
        if cfg.ob_max_dist_atr > 0:
            self._select(BULL, close, cfg.ob_max_dist_atr * atr[k])
            self._select(BEAR, close, cfg.ob_max_dist_atr * atr[k])

    def _select(self, side: int, close: float, reach: float) -> None:
        # Proximity selection (spec "Order blocks"): of the kept blocks acting for `side` (support: bullish
        # blocks and bearish breakers), the OB_NEAR nearest to the close and not farther than `reach` have
        # drawings, the others none. Runs on every processed bar, so the chart changes only when the selection
        # does; a NaN reach (ATR not ready) doesn't limit. No allocation: the cut is the OB_NEAR-th nearest
        # (distance, index), nearer first and newer first on a tie.
        st = self._st.get()
        cut_dist = -1.0
        cut_index = len(st.obs)
        for n in range(OB_NEAR):
            best = -1
            best_dist = 0.0
            for i in range(len(st.obs)):
                ob = st.obs[i]
                if self._side(ob) == side and self._drawable(ob):
                    d = ob_distance(ob, close)
                    after_cut = d > cut_dist or (d == cut_dist and i < cut_index)
                    if after_cut and (best < 0 or d < best_dist or (d == best_dist and i > best)):
                        best = i
                        best_dist = d
            if best >= 0:
                cut_dist = best_dist
                cut_index = best
        for i in range(len(st.obs)):
            ob = st.obs[i]
            if self._side(ob) == side:
                d = ob_distance(ob, close)
                near = cut_dist >= 0 and self._drawable(ob) and (d < cut_dist or (d == cut_dist and i >= cut_index)) \
                    and not d > reach
                if near and ob.box is None:
                    self._draw_new(ob)
                elif not near and ob.box is not None:
                    self._erase(ob)

    def _side(self, ob: Ob) -> int:
        # The side a block acts for: a breaker has the opposite polarity.
        return -ob.direction if ob.state == ST_BREAKER else ob.direction

    def _look(self, ob: Ob) -> int:
        # The layer a block is drawn as: its own, except that a promoted block stays internal while swing blocks are
        # hidden, so the internal-only view keeps it as it was before the swing break found it too.
        if ob.layer == L_SWING and ob.promoted and not self._cfg.ob_swing_show:
            return L_INT
        return ob.layer

    def _shown(self, ob: Ob) -> bool:
        # The layer's show toggle: a hidden layer's blocks run as usual (alerts, data) but are never drawn.
        return self._cfg.ob_swing_show if self._look(ob) == L_SWING else self._cfg.ob_int_show

    def _drawable(self, ob: Ob) -> bool:
        return self._shown(ob) and not (ob.state == ST_MITIGATED and self._cfg.ob_mitigated_action == 'Hide')

    def _create(self, k: int, e: StructEvent, ev: BarEvents) -> None:
        ctx = self._ctx
        cfg = self._cfg
        st = self._st.get()
        leg = e.leg
        # Internal and swing may pick the same candle: one order block, the swing one.
        for old in st.obs:
            if old.state != ST_BREAKER and old.direction == e.direction and old.anchor_bar == leg.ob_bar:
                if e.layer == L_SWING and old.layer == L_INT:
                    self._promote(old, e.time)
                return

        top = leg.ob_top
        bottom = leg.ob_bottom
        no_box: Optional[Rectangle] = None
        no_label: Optional[LabelAbs] = None
        no_ghost: Optional[LineSegment] = None
        inside = ctx.low[k] <= top and ctx.high[k] >= bottom
        ob = Ob(e.direction, e.layer, top, bottom, (top + bottom) / 2, leg.ob_bar, leg.ob_time, e.bar, e.time,
                leg.swept, leg.displaced, leg.ob_volume, 0, inside, ST_ACTIVE, False, no_box, no_label, no_ghost)
        if cfg.ob_hide_older:
            keep: list[Ob] = []
            for old in st.obs:
                if old.layer == ob.layer and old.direction == ob.direction and old.state != ST_BREAKER and \
                        old.bottom <= top and bottom <= old.top:
                    self._retire(old, e.time)
                else:
                    keep.append(old)
            st.obs = keep
        # With a max distance, update() draws it if it is among the nearest.
        if cfg.ob_max_dist_atr <= 0 and self._shown(ob):
            self._draw_new(ob)
        st.obs.append(ob)
        mark(ev, E_OB_NEW, e.direction)
        self._cap(ob.layer, ob.direction, e.time)

    def own(self) -> None:
        # See Main.own_state.
        st = self._st.get()
        fresh: list[Ob] = []
        for ob in st.obs:
            fresh.append(Ob(ob.direction, ob.layer, ob.top, ob.bottom, ob.mid, ob.anchor_bar, ob.anchor_time,
                            ob.confirmed_bar, ob.confirmed_time, ob.swept, ob.displaced, ob.volume, ob.touches,
                            ob.inside, ob.state, ob.promoted, ob.box, ob.label, ob.ghost))
        st.obs = fresh

    def show_all(self) -> None:
        # Draws the live order blocks' drawings (Main.materialize).
        for ob in self._st.get().obs:
            if ob.box is not None:
                self._draw.new_rect(ob.box.value())
            if ob.label is not None:
                self._draw.new_label(ob.label.value())
            if ob.ghost is not None:
                self._draw.new_line(ob.ghost.value())

    def _promote(self, ob: Ob, now: float) -> None:
        # An internal order block re-picked by a swing break becomes a swing one; moved to the newest position so
        # the swing cap doesn't retire it at once.
        st = self._st.get()
        keep: list[Ob] = []
        for other in st.obs:
            if other.anchor_bar != ob.anchor_bar or other.direction != ob.direction or other.layer != ob.layer:
                keep.append(other)
        ob.layer = L_SWING
        ob.promoted = True
        keep.append(ob)
        st.obs = keep
        # Drawn as swing unless swing blocks are hidden (_look); then nothing changes on the chart. Looking swing
        # means swing blocks are shown.
        if self._look(ob) == L_SWING:
            if ob.box is None:
                if self._cfg.ob_max_dist_atr <= 0 and self._drawable(ob):
                    self._draw_new(ob)
            else:
                self._restyle(ob, True)
        self._cap(L_SWING, ob.direction, now)

    def _cap(self, layer: int, direction: int, now: float) -> None:
        # Show last N per layer and direction (breakers included): the oldest are retired.
        st = self._st.get()
        limit = self._cfg.ob_swing_last if layer == L_SWING else self._cfg.ob_int_last
        n = 0
        for ob in st.obs:
            if ob.layer == layer and ob.direction == direction:
                n += 1
        excess = n - limit
        if excess <= 0:
            return
        keep: list[Ob] = []
        for ob in st.obs:
            if excess > 0 and ob.layer == layer and ob.direction == direction:
                self._retire(ob, now)
                excess -= 1
            else:
                keep.append(ob)
        st.obs = keep

    def _step(self, ob: Ob, high: float, low: float, close: float, now: float, ev: BarEvents) -> bool:
        # Advances one order block by one bar; False when it is finished (already retired).
        cfg = self._cfg
        inside = low <= ob.top and high >= ob.bottom
        entered = inside and not ob.inside
        ob.inside = inside
        bull = ob.direction == BULL
        if ob.state == ST_BREAKER:
            # The polarity is flipped: a bull order block's breaker is resistance.
            if entered:
                ob.touches += 1
                mark(ev, E_OB_ENTER, -ob.direction)
            through = close > ob.top if bull else close < ob.bottom
            if through:
                self._retire(ob, now)
                return False
            return True

        broken = False
        if cfg.ob_invalidation_close:
            broken = close < ob.bottom if bull else close > ob.top
        else:
            broken = low < ob.bottom if bull else high > ob.top
        mitigated = False
        if ob.state == ST_ACTIVE:
            if cfg.ob_mitigation == 'Close':
                mitigated = close <= ob.top if bull else close >= ob.bottom
            elif cfg.ob_mitigation == '50%':
                mitigated = low <= ob.mid if bull else high >= ob.mid
            else:
                mitigated = low <= ob.top if bull else high >= ob.bottom
        if mitigated:
            ob.state = ST_MITIGATED
            mark(ev, E_OB_MITIGATED, ob.direction)
        if entered:
            ob.touches += 1
            mark(ev, E_OB_ENTER, ob.direction)
        if broken:
            mark(ev, E_OB_BROKEN, ob.direction)
            if cfg.ob_breakers and (ob.swept or not cfg.strict):
                ob.state = ST_BREAKER
                self._restyle(ob, True)
                return True
            self._retire(ob, now)
            return False
        if mitigated:
            if cfg.ob_mitigated_action == 'Recolor':
                self._restyle(ob, False)
            elif cfg.ob_mitigated_action == 'Hide':
                self._erase(ob)
        return True

    def _fill(self, ob: Ob) -> Color:
        cfg = self._cfg
        if ob.state == ST_BREAKER:
            return cfg.breaker_bear_color if ob.direction == BULL else cfg.breaker_bull_color
        if ob.state == ST_MITIGATED and cfg.ob_mitigated_action == 'Recolor':
            return cfg.ob_mitigated_color
        return cfg.ob_bull_color if ob.direction == BULL else cfg.ob_bear_color

    def _border(self, ob: Ob) -> Color:
        cfg = self._cfg
        if ob.state == ST_BREAKER:
            return self._fill(ob)(1.0)
        if self._look(ob) == L_SWING:
            return cfg.bull_color if ob.direction == BULL else cfg.bear_color
        return cfg.int_bull_color if ob.direction == BULL else cfg.int_bear_color

    def _text(self, ob: Ob) -> str:
        if ob.state == ST_BREAKER:
            return 'Breaker'
        return 'OB' if self._look(ob) == L_SWING else 'iOB'

    def _draw_new(self, ob: Ob) -> None:
        # Drawn once, extended right while live; touched again only on a state change (or drawn anew by select()).
        cfg = self._cfg
        start = ob.anchor_time if cfg.anchoring == A_ORIGIN else ob.confirmed_time
        border = self._border(ob)
        box = Rectangle(AbsolutePosition(start, ob.top), AbsolutePosition(ob.confirmed_time, ob.bottom),
                        line_style=line_style.SOLID if self._look(ob) == L_SWING and ob.state != ST_BREAKER else
                        line_style.DASHED, line_width=1, line_color=border, bg_color=self._fill(ob),
                        extend_right=True, middle_line_style=line_style.DOTTED, middle_line_width=1,
                        middle_line_color=border if cfg.ob_show_mid else color.TRANSPARENT)
        ob.box = box
        self._draw.new_rect(box)
        if cfg.label_text == TEXT_FULL:
            lbl = new_text_label(self._text(ob), start, ob.top, cfg.text_color, cfg.font_int, True)
            ob.label = lbl
            self._draw.new_label(lbl)
        if cfg.anchoring == A_GHOST and ob.anchor_time < ob.confirmed_time:
            ghost = LineSegment(AbsolutePosition(ob.anchor_time, ob.mid), AbsolutePosition(ob.confirmed_time, ob.mid),
                                color=border, line_style=line_style.DOTTED, line_width=1)
            ob.ghost = ghost
            self._draw.new_line(ghost)

    def _restyle(self, ob: Ob, relabel: bool) -> None:
        # Applies the current state's look. A hidden (mitigated + Hide) order block reappears only as a breaker,
        # and only on a shown layer; with a max distance, a block without drawings is left to select().
        if ob.box is None:
            if ob.state == ST_BREAKER and self._cfg.ob_max_dist_atr <= 0 and self._shown(ob):
                self._draw_new(ob)
            return
        box = ob.box.value()
        box.bg_color = self._fill(ob)
        box.line_color = self._border(ob)
        box.line_style = line_style.SOLID if self._look(ob) == L_SWING and ob.state != ST_BREAKER else line_style.DASHED
        self._draw.rect(box)
        if relabel and ob.label is not None:
            lbl = ob.label.value()
            lbl.text = self._text(ob)
            self._draw.label(lbl)

    def _erase(self, ob: Ob) -> None:
        no_box: Optional[Rectangle] = None
        no_label: Optional[LabelAbs] = None
        no_ghost: Optional[LineSegment] = None
        if ob.box is not None:
            self._draw.erase_rect(ob.box.value())
            ob.box = no_box
        if ob.label is not None:
            self._draw.erase_label(ob.label.value())
            ob.label = no_label
        if ob.ghost is not None:
            self._draw.erase_line(ob.ghost.value())
            ob.ghost = no_ghost

    def _retire(self, ob: Ob, now: float) -> None:
        # The caller drops it from state. History keeps it truncated at `now` and faded; Present erases it.
        if not self._cfg.history:
            self._erase(ob)
            return
        if ob.box is None:
            return
        box = ob.box.value()
        fill = self._fill(ob)
        box.point_b = AbsolutePosition(now, ob.bottom)
        box.extend_right = False
        box.bg_color = fill(OB_FADED_ALPHA)
        self._draw.final_rect(box, True)
        if ob.label is not None:
            self._draw.final_label(ob.label.value(), False)
        if ob.ghost is not None:
            self._draw.final_line(ob.ghost.value(), False)


# §6 FvgEngine --------------------------------------------------------------------------------------------

@dataclass
class FvgState:
    # Live gaps: ACTIVE (unfilled), FILLED (still invertible) and INVERSE. Each state is
    # capped at fvg_last per direction. Creation order, except that a gap moves to the end when it is filled
    # or inverted, so "oldest" means oldest in its current state.
    fvgs: list[Fvg]


def new_fvg_state() -> FvgState:
    fvgs: list[Fvg] = []
    return FvgState(fvgs)


def fvg_at(ctx: Context, k: int, direction: int, cfg: Config, atr: SeriesF) -> bool:
    # True if the bar at offset k completes a FVG of `direction` (spec §3.6 detection, threshold included).
    # Also used by the structure displacement check.
    if ctx.bar_index - k < 2:
        return False
    gap = 0.0
    if direction == BULL:
        gap = ctx.low[k] - ctx.high[k + 2]
    else:
        gap = ctx.low[k + 2] - ctx.high[k]
    if not gap > 0:
        return False
    if cfg.fvg_threshold_atr > 0:
        # A size filter that can't be measured yet (ATR warm-up) rejects the gap.
        a = atr[k]
        if isnan(a) or gap < cfg.fvg_threshold_atr * a:
            return False
    if cfg.strict:
        body = ctx.close[k + 1] - ctx.open[k + 1]
        if (direction == BULL and not body > 0) or (direction == BEAR and not body < 0):
            return False
    return True


def fvg_prefix(fvgs: list[Fvg], n: int) -> list[Fvg]:
    result: list[Fvg] = []
    for i in range(n):
        result.append(fvgs[i])
    return result


def copy_fvg(f: Fvg) -> Fvg:
    return Fvg(f.direction, f.top, f.bottom, f.ce, f.filled_to, f.anchor_bar, f.anchor_time, f.confirmed_bar,
               f.confirmed_time, f.entered, f.state, f.box, f.ce_line, f.label, f.ghost)


class FvgEngine:
    # Fair value gaps (spec §3.6): detected on the bar that completes the 3-candle gap, partially filled as
    # price trades into it, filled by fvg_fill, then optionally inverted (IFVG) by a close through the far edge.
    def __init__(self, ctx: Context, st: Var[FvgState], cfg: Config, draw: Draw):
        self._ctx = ctx
        self._st = st
        self._cfg = cfg
        self._draw = draw

    def own(self) -> None:
        # See Main.own_state.
        st = self._st.get()
        fresh: list[Fvg] = []
        for i in range(len(st.fvgs)):
            fresh.append(copy_fvg(st.fvgs[i]))
        st.fvgs = fresh

    def show_all(self) -> None:
        # Draws the live gaps' drawings (Main.materialize).
        for f in self._st.get().fvgs:
            if f.box is not None:
                self._draw.new_rect(f.box.value())
            if f.ce_line is not None:
                self._draw.new_line(f.ce_line.value())
            if f.label is not None:
                self._draw.new_label(f.label.value())
            if f.ghost is not None:
                self._draw.new_line(f.ghost.value())

    def detect(self, k: int, atr: SeriesF, ev: BarEvents, data: DataOut) -> None:
        # Always runs: fvg_show and fvg_ifvg only decide what is drawn (_draw_new, _draw_inverse).
        cfg = self._cfg
        # A bar can't complete a bull and a bear gap at once (low@t > high@(t-2) excludes high@t < low@(t-2)).
        if fvg_at(self._ctx, k, BULL, cfg, atr):
            self._create(k, BULL, ev)
        elif fvg_at(self._ctx, k, BEAR, cfg, atr):
            self._create(k, BEAR, ev)

    def update(self, k: int, ev: BarEvents, data: DataOut) -> None:
        ctx = self._ctx
        st = self._st.get()
        t = ctx.bar_index - k
        # The list is rebuilt only on a bar that finishes or moves a gap; most bars change nothing.
        stay = st.fvgs
        moved = st.fvgs
        rebuilt = False
        for i in range(len(st.fvgs)):
            f = st.fvgs[i]
            keep = True
            move = False
            if f.confirmed_bar < t:
                before = f.state
                if self._step(f, k, ev):
                    move = f.state != before
                else:
                    keep = False
            if (move or not keep) and not rebuilt:
                rebuilt = True
                stay = fvg_prefix(st.fvgs, i)
                moved = fvg_prefix(st.fvgs, 0)
            if rebuilt:
                if move:
                    moved.append(f)
                elif keep:
                    stay.append(f)
        if rebuilt:
            for i in range(len(moved)):
                stay.append(moved[i])
            st.fvgs = stay
        now = ctx.time[k]
        self._prune(ST_FILLED, BULL, now)
        self._prune(ST_FILLED, BEAR, now)
        self._prune(ST_INVERSE, BULL, now)
        self._prune(ST_INVERSE, BEAR, now)

        bull_top = nan
        bear_bottom = nan
        for i in range(len(st.fvgs)):
            f = st.fvgs[i]
            if f.state != ST_ACTIVE:
                continue
            # The unfilled edge of an active gap is on the near side of the close, so the nearest gap is the
            # one with the highest bull edge / the lowest bear edge.
            if f.direction == BULL and (isnan(bull_top) or f.filled_to > bull_top):
                bull_top = f.filled_to
            if f.direction == BEAR and (isnan(bear_bottom) or f.filled_to < bear_bottom):
                bear_bottom = f.filled_to
        data.fvg_bull_top = bull_top
        data.fvg_bear_bottom = bear_bottom

    def _create(self, k: int, direction: int, ev: BarEvents) -> None:
        ctx = self._ctx
        t = ctx.bar_index - k
        top = ctx.low[k + 2]
        bottom = ctx.high[k]
        filled_to = bottom
        if direction == BULL:
            top = ctx.low[k]
            bottom = ctx.high[k + 2]
            filled_to = top
        no_box: Optional[Rectangle] = None
        no_line: Optional[LineSegment] = None
        no_label: Optional[LabelAbs] = None
        f = Fvg(direction, top, bottom, (top + bottom) / 2, filled_to, t - 1, ctx.time[k + 1], t, ctx.time[k], False,
                ST_ACTIVE, no_box, no_line, no_label, no_line)
        mark(ev, E_FVG_NEW, direction)
        self._draw_new(f)
        self._st.get().fvgs.append(f)
        self._prune(ST_ACTIVE, direction, ctx.time[k])

    def _step(self, f: Fvg, k: int, ev: BarEvents) -> bool:
        # Updates one gap on the bar at offset k; False when it is finished and leaves the state.
        ctx = self._ctx
        cfg = self._cfg
        bull = f.direction == BULL
        low = ctx.low[k]
        high = ctx.high[k]
        close = ctx.close[k]
        now = ctx.time[k]
        if f.state == ST_INVERSE:
            # The inverse gap is finished by a close back through it (bull gap inverted to resistance: above top).
            if (bull and close > f.top) or (not bull and close < f.bottom):
                self._close_inverse(f, now)
                return False
            return True

        if f.state == ST_ACTIVE:
            touched = low <= f.top if bull else high >= f.bottom
            if touched and not f.entered:
                f.entered = True
                mark(ev, E_FVG_ENTER, f.direction)
            moved = False
            if bull and low < f.filled_to:
                f.filled_to = max(low, f.bottom)
                moved = True
            elif not bull and high > f.filled_to:
                f.filled_to = min(high, f.top)
                moved = True
            filled = False
            if cfg.fvg_fill == 'Close (full)':
                filled = close <= f.bottom if bull else close >= f.top
            elif cfg.fvg_fill == 'CE (50%)':
                filled = low <= f.ce if bull else high >= f.ce
            else:
                filled = low <= f.bottom if bull else high >= f.top
            if filled:
                f.state = ST_FILLED
                mark(ev, E_FVG_FILLED, f.direction)
                self._close_box(f, now)
            elif moved and cfg.fvg_shrink and f.box is not None:
                start = f.anchor_time if cfg.anchoring == A_ORIGIN else f.confirmed_time
                box = f.box.value()
                if bull:
                    box.point_a = AbsolutePosition(start, f.filled_to)
                else:
                    box.point_b = AbsolutePosition(f.confirmed_time, f.filled_to)
                self._draw.rect(box)

        if f.state == ST_FILLED:
            # A body close beyond the far edge inverts the gap (also on the bar that filled it).
            if (bull and close < f.bottom) or (not bull and close > f.top):
                f.state = ST_INVERSE
                mark(ev, E_IFVG, -f.direction)
                self._draw_inverse(f, now)
        return True

    def _draw_new(self, f: Fvg) -> None:
        cfg = self._cfg
        if not cfg.fvg_show:
            return
        col = cfg.fvg_bull_color if f.direction == BULL else cfg.fvg_bear_color
        start = f.anchor_time if cfg.anchoring == A_ORIGIN else f.confirmed_time
        # Bull: point_a carries the top (the edge that fills), bear: point_b carries the bottom.
        box = Rectangle(AbsolutePosition(start, f.top), AbsolutePosition(f.confirmed_time, f.bottom),
                        line_width=1, line_color=color.TRANSPARENT, bg_color=col, extend_right=True)
        f.box = box
        self._draw.new_rect(box)
        if cfg.fvg_ce:
            # A separate ray, not the box middle line: the box shrinks, the CE stays at the original midpoint.
            # point_b only gives the ray its direction, also in "At confirmation" mode (ray_end).
            ce = LineSegment(AbsolutePosition(start, f.ce), AbsolutePosition(ray_end(start), f.ce),
                             extend_type=extend_type.RIGHT, color=col(0.8), line_style=line_style.DOTTED,
                             line_width=1)
            f.ce_line = ce
            self._draw.new_line(ce)
        if cfg.label_text == TEXT_FULL:
            lbl = new_text_label('FVG', start, f.top, cfg.text_color, cfg.font_int, True)
            f.label = lbl
            self._draw.new_label(lbl)
        if cfg.anchoring == A_GHOST:
            ghost = LineSegment(AbsolutePosition(f.anchor_time, f.ce), AbsolutePosition(f.confirmed_time, f.ce),
                                color=col(0.8), line_style=line_style.DOTTED, line_width=1)
            f.ghost = ghost
            self._draw.new_line(ghost)

    def _close_box(self, f: Fvg, now: float) -> None:
        # Ends the gap's drawing on a fill or a retire. History: truncated at `now`, full original bounds (the
        # shrink is a live view only); Present: erased. The record no longer holds drawings afterwards.
        cfg = self._cfg
        no_box: Optional[Rectangle] = None
        no_line: Optional[LineSegment] = None
        no_label: Optional[LabelAbs] = None
        if f.box is not None:
            box = f.box.value()
            if cfg.history:
                start = f.anchor_time if cfg.anchoring == A_ORIGIN else f.confirmed_time
                box.point_a = AbsolutePosition(start, f.top)
                box.point_b = AbsolutePosition(now, f.bottom)
                box.extend_right = False
                self._draw.final_rect(box, True)
            else:
                self._draw.erase_rect(box)
        if f.ce_line is not None:
            ce = f.ce_line.value()
            if cfg.history:
                ce.point_b = AbsolutePosition(now, f.ce)
                ce.extend_type = extend_type.NONE
                self._draw.final_line(ce, True)
            else:
                self._draw.erase_line(ce)
        if f.label is not None:
            if cfg.history:
                self._draw.final_label(f.label.value(), False)
            else:
                self._draw.erase_label(f.label.value())
        if f.ghost is not None:
            if cfg.history:
                self._draw.final_line(f.ghost.value(), False)
            else:
                self._draw.erase_line(f.ghost.value())
        f.box = no_box
        f.ce_line = no_line
        f.label = no_label
        f.ghost = no_line

    def _draw_inverse(self, f: Fvg, now: float) -> None:
        # The inverse gap is drawn from the inversion bar, full original bounds, in a light fill of the direction
        # it now acts in (a bullish gap inverts to bearish) with a dashed border. Drawn with fvg_show and fvg_ifvg.
        cfg = self._cfg
        if not cfg.fvg_show or not cfg.fvg_ifvg:
            return
        col = cfg.ifvg_bear_color if f.direction == BULL else cfg.ifvg_bull_color
        box = Rectangle(AbsolutePosition(now, f.top), AbsolutePosition(now, f.bottom), line_width=1,
                        line_color=col(0.5), line_style=line_style.DASHED, bg_color=col, extend_right=True)
        f.box = box
        self._draw.new_rect(box)
        if cfg.label_text == TEXT_FULL:
            lbl = new_text_label('IFVG', now, f.top, cfg.text_color, cfg.font_int, True)
            f.label = lbl
            self._draw.new_label(lbl)

    def _close_inverse(self, f: Fvg, now: float) -> None:
        cfg = self._cfg
        no_box: Optional[Rectangle] = None
        no_label: Optional[LabelAbs] = None
        if f.box is not None:
            box = f.box.value()
            if cfg.history:
                box.point_b = AbsolutePosition(now, f.bottom)
                box.extend_right = False
                self._draw.final_rect(box, True)
            else:
                self._draw.erase_rect(box)
        if f.label is not None:
            if cfg.history:
                self._draw.final_label(f.label.value(), False)
            else:
                self._draw.erase_label(f.label.value())
        f.box = no_box
        f.label = no_label

    def _prune(self, state: int, direction: int, now: float) -> None:
        # Keeps the newest fvg_last gaps of one state and direction; older ones are retired.
        st = self._st.get()
        count = 0
        for i in range(len(st.fvgs)):
            if st.fvgs[i].state == state and st.fvgs[i].direction == direction:
                count += 1
        excess = count - self._cfg.fvg_last
        if excess <= 0:
            return
        keep: list[Fvg] = []
        for i in range(len(st.fvgs)):
            f = st.fvgs[i]
            if excess > 0 and f.state == state and f.direction == direction:
                excess -= 1
                if state == ST_ACTIVE:
                    self._close_box(f, now)
                elif state == ST_INVERSE:
                    self._close_inverse(f, now)
                # A FILLED gap is already finalized on the chart; it is just dropped.
                continue
            keep.append(f)
        st.fvgs = keep


# §7 LiquidityEngine --------------------------------------------------------------------------------------

# A pool's side is the direction of its events: buy-side pools (above highs) are the bearish side, sell-side
# pools (below lows) the bullish side (spec WP1 deviations: +1 = equal lows / sell-side swept).
SIDE_BSL = BEAR
SIDE_SSL = BULL
# Key levels in LiqState.htf order: the first three are highs (buy-side), the last three lows (sell-side).
HTF_SLOTS = 6


@dataclass
class LiqState:
    # Live pools per side: ACTIVE or PIERCED (closed beyond, waiting for the close back within the window).
    bsl: list[Pool]
    ssl: list[Pool]
    # Key levels last registered as pools: pdh, pwh, pmh, pdl, pwl, pml; NaN when none.
    htf: list[float]
    # Present mode: sweep labels still on the chart, oldest first.
    sweep_labels: list[LabelAbs]


def new_liq_state() -> LiqState:
    bsl: list[Pool] = []
    ssl: list[Pool] = []
    htf: list[float] = []
    for _ in range(HTF_SLOTS):
        htf.append(nan)
    labels: list[LabelAbs] = []
    return LiqState(bsl, ssl, htf, labels)


def htf_value(data: DataOut, slot: int) -> float:
    # The key level of LiqState.htf slot `slot`.
    if slot == 0:
        return data.pdh
    if slot == 1:
        return data.pwh
    if slot == 2:
        return data.pmh
    if slot == 3:
        return data.pdl
    if slot == 4:
        return data.pwl
    return data.pml


def new_pool(side: int, level: float, anchor_time: float, confirmed_bar: int, source: int) -> Pool:
    no_line: Optional[LineSegment] = None
    no_label: Optional[LabelAbs] = None
    return Pool(side, level, 1, anchor_time, anchor_time, confirmed_bar, source, ST_ACTIVE, -1, no_line, no_label,
                no_line)


def pool_prefix(pools: list[Pool], n: int) -> list[Pool]:
    result: list[Pool] = []
    for i in range(n):
        result.append(pools[i])
    return result


def float_prefix(values: list[float], n: int) -> list[float]:
    result: list[float] = []
    for i in range(n):
        result.append(values[i])
    return result


def contains(values: list[float], v: float) -> bool:
    for x in values:
        if x == v:
            return True
    return False


def copy_pools(pools: list[Pool]) -> list[Pool]:
    result: list[Pool] = []
    for p in pools:
        result.append(Pool(p.side, p.level, p.touches, p.first_anchor_time, p.last_anchor_time, p.confirmed_bar,
                           p.source, p.state, p.pierced_bar, p.line, p.label, p.ghost))
    return result


def own_liq_state(st: LiqState) -> None:
    # See Main.own_state.
    st.bsl = copy_pools(st.bsl)
    st.ssl = copy_pools(st.ssl)
    htf: list[float] = []
    for v in st.htf:
        htf.append(v)
    st.htf = htf
    labels: list[LabelAbs] = []
    for lbl in st.sweep_labels:
        labels.append(lbl)
    st.sweep_labels = labels


def key_level_name(st: LiqState, pools: list[Pool], side: int, level: float) -> str:
    # The name of the key level a live key-level pool at `level` stands for, '' if none. Levels of several periods
    # can coincide (a Friday high that is also the week's high): the longest period wins.
    result = ''
    is_key = False
    for p in pools:
        if p.source == POOL_HTF and p.level == level:
            is_key = True
    if not is_key:
        return result
    # LiqState.htf order.
    names = ['PDH', 'PWH', 'PMH', 'PDL', 'PWL', 'PML']
    first = 0 if side == SIDE_BSL else 3
    for i in range(first, first + 3):
        if st.htf[i] == level:
            result = names[i]
    return result


def nearest_pool(pools: list[Pool], side: int, close: float) -> float:
    # Nearest ACTIVE pool level beyond close on the pool's side: above for buy-side, below for sell-side.
    result = nan
    for p in pools:
        if p.state != ST_ACTIVE:
            continue
        if side == SIDE_BSL and p.level >= close and (isnan(result) or p.level < result):
            result = p.level
        elif side == SIDE_SSL and p.level <= close and (isnan(result) or p.level > result):
            result = p.level
    return result


class LiquidityEngine:
    # EQH / EQL clusters, pools and sweeps (spec §3.7). Swing pools come from ev.new_swing_hi / new_swing_lo,
    # HTF pools from the pdh ... pml fields of DataOut.
    def __init__(self, ctx: Context, st: Var[LiqState], cfg: Config, draw: Draw):
        self._ctx = ctx
        self._st = st
        self._cfg = cfg
        self._draw = draw

    def own(self) -> None:
        own_liq_state(self._st.get())

    def show_all(self) -> None:
        # Draws the live pools' drawings and the sweep labels (Main.materialize).
        st = self._st.get()
        self._show_pools(st.bsl)
        self._show_pools(st.ssl)
        for lbl in st.sweep_labels:
            self._draw.new_label(lbl)

    def _show_pools(self, pools: list[Pool]) -> None:
        for p in pools:
            if p.ghost is not None:
                self._draw.new_line(p.ghost.value())
            if p.line is not None:
                self._draw.new_line(p.line.value())
            if p.label is not None:
                self._draw.new_label(p.label.value())

    def sweeps(self, k: int, ev: BarEvents, data: DataOut) -> None:
        # Runs before the bar's new pivots: only pools known before this bar can be swept by it.
        st = self._st.get()
        if self._cfg.liq_sweep_htf:
            self._sync_htf(k, st, data)
        st.bsl = self._sweep_side(k, st, st.bsl, SIDE_BSL, ev)
        st.ssl = self._sweep_side(k, st, st.ssl, SIDE_SSL, ev)

    def new_pivots(self, k: int, eq_ph: float, eq_pl: float, atr: SeriesF, ev: BarEvents, data: DataOut) -> None:
        st = self._st.get()
        cfg = self._cfg
        tol = 0.0
        if not isnan(atr[k]):
            tol = cfg.liq_eq_tol_atr * atr[k]
        if not isnan(eq_ph):
            self._eq_pivot(k, st.bsl, SIDE_BSL, eq_ph, tol, ev)
        if not isnan(eq_pl):
            self._eq_pivot(k, st.ssl, SIDE_SSL, eq_pl, tol, ev)
        if cfg.liq_sweep_swing:
            if ev.new_swing_hi is not None:
                self._swing_pool(k, st.bsl, SIDE_BSL, ev.new_swing_hi.value())
            if ev.new_swing_lo is not None:
                self._swing_pool(k, st.ssl, SIDE_SSL, ev.new_swing_lo.value())
        st.bsl = self._cap(k, st.bsl)
        st.ssl = self._cap(k, st.ssl)
        close = self._ctx.close[k]
        data.liq_bsl = nearest_pool(st.bsl, SIDE_BSL, close)
        data.liq_ssl = nearest_pool(st.ssl, SIDE_SSL, close)

    def _sync_htf(self, k: int, st: LiqState, data: DataOut) -> None:
        # A key level is a pool while its period is current: a new value replaces the previous period's pool.
        # A swept level is not registered again until the value changes.
        t = self._ctx.bar_index - k
        for i in range(HTF_SLOTS):
            old = st.htf[i]
            new = htf_value(data, i)
            if (isnan(old) and isnan(new)) or old == new:
                continue
            side = SIDE_BSL if i < 3 else SIDE_SSL
            pools = st.bsl if side == SIDE_BSL else st.ssl
            if not isnan(old):
                for j in range(len(pools)):
                    if pools[j].source == POOL_HTF and pools[j].level == old:
                        pools.pop(j)
                        break
            if not isnan(new):
                pools.append(new_pool(side, new, self._ctx.time[k], t, POOL_HTF))
            st.htf[i] = new

    def _sweep_side(self, k: int, st: LiqState, pools: list[Pool], side: int, ev: BarEvents) -> list[Pool]:
        # Wick through and close back (within liq_sweep_window bars) is a sweep; a close beyond that stays
        # beyond is a run. Either way the pool is finished. Returns the pools still live.
        ctx = self._ctx
        cfg = self._cfg
        t = ctx.bar_index - k
        close = ctx.close[k]
        # keep and labelled are allocated on the first finished pool only.
        keep = pools
        labelled = st.htf
        rebuilt = False
        for i in range(len(pools)):
            p = pools[i]
            through = ctx.high[k] > p.level if side == SIDE_BSL else ctx.low[k] < p.level
            back = close <= p.level if side == SIDE_BSL else close >= p.level
            swept = False
            done = False
            if p.state == ST_PIERCED:
                if back:
                    swept = True
                    done = True
                elif t - p.pierced_bar >= cfg.liq_sweep_window:
                    done = True
            elif through:
                if back:
                    swept = True
                    done = True
                elif cfg.liq_sweep_window == 0:
                    done = True
                else:
                    p.state = ST_PIERCED
                    p.pierced_bar = t
            if not done:
                if rebuilt:
                    keep.append(p)
                continue
            if not rebuilt:
                rebuilt = True
                keep = pool_prefix(pools, i)
                labelled = float_prefix(st.htf, 0)
            if swept and self._sweep_source(p):
                mark(ev, E_SWEEP, side)
                # Pools of several sources can share a level; one label per level and bar.
                if not contains(labelled, p.level):
                    labelled.append(p.level)
                    self._sweep_label(k, st, side, p.level, pools)
            self._finish(k, p)
        return keep

    def _sweep_source(self, p: Pool) -> bool:
        cfg = self._cfg
        if p.source == POOL_EQ:
            # A single pivot is latent liquidity: its pool lives (and dies) like the others, silently.
            return cfg.liq_sweep_eq and p.touches >= cfg.liq_eq_min_touches
        if p.source == POOL_SWING:
            return cfg.liq_sweep_swing
        return cfg.liq_sweep_htf

    def _sweep_label(self, k: int, st: LiqState, side: int, level: float, pools: list[Pool]) -> None:
        # A swept key level is named ("PWH ×", Short and Full alike, like the key-level labels), so the label reads
        # also when the level's line isn't drawn; other levels get "BSL ×" / "SSL ×" ("×").
        cfg = self._cfg
        if not cfg.liq_sweeps_show or cfg.label_text == TEXT_OFF:
            return
        bsl = side == SIDE_BSL
        text = text_for(cfg, 'BSL ×' if bsl else 'SSL ×', '×')
        name = key_level_name(st, pools, side, level)
        if name != '':
            text = name + ' ×'
        lbl = new_text_label(text, self._ctx.time[k], level, cfg.bear_color if bsl else cfg.bull_color, cfg.font,
                             bsl)
        self._draw.keep_label(lbl)
        if cfg.history:
            return
        st.sweep_labels.append(lbl)
        if len(st.sweep_labels) > POOL_CAP:
            self._draw.erase_label(st.sweep_labels[0])
            st.sweep_labels.pop(0)

    def _eq_pivot(self, k: int, pools: list[Pool], side: int, price: float, tol: float, ev: BarEvents) -> None:
        # Joins the closest ACTIVE EQ pool within tol, else starts a latent one. A pool always has every
        # member unbroken in between: it is finished as soon as price trades beyond it.
        ctx = self._ctx
        cfg = self._cfg
        t = ctx.bar_index - k
        anchor_time = ctx.time[k + cfg.liq_eq_len]
        best = -1
        best_d = 0.0
        for i in range(len(pools)):
            p = pools[i]
            if p.source == POOL_EQ and p.state == ST_ACTIVE:
                d = abs(price - p.level)
                if d <= tol and (best < 0 or d < best_d):
                    best = i
                    best_d = d
        if best < 0:
            pools.append(new_pool(side, price, anchor_time, t, POOL_EQ))
            return
        p = pools[best]
        p.touches += 1
        p.level = max(p.level, price) if side == SIDE_BSL else min(p.level, price)
        p.last_anchor_time = anchor_time
        if p.touches == cfg.liq_eq_min_touches:
            p.confirmed_bar = t
            mark(ev, E_EQ, side)
        if p.touches >= cfg.liq_eq_min_touches and cfg.liq_eq_show:
            self._draw_eq(k, p)

    def _draw_eq(self, k: int, p: Pool) -> None:
        # Dotted level from the first member (or the cluster's confirmation), extended right while live.
        ctx = self._ctx
        cfg = self._cfg
        bsl = p.side == SIDE_BSL
        col = cfg.liq_bsl_color if bsl else cfg.liq_ssl_color
        now = ctx.time[k]
        new_line = p.line is None
        if new_line:
            start = p.first_anchor_time if cfg.anchoring == A_ORIGIN else now
            p.line = LineSegment(AbsolutePosition(start, p.level),
                                 AbsolutePosition(ray_end(start), p.level),
                                 extend_type=extend_type.RIGHT, color=col, line_style=line_style.DOTTED, line_width=1)
            if cfg.anchoring == A_GHOST:
                p.ghost = LineSegment(AbsolutePosition(p.first_anchor_time, p.level), AbsolutePosition(now, p.level),
                                      color=col, line_style=line_style.DOTTED, line_width=1)
                self._draw.new_line(p.ghost.value())
        else:
            ln = p.line.value()
            start = ln.point_a.time
            ln.point_a = AbsolutePosition(start, p.level)
            ln.point_b = AbsolutePosition(ray_end(start), p.level)
        self._draw.show_line(p.line.value(), new_line)
        if cfg.label_text == TEXT_OFF:
            return
        text = text_for(cfg, 'EQH' if bsl else 'EQL', '=H' if bsl else '=L')
        if p.touches >= 3:
            text = text_for(cfg, text + ' ×' + str(p.touches), text + str(p.touches))
        when = p.last_anchor_time if cfg.anchoring == A_ORIGIN else now
        new_label = p.label is None
        if new_label:
            p.label = new_text_label(text, when, p.level, col, cfg.font, bsl)
        else:
            p.label.value().text = text
            p.label.value().position = AbsolutePosition(when, p.level)
        self._draw.show_label(p.label.value(), new_label)

    def _swing_pool(self, k: int, pools: list[Pool], side: int, sw: Swing) -> None:
        # A swing point is a sweep source only (not drawn: the structure engine shows it).
        for p in pools:
            if p.source == POOL_SWING and p.level == sw.price:
                return
        pools.append(new_pool(side, sw.price, sw.anchor_time, self._ctx.bar_index - k, POOL_SWING))

    def _cap(self, k: int, pools: list[Pool]) -> list[Pool]:
        # At most POOL_CAP EQ and swing pools per side: the farthest from close goes first. Key levels are
        # bounded by their slots.
        close = self._ctx.close[k]
        count = 0
        for p in pools:
            if p.source != POOL_HTF:
                count += 1
        while count > POOL_CAP:
            far = -1
            far_d = 0.0
            for i in range(len(pools)):
                if pools[i].source != POOL_HTF:
                    d = abs(pools[i].level - close)
                    if far < 0 or d > far_d:
                        far = i
                        far_d = d
            self._finish(k, pools[far])
            pools.pop(far)
            count -= 1
        return pools

    def _finish(self, k: int, p: Pool) -> None:
        # The pool leaves the state: Present erases its drawing, History truncates it at this bar.
        if p.line is None:
            return
        if self._cfg.history:
            ln = p.line.value()
            ln.extend_type = extend_type.NONE
            ln.point_b = AbsolutePosition(self._ctx.time[k], p.level)
            if p.ghost is not None:
                self._draw.final_line(p.ghost.value(), False)
            self._draw.final_line(ln, True)
            if p.label is not None:
                self._draw.final_label(p.label.value(), False)
            return
        self._draw.erase_line(p.line.value())
        if p.label is not None:
            self._draw.erase_label(p.label.value())
        if p.ghost is not None:
            self._draw.erase_line(p.ghost.value())


# §8 RangeEngine (premium/discount, strong/weak) -----------------------------------------------------------

# Zone of the close in the range (spec §3.9); Z_NONE until a valid range classifies a close.
Z_NONE = 2
Z_PREMIUM = 1
Z_EQ = 0
Z_DISCOUNT = -1


@dataclass
class PdState:
    zone: int
    premium: Optional[Rectangle]
    discount: Optional[Rectangle]
    eq_box: Optional[Rectangle]
    eq_line: Optional[LineSegment]
    premium_label: Optional[LabelAbs]
    eq_label: Optional[LabelAbs]
    discount_label: Optional[LabelAbs]
    drawn_top: float
    drawn_bottom: float
    drawn_left: float


def new_pd_state() -> PdState:
    no_rect: Optional[Rectangle] = None
    no_line: Optional[LineSegment] = None
    no_label: Optional[LabelAbs] = None
    return PdState(Z_NONE, no_rect, no_rect, no_rect, no_line, no_label, no_label, no_label, nan, nan, nan)


@dataclass
class RangeState:
    # Trailing swing range: reset to the swing layer's newest hi / lo, then widened by every processed bar.
    top: float
    bottom: float
    top_anchor_time: float
    bottom_anchor_time: float
    top_level: Level
    bottom_level: Level
    drawn_top: float
    drawn_bottom: float
    drawn_trend: int
    pd: PdState


def new_range_state() -> RangeState:
    no_line: Optional[LineSegment] = None
    no_label: Optional[LabelAbs] = None
    return RangeState(nan, nan, nan, nan, Level(nan, 0, nan, no_line, no_label), Level(nan, 0, nan, no_line, no_label),
                      nan, nan, 0, new_pd_state())


class RangeEngine:
    # Trailing range and strong / weak high-low (spec §3.4, §3.9). Premium / discount zones build on it.
    def __init__(self, ctx: Context, st: Var[RangeState], cfg: Config, draw: Draw):
        self._ctx = ctx
        self._st = st
        self._cfg = cfg
        self._draw = draw

    def update(self, k: int, ev: BarEvents, data: DataOut) -> None:
        ctx = self._ctx
        st = self._st.get()
        if ev.new_swing_hi is not None:
            st.top = ev.new_swing_hi.value().price
            st.top_anchor_time = ev.new_swing_hi.value().anchor_time
        if ev.new_swing_lo is not None:
            st.bottom = ev.new_swing_lo.value().price
            st.bottom_anchor_time = ev.new_swing_lo.value().anchor_time
        if not isnan(st.top) and ctx.high[k] > st.top:
            st.top = ctx.high[k]
            st.top_anchor_time = ctx.time[k]
        if not isnan(st.bottom) and ctx.low[k] < st.bottom:
            st.bottom = ctx.low[k]
            st.bottom_anchor_time = ctx.time[k]
        data.range_top = st.top
        data.range_bottom = st.bottom
        self._premium_discount(k, ev, data)

    def _premium_discount(self, k: int, ev: BarEvents, data: DataOut) -> None:
        # Always runs: pd_show only decides whether the zones are drawn (_draw_pd).
        cfg = self._cfg
        st = self._st.get()
        if isnan(st.top) or isnan(st.bottom) or st.top <= st.bottom:
            st.pd.zone = Z_NONE
            data.pd_position = nan
            return
        close = self._ctx.close[k]
        data.pd_position = (close - st.bottom) / (st.top - st.bottom)
        eq = (st.top + st.bottom) / 2
        band = pd_band(cfg, st.top, st.bottom)
        zone = Z_EQ
        if close > eq + band:
            zone = Z_PREMIUM
        elif close < eq - band:
            zone = Z_DISCOUNT
        # The first classified close only sets the zone: there is no zone it entered from.
        if zone != st.pd.zone and st.pd.zone != Z_NONE:
            if zone == Z_DISCOUNT:
                mark(ev, E_PD, BULL)
            elif zone == Z_PREMIUM:
                mark(ev, E_PD, BEAR)
        st.pd.zone = zone

    def draw_last(self, swing_trend: int) -> None:
        self._draw_strong_weak(swing_trend)
        self._draw_pd()

    def _draw_strong_weak(self, swing_trend: int) -> None:
        # Strong / weak levels describe "now", so they are drawn on the last bar only and touched on change. They
        # belong to the swing structure: hidden with it. Drawing only, nothing else reads ms_strong_weak.
        cfg = self._cfg
        if not cfg.ms_strong_weak or not cfg.ms_swing_show:
            return
        st = self._st.get()
        if st.top == st.drawn_top and st.bottom == st.drawn_bottom and swing_trend == st.drawn_trend:
            return
        if not isnan(st.top):
            strong_high = swing_trend == BEAR
            text = text_for(cfg, 'Strong High', 'Strong H') if strong_high else text_for(cfg, 'Weak High', 'Weak H')
            self._level(st.top_level, st.top, st.top_anchor_time, text, cfg.bear_color, True)
        if not isnan(st.bottom):
            strong_low = swing_trend == BULL
            text = text_for(cfg, 'Strong Low', 'Strong L') if strong_low else text_for(cfg, 'Weak Low', 'Weak L')
            self._level(st.bottom_level, st.bottom, st.bottom_anchor_time, text, cfg.bull_color, False)
        st.drawn_top = st.top
        st.drawn_bottom = st.bottom
        st.drawn_trend = swing_trend

    def _level(self, lv: Level, price: float, anchor_time: float, text: str, col: Color,
               above: bool) -> None:
        cfg = self._cfg
        a = AbsolutePosition(anchor_time, price)
        # point_b only gives the ray its direction (extended right; ray_end).
        b = AbsolutePosition(ray_end(anchor_time), price)
        new_line = lv.line is None
        if new_line:
            lv.line = LineSegment(a, b, extend_type=extend_type.RIGHT, color=col, line_style=line_style.DASHED,
                                  line_width=1)
        else:
            lv.line.value().point_a = a
            lv.line.value().point_b = b
        self._draw.show_line(lv.line.value(), new_line)
        if cfg.label_text != TEXT_OFF:
            new_label = lv.label is None
            if new_label:
                lv.label = new_text_label(text, anchor_time, price, col, cfg.font, above)
            else:
                lv.label.value().text = text
                lv.label.value().position = AbsolutePosition(anchor_time, price)
            self._draw.show_label(lv.label.value(), new_label)
        lv.price = price
        lv.anchor_time = anchor_time

    def _draw_pd(self) -> None:
        # Zones describe "now" like strong / weak: last bar only, redrawn when the range or its start moved.
        cfg = self._cfg
        if not cfg.pd_show:
            return
        st = self._st.get()
        pd = st.pd
        if isnan(st.top) or isnan(st.bottom) or st.top <= st.bottom:
            return
        left = min(st.top_anchor_time, st.bottom_anchor_time)
        if st.top == pd.drawn_top and st.bottom == pd.drawn_bottom and left == pd.drawn_left:
            return
        # The zones extend right; like the strong / weak rays they don't depend on the bar that drew them. A
        # rectangle extends by its side, so 1 s of width is enough; the equilibrium line is a ray (ray_end).
        right = left + 1
        eq = (st.top + st.bottom) / 2
        band = pd_band(cfg, st.top, st.bottom)
        pd.premium = self._zone_box(pd.premium, left, right, st.top, eq + band, cfg.pd_premium_color)
        pd.discount = self._zone_box(pd.discount, left, right, eq - band, st.bottom, cfg.pd_discount_color)
        if cfg.pd_eq_band_pct > 0:
            new_box = pd.eq_box is None
            if new_box:
                pd.eq_box = Rectangle(AbsolutePosition(left, eq + band), AbsolutePosition(right, eq - band),
                                      line_style=line_style.DOTTED, line_color=cfg.pd_eq_color,
                                      bg_color=color.TRANSPARENT, middle_line_style=line_style.DASHED,
                                      middle_line_color=cfg.pd_eq_color, extend_right=True)
            else:
                pd.eq_box.value().point_a = AbsolutePosition(left, eq + band)
                pd.eq_box.value().point_b = AbsolutePosition(right, eq - band)
            self._draw.show_rect(pd.eq_box.value(), new_box)
        else:
            new_line = pd.eq_line is None
            if new_line:
                pd.eq_line = LineSegment(AbsolutePosition(left, eq), AbsolutePosition(ray_end(left), eq),
                                         extend_type=extend_type.RIGHT, color=cfg.pd_eq_color,
                                         line_style=line_style.DASHED, line_width=1)
            else:
                pd.eq_line.value().point_a = AbsolutePosition(left, eq)
                pd.eq_line.value().point_b = AbsolutePosition(ray_end(left), eq)
            self._draw.show_line(pd.eq_line.value(), new_line)
        if cfg.label_text != TEXT_OFF:
            # Inside the zones at their left edge, clear of the strong / weak labels outside the range.
            pd.premium_label = self._zone_label(pd.premium_label, text_for(cfg, 'Premium', 'P'), left, st.top, False)
            pd.eq_label = self._zone_label(pd.eq_label, text_for(cfg, 'Equilibrium', 'EQ'), left, eq, True)
            pd.discount_label = self._zone_label(pd.discount_label, text_for(cfg, 'Discount', 'D'), left, st.bottom,
                                                 True)
        pd.drawn_top = st.top
        pd.drawn_bottom = st.bottom
        pd.drawn_left = left

    def _zone_box(self, box: Optional[Rectangle], left: float, right: float, top: float, bottom: float,
                  col: Color) -> Optional[Rectangle]:
        result = box
        created = result is None
        if created:
            result = Rectangle(AbsolutePosition(left, top), AbsolutePosition(right, bottom), line_color=color.TRANSPARENT,
                               bg_color=col, extend_right=True)
        else:
            result.value().point_a = AbsolutePosition(left, top)
            result.value().point_b = AbsolutePosition(right, bottom)
        self._draw.show_rect(result.value(), created)
        return result

    def _zone_label(self, lbl: Optional[LabelAbs], text: str, time: float, price: float,
                    above: bool) -> Optional[LabelAbs]:
        result = lbl
        created = result is None
        if created:
            result = new_text_label(text, time, price, self._cfg.text_color, self._cfg.font, above)
        else:
            result.value().position = AbsolutePosition(time, price)
        self._draw.show_label(result.value(), created)
        return result


def pd_band(cfg: Config, top: float, bottom: float) -> float:
    # Half-width of the equilibrium band; 0 makes equilibrium a line.
    return cfg.pd_eq_band_pct / 100 * (top - bottom) / 2


# §9 HtfEngine + @sec_context HtfSec ----------------------------------------------------------------------

HTF_DAY = 0
HTF_WEEK = 1
HTF_MONTH = 2
HTF_COUNT = 3
HTF_OUTPUTS = 6


@sec_context
def HtfSec(self):
    # The monthly levels on a weekly chart (a native 1M context); below 1W, KeyLevelSec serves every level.
    # Read with lookahead (spec §3.11): a history bar gets the period in effect at its open, whose [1] is the
    # previous, completed period. A live bar can already see a period that started inside it; HtfEngine.read
    # then takes [1] and [2] to stay on the period in effect at the bar's open, as history does.
    return self.time[0], self.high[1], self.low[1], self.time[1], self.high[2], self.low[2]


# Daily bars are assigned to a trading date by their time shifted by this much: a session that opens late in the
# UTC day (forex or futures on Sunday 21:00-23:00, Sydney at 23:00) belongs to the next day's week and month,
# one that opens before 18:00 UTC (US stocks 13:30, crypto 00:00) to its own UTC day.
TRADING_DATE_SHIFT = 6 * 3600
DAY_SECONDS = 86400


@dataclass
class PeriodAgg:
    # A calendar period (week or month) aggregated from daily bars, with the two periods before it. Replaced,
    # never mutated, so a rolled-back daily update can't leak into the committed one.
    key: float
    start: float
    high: float
    low: float
    complete: bool
    prev_start: float
    prev_high: float
    prev_low: float
    prev2_high: float
    prev2_low: float


def new_period_agg() -> PeriodAgg:
    return PeriodAgg(nan, nan, nan, nan, False, nan, nan, nan, nan, nan)


def trading_day(t: float) -> int:
    # Days since 1970-01-01 (a Thursday) of the trading date of a daily bar starting at t.
    return int(floor((t + TRADING_DATE_SHIFT) / DAY_SECONDS))


def week_key(day: int) -> float:
    # The Monday of the day's week (ISO weeks, Monday to Sunday), as a day number.
    return float(day - (day + 3) % 7)


def month_key(day: int) -> float:
    d = datetime.utcfromtimestamp(day * DAY_SECONDS)
    return float(d.year * 12 + d.month - 1)


def month_first_day(day: int) -> bool:
    # Whether no weekday of the month comes before this day (the 1st, or a Monday 2nd/3rd after a weekend):
    # the first month in the data starting here holds the whole month.
    d = datetime.utcfromtimestamp(day * DAY_SECONDS)
    for back in range(1, d.day):
        if (day - back + 3) % 7 < 5:
            return False
    return True


def roll_period(agg: PeriodAgg, key: float, first_day: bool, t: float, high: float, low: float) -> PeriodAgg:
    # The aggregate after the daily bar (t, high, low) of period `key`. The first period in the data is only
    # used once it is known to be whole (it starts on its first possible day); otherwise its level is NaN.
    if isnan(agg.key):
        return PeriodAgg(key, t, high, low, first_day, nan, nan, nan, nan, nan)
    if key != agg.key:
        prev_high = agg.high if agg.complete else nan
        prev_low = agg.low if agg.complete else nan
        return PeriodAgg(key, t, high, low, True, agg.start, prev_high, prev_low, agg.prev_high, agg.prev_low)
    return PeriodAgg(key, agg.start, max(agg.high, high), min(agg.low, low), agg.complete, agg.prev_start,
                     agg.prev_high, agg.prev_low, agg.prev2_high, agg.prev2_low)


class KeyLevelSec(SecContext):
    # One daily context for every key level (spec "Key levels"): the previous day as HtfSec does, and the previous
    # week and month aggregated from the daily bars. Each kind gives HTF_OUTPUTS values in HtfSec's layout: the
    # current period's start, the previous period's high and low, the previous period's start and the high and
    # low of the period before it. A period starts at its first daily bar, as a native 1W/1M bar does.
    def __init__(self):
        self._week = self.new_var(new_period_agg())
        self._month = self.new_var(new_period_agg())

    def calc(self):
        t = self.time[0]
        day = trading_day(t)
        w = roll_period(self._week.get(), week_key(day), (day + 3) % 7 == 0, t, self.high[0], self.low[0])
        self._week.set(w)
        m = roll_period(self._month.get(), month_key(day), month_first_day(day), t, self.high[0], self.low[0])
        self._month.set(m)
        return self.time[0], self.high[1], self.low[1], self.time[1], self.high[2], self.low[2], \
            w.start, w.prev_high, w.prev_low, w.prev_start, w.prev2_high, w.prev2_low, \
            m.start, m.prev_high, m.prev_low, m.prev_start, m.prev2_high, m.prev2_low


@dataclass
class HtfState:
    # Two levels per period kind, indexed 2 * kind (high) and 2 * kind + 1 (low).
    levels: list[HtfLevel]


def new_htf_state() -> HtfState:
    levels: list[HtfLevel] = []
    names = ['PDH', 'PDL', 'PWH', 'PWL', 'PMH', 'PML']
    no_line: Optional[LineSegment] = None
    no_label: Optional[LabelAbs] = None
    for i in range(len(names)):
        levels.append(HtfLevel(names[i], i % 2 == 0, nan, nan, nan, no_line, no_label, nan, nan, nan, -1, False))
    return HtfState(levels)


class HtfEngine:
    # Previous day / week / month high and low through calc_on (spec "Key levels"): KeyLevelSec or HtfSec.
    def __init__(self, ctx: Context, st: Var[HtfState], cfg: Config, draw: Draw, week: Var[PeriodAgg],
                 month: Var[PeriodAgg]):
        self._ctx = ctx
        self._st = st
        self._cfg = cfg
        self._draw = draw
        # HtfSec outputs, HTF_OUTPUTS per period kind, once attach() connected a context. The chart's close
        # stands in for a level not above the chart timeframe, so every entry is a valid series.
        self._on: list[bool] = []
        self._series: list[SeriesF] = []
        for _ in range(HTF_COUNT):
            self._on.append(False)
            for _ in range(HTF_OUTPUTS):
                self._series.append(ctx.close)
        # A chart from 1D to below 1W aggregates its own bars into the week and month (aggregate()), no context:
        # a daily one on a daily chart's own data set doesn't see the live bar, and Go misplaces a lower timeframe's
        # period starts. A multi-day bar counts for the period of its start. Per kind, the aggregate before and
        # after this calc's bar.
        self._own: list[bool] = []
        self._week = week
        self._month = month
        self._before: list[PeriodAgg] = []
        self._after: list[PeriodAgg] = []
        for _ in range(HTF_COUNT):
            self._own.append(False)
            self._before.append(new_period_agg())
            self._after.append(new_period_agg())

    def own(self) -> None:
        # See Main.own_state.
        st = self._st.get()
        levels: list[HtfLevel] = []
        for lv in st.levels:
            levels.append(HtfLevel(lv.name, lv.is_high, lv.price, lv.period_start, lv.start_time, lv.line, lv.label,
                                   lv.run_start, lv.run_extreme, lv.run_time, lv.run_bar, lv.run_full))
        st.levels = levels

    def show_all(self) -> None:
        # Draws the current key levels (Main.materialize).
        for lv in self._st.get().levels:
            if lv.line is not None:
                self._draw.new_line(lv.line.value())
            if lv.label is not None:
                self._draw.new_label(lv.label.value())

    def draw_last(self) -> None:
        # Last bar only: the current levels' names sit at the last bar (left corner on it, text to the right), off
        # the candles; the line still starts at the reference point. Redrawn on every last-bar update: the runtime
        # rolls back an unclosed update's drawing changes, but the label object in state keeps the moved position
        # (rollback aliasing), so a "position already set" check would leave the chart at the period start.
        t = self._ctx.time[0]
        for lv in self._st.get().levels:
            if lv.line is None or lv.label is None or isnan(lv.price):
                continue
            lbl = lv.label.value()
            lbl.position = AbsolutePosition(t, lv.price)
            self._draw.label(lbl)

    def attach(self, kind: int, outputs: list[SeriesF]) -> None:
        self._on[kind] = True
        for i in range(HTF_OUTPUTS):
            self._series[kind * HTF_OUTPUTS + i] = outputs[i]

    def attach_chart(self, kind: int) -> None:
        # The week or month from the chart's own (daily or multi-day) bars.
        self._own[kind] = True

    def aggregate(self) -> None:
        # Every calc, before the bar is processed: rolls the chart's bar into the week and month aggregates.
        # The state before it is the previous bar's (a catch-up reads it), the state after it this bar's.
        ctx = self._ctx
        for kind in range(HTF_COUNT):
            if self._own[kind]:
                t = ctx.time[0]
                day = trading_day(t)
                if kind == HTF_WEEK:
                    week = self._week.get()
                    self._before[kind] = week
                    week = roll_period(week, week_key(day), (day + 3) % 7 == 0, t, ctx.high[0], ctx.low[0])
                    self._week.set(week)
                    self._after[kind] = week
                else:
                    month = self._month.get()
                    self._before[kind] = month
                    month = roll_period(month, month_key(day), month_first_day(day), t, ctx.high[0], ctx.low[0])
                    self._month.set(month)
                    self._after[kind] = month

    def read(self, k: int, ev: BarEvents, data: DataOut) -> None:
        for kind in range(HTF_COUNT):
            high = nan
            low = nan
            if self._own[kind]:
                # A chart bar always starts inside its own period: no straddle.
                agg = self._after[kind] if k == 0 else self._before[kind]
                high = agg.prev_high
                low = agg.prev_low
                self._period(k, 2 * kind, agg.start, high)
                self._period(k, 2 * kind + 1, agg.start, low)
            elif self._on[kind]:
                base = kind * HTF_OUTPUTS
                start = self._series[base][k]
                high = self._series[base + 1][k]
                low = self._series[base + 2][k]
                if not isnan(start) and start > self._ctx.time[k]:
                    start = self._series[base + 3][k]
                    high = self._series[base + 4][k]
                    low = self._series[base + 5][k]
                self._period(k, 2 * kind, start, high)
                self._period(k, 2 * kind + 1, start, low)
            if kind == HTF_DAY:
                data.pdh = high
                data.pdl = low
            elif kind == HTF_WEEK:
                data.pwh = high
                data.pwl = low
            else:
                data.pmh = high
                data.pml = low

    def _period(self, k: int, index: int, start: float, price: float) -> None:
        # A new period is detected by its start time, so a period repeating the previous level still gets
        # its own line.
        lv = self._st.get().levels[index]
        extreme_time = self._track(k, lv, start, price)
        if isnan(start) or start == lv.period_start:
            return
        lv.period_start = start
        cfg = self._cfg
        t = self._ctx.time[k]
        # The line starts at the bar that made the level, or at the new period's start when that bar is unknown.
        s = t if isnan(extreme_time) else extreme_time
        if not htf_shown(cfg, index // 2):
            # A hidden level is still read (data outputs, key-level sweeps) but never drawn, so it has no line.
            lv.price = price
            lv.start_time = s
            return
        no_line: Optional[LineSegment] = None
        no_label: Optional[LabelAbs] = None
        if lv.line is not None and (cfg.history or isnan(price)):
            # The previous period's line ends here: History keeps it, truncated; with no level for the new
            # period (NaN) Present removes it, so no stale line stays extended as if it were current.
            if cfg.history:
                old = lv.line.value()
                old.point_b = AbsolutePosition(t, lv.price)
                old.extend_type = extend_type.NONE
                self._draw.final_line(old, True)
                if lv.label is not None:
                    # Back from the last bar (draw_last) to the line's start, where a history run leaves it.
                    old_label = lv.label.value()
                    old_label.position = AbsolutePosition(lv.start_time, lv.price)
                    self._draw.final_label(old_label, True)
            else:
                self._draw.erase_line(lv.line.value())
                if lv.label is not None:
                    self._draw.erase_label(lv.label.value())
            lv.line = no_line
            lv.label = no_label
        if isnan(price):
            return
        a = AbsolutePosition(s, price)
        # point_b only gives the ray its direction; the line is extended right (ray_end).
        b = AbsolutePosition(ray_end(s), price)
        created = lv.line is None
        if created:
            lv.line = LineSegment(a, b, extend_type=extend_type.RIGHT, color=cfg.htf_color,
                                  line_style=htf_line_style(cfg), line_width=1)
            # Key-level names are drawn even with label text off: the line means nothing without them.
            lv.label = new_text_label(lv.name, s, price, cfg.htf_color, cfg.font, lv.is_high)
        else:
            lv.line.value().point_a = a
            lv.line.value().point_b = b
            lv.label.value().position = a
        self._draw.show_line(lv.line.value(), created)
        self._draw.show_label(lv.label.value(), created)
        lv.price = price
        lv.start_time = s

    def _track(self, k: int, lv: HtfLevel, start: float, price: float) -> float:
        # Every processed bar: follows the high (low) of the period in effect at bar k on the chart's bars, ties to
        # the earliest bar. On the first bar of a new period it returns the time of the chart bar of the finished
        # period that made the level `price`, or NaN when that bar is unknown.
        ctx = self._ctx
        if isnan(start):
            lv.run_start = nan
            lv.run_full = False
            return nan
        v = ctx.high[k] if lv.is_high else ctx.low[k]
        if start == lv.run_start:
            if isnan(lv.run_extreme) or (v > lv.run_extreme if lv.is_high else v < lv.run_extreme):
                lv.run_extreme = v
                lv.run_time = ctx.time[k]
            return nan
        bar = ctx.bar_index - k
        extreme_time = nan
        # Unknown when the finished period began before the chart's first bar or in a stretch with no period.
        if lv.run_full and not isnan(price):
            tol = max(self._cfg.tick, 0.0) * 0.5
            if abs(lv.run_extreme - price) <= tol:
                extreme_time = lv.run_time
            else:
                # The level's source (daily or monthly bars) has another extreme than the chart's bars: another
                # feed a tick off, a chart with extended hours beyond the session's daily bar, a weekly bar across a
                # month start. Then the first bar nearest the level, if the whole period is within the lookback.
                extreme_time = self._nearest(k, bar - lv.run_bar, lv.is_high, price)
        # A run is whole when the previous bar was in an earlier period, or the first bar is at the period's start.
        lv.run_full = not isnan(lv.run_start) or ctx.time[k] <= start
        lv.run_start = start
        lv.run_extreme = v
        lv.run_time = ctx.time[k]
        lv.run_bar = bar
        return extreme_time

    def _nearest(self, k: int, n: int, is_high: bool, price: float) -> float:
        # The time of the oldest of the n bars before bar k whose high (low) is nearest `price`, NaN if they reach
        # past MAX_LOOKBACK.
        ctx = self._ctx
        if n <= 0 or k + n > MAX_LOOKBACK:
            return nan
        best = nan
        best_time = nan
        for j in range(k + n, k, -1):
            d = abs((ctx.high[j] if is_high else ctx.low[j]) - price)
            if isnan(best) or d < best:
                best = d
                best_time = ctx.time[j]
        return best_time


def htf_shown(cfg: Config, kind: int) -> bool:
    if kind == HTF_DAY:
        return cfg.htf_daily
    if kind == HTF_WEEK:
        return cfg.htf_weekly
    return cfg.htf_monthly


def htf_line_style(cfg: Config) -> line_style:
    if cfg.htf_style == 'Solid':
        return line_style.SOLID
    if cfg.htf_style == 'Dotted':
        return line_style.DOTTED
    return line_style.DASHED


# §10 Outputs: alert/data assembly, any-event OR --------------------------------------------------------------

def event_title(slot: int, bull: bool) -> str:
    # Option titles of the event outputs, two per slot (bull first) in slot order: the options of `alert_any` and,
    # per slot, of its two-option event output.
    titles = ['Bullish internal BOS', 'Bearish internal BOS', 'Bullish internal CHoCH', 'Bearish internal CHoCH',
              'Bullish swing BOS', 'Bearish swing BOS', 'Bullish swing CHoCH', 'Bearish swing CHoCH',
              'Bullish MSS', 'Bearish MSS', 'New bullish OB', 'New bearish OB',
              'Enters bullish OB / breaker', 'Enters bearish OB / breaker', 'Bullish OB mitigated',
              'Bearish OB mitigated', 'Bullish OB broken (price down)', 'Bearish OB broken (price up)',
              'New bullish FVG', 'New bearish FVG', 'Enters bullish FVG', 'Enters bearish FVG',
              'Bullish FVG filled (price down)', 'Bearish FVG filled (price up)', 'New bullish inverse FVG',
              'New bearish inverse FVG', 'Equal lows formed', 'Equal highs formed', 'Sell-side sweep (lows)',
              'Buy-side sweep (highs)', 'Enters discount', 'Enters premium']
    index = 2 * slot
    if not bull:
        index += 1
    return titles[index]


def event_option(ev: BarEvents, slot: int) -> Optional[str]:
    # The fired option of a two-option event output. When both directions fire in one update, bull wins: one
    # output can't carry both.
    result: Optional[str] = None
    if ev.bull[slot]:
        result = event_title(slot, True)
    elif ev.bear[slot]:
        result = event_title(slot, False)
    return result


def any_selected(ev: BarEvents, cfg: Config) -> Optional[str]:
    # The option of `alert_any`: the title of the first selected slot that fired, in slot order (bull first within
    # a slot), or None. Option k of `alert_any` is slot (k - 1) // 2, so the value names the event.
    slots: list[int] = []
    # Appended in slot order (E_INT_BOS < E_INT_CHOCH < E_SWING_BOS < ...): the first fired one names the event.
    if cfg.alr_any_internal:
        if cfg.alr_any_bos:
            slots.append(E_INT_BOS)
        if cfg.alr_any_choch:
            slots.append(E_INT_CHOCH)
    if cfg.alr_any_bos:
        slots.append(E_SWING_BOS)
    if cfg.alr_any_choch:
        slots.append(E_SWING_CHOCH)
        slots.append(E_MSS)
    if cfg.alr_any_ob_new:
        slots.append(E_OB_NEW)
    if cfg.alr_any_ob_enter:
        slots.append(E_OB_ENTER)
    if cfg.alr_any_ob_mitigated:
        slots.append(E_OB_MITIGATED)
    if cfg.alr_any_ob_broken:
        slots.append(E_OB_BROKEN)
    if cfg.alr_any_fvg_new:
        slots.append(E_FVG_NEW)
    if cfg.alr_any_fvg_enter:
        slots.append(E_FVG_ENTER)
    if cfg.alr_any_fvg_filled:
        slots.append(E_FVG_FILLED)
    if cfg.alr_any_ifvg:
        slots.append(E_IFVG)
    if cfg.alr_any_eq:
        slots.append(E_EQ)
    if cfg.alr_any_sweep:
        slots.append(E_SWEEP)
    if cfg.alr_any_pd:
        slots.append(E_PD)
    # The direction is the signal's bias, which is the slot's side except for a zone that failed: a bullish OB
    # broken or a bullish FVG filled is price moving down, so it counts as bearish (and the bearish ones as bullish).
    use_bull = cfg.alr_any_direction != 'Bearish'
    use_bear = cfg.alr_any_direction != 'Bullish'
    # The title stays the fired option's own ("Bullish OB broken (price down)"), only the filter uses the bias.
    for slot in slots:
        allow_bull_side = use_bull
        allow_bear_side = use_bear
        if slot == E_OB_BROKEN or slot == E_FVG_FILLED:
            allow_bull_side = use_bear
            allow_bear_side = use_bull
        if allow_bull_side and ev.bull[slot]:
            return event_title(slot, True)
        if allow_bear_side and ev.bear[slot]:
            return event_title(slot, False)
    return None


def trend_color(cfg: Config, swing_trend: int, internal_trend: int) -> Optional[Color]:
    result: Optional[Color] = None
    if cfg.ms_candle_color == 'Internal':
        if internal_trend != 0:
            result = cfg.int_bull_color if internal_trend == BULL else cfg.int_bear_color
    elif swing_trend != 0:
        result = cfg.bull_color if swing_trend == BULL else cfg.bear_color
    return result


# §11 Main(MainContext): decorators, __init__, calc --------------------------------------------------------

@indicator('SMC', overlay_main_pane=True)
# Inputs: with a preset other than Custom the dialog shows only the inputs presets never set (Preset, Mode, Style,
# Alerts); show_if=CUSTOM hides the rest, which then come from the preset (apply_preset), not from the user.
# Within Custom, a feature's options show only while the feature is on. Input defaults equal the Standard preset.
# The show toggles (structure, order blocks, FVGs, inverse FVGs, equal highs / lows, sweeps, premium / discount, key
# levels) only decide what is drawn: detection always runs, so every alert and data output works under every setting.
# General
@param.str('gen_preset', default='Standard', options=['Standard', 'Structure', 'ICT Strict', 'Scalper', 'Full', 'Custom'],
           title='Preset', group=G_GEN,
           tooltip='What is drawn and how it is detected. Standard: swing structure, the nearest order blocks, the '
                   'last FVGs, previous day high / low. Structure: structure and key levels only. ICT Strict / '
                   'Scalper / Full: see the docs. Custom: every input. Every alert works under every preset, also for '
                   "what isn't drawn.")
@param.str('gen_mode', default='Present', options=['Present', 'History'], title='Mode', group=G_GEN,
           tooltip='Present: live objects, plus the last N finished structure breaks per layer (N: "Present mode: '
                   'last structure breaks per layer") and their swing labels. History: finished objects stay, faded.')
@param.str('gen_anchoring', default='At origin', options=['At origin', 'At confirmation', 'At confirmation + ghost'],
           title='Draw objects from', group=G_GEN, show_if=CUSTOM,
           tooltip='Where an object starts. "At confirmation" shows only what was known on each bar.')
@param.str('gen_definitions', default='Classic', options=['Classic', 'Strict ICT'], title='Definitions', group=G_GEN,
           show_if=CUSTOM,
           tooltip='Strict ICT: MSS and OBs require a liquidity sweep; FVG middle candle must close in direction.')
@param.int('gen_atr_len', default=14, min=1, max=500, title='ATR length (for thresholds)', group=G_GEN,
           show_if=CUSTOM)
# Market structure
@param.bool('ms_swing_show', default=True, title='Swing structure', group=G_MS, show_if=CUSTOM)
@param.int('ms_swing_left', default=50, min=2, max=500, title='Swing pivot: left bars', group=G_MS,
           show_if='ms_swing_show')
@param.int('ms_swing_right', default=10, min=1, max=500, title='Swing pivot: right bars (confirmation lag)', group=G_MS,
           show_if='ms_swing_show')
@param.str('ms_swing_filter', default='All', options=['All', 'BOS', 'CHoCH'], title='Swing: show', group=G_MS,
           show_if='ms_swing_show')
@param.bool('ms_swing_labels', default=False, title='Swing labels HH / HL / LH / LL', group=G_MS,
            show_if='ms_swing_show')
@param.bool('ms_strong_weak', default=True, title='Strong / weak high and low', group=G_MS, show_if='ms_swing_show',
            tooltip="Strong high/low: the swing that produced the current trend's structure (protected). Weak: the "
                    "opposite swing, the trend's next target. Part of the swing structure: hidden while it is off.")
@param.bool('ms_int_show', default=False, title='Internal structure', group=G_MS, show_if=CUSTOM)
@param.int('ms_int_left', default=5, min=1, max=100, title='Internal pivot: left bars', group=G_MS,
           show_if='ms_int_show')
@param.int('ms_int_right', default=5, min=1, max=100, title='Internal pivot: right bars (confirmation lag)', group=G_MS,
           show_if='ms_int_show')
@param.str('ms_int_filter', default='All', options=['All', 'BOS', 'CHoCH'], title='Internal: show', group=G_MS,
           show_if='ms_int_show')
@param.bool('ms_int_hide_at_swing', default=True, title='Hide internal breaks at swing levels', group=G_MS,
            show_if='ms_int_show')
@param.str('ms_confirm', default='Close', options=['Close', 'Wick'], title='Break confirmed by', group=G_MS,
           show_if=CUSTOM)
@param.float('ms_break_buffer_atr', default=0.0, min=0.0, max=5.0, step=0.05, title='Break buffer (× ATR)', group=G_MS,
             show_if=CUSTOM)
@param.float('ms_mss_disp_atr', default=1.0, min=0.0, max=10.0, step=0.1, title='MSS displacement: body ≥ (× ATR)',
             group=G_MS, show_if=CUSTOM)
@param.bool('ms_choch_plus', default=True, title='Mark CHoCH+', group=G_MS, show_if=CUSTOM)
@param.int('ms_max_events', default=3, min=1, max=50, title='Present mode: last structure breaks per layer', group=G_MS,
           show_if=CUSTOM)
# Order blocks
@param.bool('ob_swing_show', default=True, title='Swing order blocks', group=G_OB, show_if=CUSTOM)
@param.int('ob_swing_last', default=5, min=1, max=10, title='Swing: keep last (per direction)', group=G_OB,
           show_if='ob_swing_show',
           tooltip='Older order blocks are dropped. When "Show nearest 2 within (× ATR, 0 = all)" is above 0, these '
                   'are the candidates; only the nearest 2 per side are drawn.')
@param.bool('ob_int_show', default=True, title='Internal order blocks', group=G_OB, show_if=CUSTOM)
@param.int('ob_int_last', default=5, min=1, max=10, title='Internal: keep last (per direction)', group=G_OB,
           show_if='ob_int_show',
           tooltip='Older order blocks are dropped. When "Show nearest 2 within (× ATR, 0 = all)" is above 0, these '
                   'are the candidates; only the nearest 2 per side are drawn.')
@param.str('ob_type', default='Last opposite candle', options=['Last opposite candle', 'Leg extreme'],
           title='Order block candle', group=G_OB, show_if=CUSTOM)
@param.bool('ob_require_displacement', default=False, title='Only after displacement', group=G_OB, show_if=CUSTOM)
@param.str('ob_mitigation', default='Wick', options=['Wick', 'Close', '50%'],
           title='Mitigated when price reaches it by', group=G_OB, show_if=CUSTOM)
@param.str('ob_mitigated_action', default='Keep', options=['Keep', 'Recolor', 'Hide'],
           title='Mitigated order blocks', group=G_OB, show_if=CUSTOM)
@param.str('ob_invalidation', default='Close', options=['Close', 'Wick'], title='Invalidated by', group=G_OB,
           show_if=CUSTOM)
@param.bool('ob_breakers', default=False, title='Invalidated OB becomes breaker', group=G_OB, show_if=CUSTOM)
@param.str('ob_overlap', default='Hide older', options=['Keep all', 'Hide older'], title='Overlapping order blocks',
           group=G_OB, show_if=CUSTOM)
@param.bool('ob_show_mid', default=False, title='50% line', group=G_OB, show_if=CUSTOM)
@param.float('ob_max_dist_atr', default=8.0, min=0.0, max=100.0, step=0.5,
             title='Show nearest 2 within (× ATR, 0 = all)', group=G_OB, show_if=CUSTOM,
             tooltip='Draw only the 2 order blocks per side nearest to the close, and none farther than this many '
                     'ATRs. Alerts and data outputs still see every kept block. 0: draw every kept block.')
# Fair value gaps
@param.bool('fvg_show', default=True, title='Fair value gaps', group=G_FVG, show_if=CUSTOM)
@param.float('fvg_threshold_atr', default=0.5, min=0.0, max=5.0, step=0.05, title='Minimum size (× ATR, 0 = any)',
             group=G_FVG, show_if='fvg_show')
@param.int('fvg_last', default=2, min=1, max=15, title='Keep last unfilled (per direction)', group=G_FVG,
           show_if='fvg_show')
@param.str('fvg_fill', default='Wick (full)', options=['Wick (full)', 'Close (full)', 'CE (50%)'], title='Filled when',
           group=G_FVG, show_if='fvg_show')
@param.bool('fvg_shrink', default=True, title='Shrink as it fills', group=G_FVG, show_if='fvg_show')
@param.bool('fvg_ce', default=False, title='CE (50%) line', group=G_FVG, show_if='fvg_show')
@param.bool('fvg_ifvg', default=False, title='Show inverse FVGs', group=G_FVG, show_if='fvg_show')
# Liquidity
@param.bool('liq_eq_show', default=False, title='Equal highs / lows', group=G_LIQ, show_if=CUSTOM)
@param.int('liq_eq_len', default=3, min=1, max=50, title='Equal highs / lows pivot bars', group=G_LIQ,
           show_if='liq_eq_show')
@param.float('liq_eq_tol_atr', default=0.1, min=0.0, max=2.0, step=0.01, title='Equal within (× ATR)', group=G_LIQ,
             show_if='liq_eq_show')
@param.int('liq_eq_min_touches', default=2, min=2, max=10, title='Minimum touches', group=G_LIQ,
           show_if='liq_eq_show')
@param.bool('liq_sweeps_show', default=False, title='Liquidity sweeps', group=G_LIQ, show_if=CUSTOM)
@param.int('liq_sweep_window', default=0, min=0, max=3, title='Close back inside within (bars, 0 = same bar)',
           group=G_LIQ, show_if='liq_sweeps_show')
@param.bool('liq_sweep_eq', default=True, title='Sweeps of equal highs / lows', group=G_LIQ,
            show_if='liq_sweeps_show',
            tooltip='Which levels count for the sweep alert and labels. All three off counts as all three on (the '
                    'sweep alert never goes silent).')
@param.bool('liq_sweep_swing', default=True, title='Sweeps of swing points', group=G_LIQ, show_if='liq_sweeps_show',
            tooltip='Which levels count for the sweep alert and labels. All three off counts as all three on (the '
                    'sweep alert never goes silent).')
@param.bool('liq_sweep_htf', default=True, title='Sweeps of key levels', group=G_LIQ, show_if='liq_sweeps_show',
            tooltip='Which levels count for the sweep alert and labels. All three off counts as all three on (the '
                    'sweep alert never goes silent).')
# Premium / discount
@param.bool('pd_show', default=False, title='Premium / discount zones', group=G_PD, show_if=CUSTOM)
@param.float('pd_eq_band_pct', default=0.0, min=0.0, max=20.0, step=0.5,
             title='Equilibrium band (% of range, 0 = line)', group=G_PD, show_if='pd_show')
# Key levels
@param.bool('htf_daily', default=True, title='Previous day high / low', group=G_HTF, show_if=CUSTOM)
@param.bool('htf_weekly', default=False, title='Previous week high / low', group=G_HTF, show_if=CUSTOM)
@param.bool('htf_monthly', default=False, title='Previous month high / low', group=G_HTF, show_if=CUSTOM)
@param.str('htf_style', default='Dashed', options=['Solid', 'Dashed', 'Dotted'], title='Line style', group=G_HTF,
           show_if=CUSTOM)
# Style: label size and text, the bullish and bearish colors and the candle trend are never set by presets. The other
# colors are derived from these (lighter fills) or are Custom inputs.
@param.str('sty_label_text', default='Short', options=['Off', 'Short', 'Full'], title='Label text', group=G_STY,
           tooltip='Short: abbreviated labels, no labels on order blocks and FVGs. Full: every label. Key levels read '
                   'PDH … PML in every mode.')
@param.str('sty_label_size', default='Small', options=['Tiny', 'Small', 'Normal', 'Large'], title='Label size',
           group=G_STY)
@param.color('sty_bull_color', default=color.rgba(8, 153, 129, 1.0), title='Bullish', group=G_STY)
@param.color('sty_bear_color', default=color.rgba(242, 54, 69, 1.0), title='Bearish', group=G_STY)
@param.str('ms_candle_color', default='Swing', options=['Swing', 'Internal'], title='Candle trend', group=G_STY,
           tooltip='Which trend colors the candles. Turn the coloring on or off with the "Trend candles" output '
                   '(hidden by default).')
@param.color('sty_fvg_bull_color', default=color.rgba(0, 188, 212, 0.25), title='Bullish FVG', group=G_STY,
             show_if='fvg_show')
@param.color('sty_fvg_bear_color', default=color.rgba(233, 30, 99, 0.25), title='Bearish FVG', group=G_STY,
             show_if='fvg_show')
@param.color('sty_neutral_color', default=color.rgba(128, 128, 128, 1.0), title='Neutral', group=G_STY,
             show_if=CUSTOM,
             tooltip='Key levels, label text, mitigated order blocks, equilibrium.')
# Alerts: what feeds the "any selected event" output; presets set only alr_any_internal. Every event also has its
# own output.
@param.str('alr_any_events', default='Structure breaks + zone entry',
           options=['Structure breaks + zone entry', 'Structure breaks', 'Zone entry', 'Liquidity', 'All events',
                    'Custom'],
           title='Any-event alert: events', group=G_ALR,
           tooltip='Structure breaks: BOS, CHoCH, MSS (swing; internal too under ICT Strict, Scalper, Full, or Custom '
                   'with "include internal BOS / CHoCH"). Zone entry: price enters an order block or FVG. Liquidity: '
                   'equal highs / lows, sweeps. Custom: pick events one by one.')
@param.str('alr_any_direction', default='Both', options=['Both', 'Bullish', 'Bearish'],
           title='Any-event alert: direction', group=G_ALR,
           tooltip="The signal's bias. Bullish: bullish BOS / CHoCH / MSS, a new or entered bullish OB or FVG, a "
                   'bullish OB mitigated, a bearish OB broken or bearish FVG filled (price up), a new bullish inverse '
                   'FVG, equal lows, a sell-side sweep, entering discount. Bearish: the opposite.')
@param.bool('alr_any_internal', default=False, title='Any-event alert: include internal BOS / CHoCH', group=G_ALR,
            show_if=CUSTOM,
            tooltip='Internal BOS / CHoCH also feed the any-event alert (its BOS and CHoCH events, family or Custom), '
                    'whether or not internal structure is drawn. Presets: off for Standard and Structure, on for the '
                    'others.')
@param.bool('alr_any_bos', default=True, title='… BOS', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_choch', default=True, title='… CHoCH / CHoCH+ / MSS', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_ob_new', default=False, title='… new order block', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_ob_enter', default=True, title='… price enters an order block', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_ob_mitigated', default=False, title='… order block mitigated', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_ob_broken', default=False, title='… order block broken', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_fvg_new', default=False, title='… new FVG', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_fvg_enter', default=True, title='… price enters an FVG', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_fvg_filled', default=False, title='… FVG filled', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_ifvg', default=False, title='… inverse FVG', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_eq', default=False, title='… equal highs / lows formed', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_sweep', default=False, title='… liquidity sweep', group=G_ALR, show_if=ALR_CUSTOM)
@param.bool('alr_any_pd', default=False, title='… enters premium / discount', group=G_ALR, show_if=ALR_CUSTOM)
# Outputs: trend candles, then the alert events, then data outputs. An event with two options returns the first
# (bullish, series 1), the second (bearish, series 2) or None (0). For liquidity and zones the first option is the
# lower side (equal lows, sell-side sweep, discount); for OB / FVG it is the zone's polarity, and the two that are
# price moves against the zone say so ("Bullish OB broken (price down)"). `alert_any` has all 32 options in slot
# order (bull first): its value names the first selected event that fired.
# Every output is computed under every preset and setting (spec "The alert rule": show toggles only hide drawings).
# Trend candles: hidden by default (pane=False); its visibility is the on/off switch for candle coloring, the Style
# input "Candle trend" picks the trend. No alert role.
@plot.bar_color(title='Trend candles', display_options=plot.BarColorDisplayOptions(pane=False))
@plot.event('alert_int_bos', title='Internal BOS', options=['Bullish internal BOS', 'Bearish internal BOS'])
@plot.event('alert_int_choch', title='Internal CHoCH', options=['Bullish internal CHoCH', 'Bearish internal CHoCH'])
@plot.event('alert_swing_bos', title='Swing BOS', options=['Bullish swing BOS', 'Bearish swing BOS'])
@plot.event('alert_swing_choch', title='Swing CHoCH', options=['Bullish swing CHoCH', 'Bearish swing CHoCH'])
@plot.event('alert_mss', title='MSS', options=['Bullish MSS', 'Bearish MSS'])
@plot.event('alert_ob_new', title='New order block', options=['New bullish OB', 'New bearish OB'])
@plot.event('alert_ob_enter', title='Price enters order block',
            options=['Enters bullish OB / breaker', 'Enters bearish OB / breaker'])
@plot.event('alert_ob_mitigated', title='Order block mitigated',
            options=['Bullish OB mitigated', 'Bearish OB mitigated'])
@plot.event('alert_ob_broken', title='Order block broken',
            options=['Bullish OB broken (price down)', 'Bearish OB broken (price up)'])
@plot.event('alert_fvg_new', title='New FVG', options=['New bullish FVG', 'New bearish FVG'])
@plot.event('alert_fvg_enter', title='Price enters FVG', options=['Enters bullish FVG', 'Enters bearish FVG'])
@plot.event('alert_fvg_filled', title='FVG filled',
            options=['Bullish FVG filled (price down)', 'Bearish FVG filled (price up)'])
@plot.event('alert_ifvg', title='New inverse FVG', options=['New bullish inverse FVG', 'New bearish inverse FVG'])
@plot.event('alert_eq', title='Equal highs / lows', options=['Equal lows formed', 'Equal highs formed'])
@plot.event('alert_sweep', title='Liquidity sweep', options=['Sell-side sweep (lows)', 'Buy-side sweep (highs)'])
@plot.event('alert_pd', title='Premium / discount', options=['Enters discount', 'Enters premium'])
@plot.event('alert_any', title='Any selected event',
            options=['Bullish internal BOS', 'Bearish internal BOS', 'Bullish internal CHoCH',
                     'Bearish internal CHoCH', 'Bullish swing BOS', 'Bearish swing BOS', 'Bullish swing CHoCH',
                     'Bearish swing CHoCH', 'Bullish MSS', 'Bearish MSS', 'New bullish OB', 'New bearish OB',
                     'Enters bullish OB / breaker', 'Enters bearish OB / breaker', 'Bullish OB mitigated',
                     'Bearish OB mitigated', 'Bullish OB broken (price down)', 'Bearish OB broken (price up)',
                     'New bullish FVG', 'New bearish FVG', 'Enters bullish FVG', 'Enters bearish FVG',
                     'Bullish FVG filled (price down)', 'Bearish FVG filled (price up)', 'New bullish inverse FVG',
                     'New bearish inverse FVG', 'Equal lows formed', 'Equal highs formed', 'Sell-side sweep (lows)',
                     'Buy-side sweep (highs)', 'Enters discount', 'Enters premium'])
@plot.data('trend_swing', title='Swing trend (+1 / −1 / 0)')
@plot.data('trend_internal', title='Internal trend (+1 / −1 / 0)')
@plot.data('range_top', title='Range top')
@plot.data('range_bottom', title='Range bottom')
@plot.data('pd_position', title='Position in range (0 bottom, 1 top)')
@plot.data('ob_bull_top', title='Nearest bullish order block top')
@plot.data('ob_bear_bottom', title='Nearest bearish order block bottom')
@plot.data('fvg_bull_top', title='Nearest bullish FVG top (unfilled)')
@plot.data('fvg_bear_bottom', title='Nearest bearish FVG bottom (unfilled)')
@plot.data('liq_bsl', title='Nearest buy-side liquidity')
@plot.data('liq_ssl', title='Nearest sell-side liquidity')
@plot.data('pdh', title='Previous day high')
@plot.data('pdl', title='Previous day low')
@plot.data('pwh', title='Previous week high')
@plot.data('pwl', title='Previous week low')
@plot.data('pmh', title='Previous month high')
@plot.data('pml', title='Previous month low')
class Main(MainContext):
    def __init__(self, gen_preset, gen_mode, gen_anchoring, gen_definitions, gen_atr_len,
                 ms_swing_show, ms_swing_left, ms_swing_right, ms_swing_filter, ms_swing_labels, ms_strong_weak,
                 ms_int_show, ms_int_left, ms_int_right, ms_int_filter, ms_int_hide_at_swing,
                 ms_confirm, ms_break_buffer_atr, ms_mss_disp_atr, ms_choch_plus, ms_max_events,
                 ob_swing_show, ob_swing_last, ob_int_show, ob_int_last, ob_type, ob_require_displacement,
                 ob_mitigation, ob_mitigated_action, ob_invalidation, ob_breakers, ob_overlap, ob_show_mid,
                 ob_max_dist_atr,
                 fvg_show, fvg_threshold_atr, fvg_last, fvg_fill, fvg_shrink, fvg_ce, fvg_ifvg,
                 liq_eq_show, liq_eq_len, liq_eq_tol_atr, liq_eq_min_touches, liq_sweeps_show, liq_sweep_window,
                 liq_sweep_eq, liq_sweep_swing, liq_sweep_htf,
                 pd_show, pd_eq_band_pct,
                 htf_daily, htf_weekly, htf_monthly, htf_style,
                 sty_label_text, sty_label_size, sty_bull_color, sty_bear_color, ms_candle_color,
                 sty_fvg_bull_color, sty_fvg_bear_color, sty_neutral_color,
                 alr_any_events, alr_any_direction, alr_any_internal, alr_any_bos, alr_any_choch, alr_any_ob_new,
                 alr_any_ob_enter, alr_any_ob_mitigated, alr_any_ob_broken, alr_any_fvg_new, alr_any_fvg_enter,
                 alr_any_fvg_filled, alr_any_ifvg, alr_any_eq, alr_any_sweep, alr_any_pd):
        cfg = Config()
        cfg.preset = gen_preset
        if gen_preset == 'Custom':
            # Only Custom reads the inputs behind show_if=CUSTOM; a preset sets them (apply_preset).
            cfg.anchoring = A_ORIGIN
            if gen_anchoring == 'At confirmation':
                cfg.anchoring = A_CONFIRM
            elif gen_anchoring == 'At confirmation + ghost':
                cfg.anchoring = A_GHOST
            cfg.strict = gen_definitions == 'Strict ICT'
            cfg.atr_len = gen_atr_len

            cfg.ms_int_show = ms_int_show
            cfg.ms_int_left = ms_int_left
            cfg.ms_int_right = ms_int_right
            cfg.ms_int_filter = ms_int_filter
            cfg.ms_int_hide_at_swing = ms_int_hide_at_swing
            cfg.ms_swing_show = ms_swing_show
            cfg.ms_swing_left = ms_swing_left
            cfg.ms_swing_right = ms_swing_right
            cfg.ms_swing_filter = ms_swing_filter
            cfg.ms_confirm_close = ms_confirm == 'Close'
            cfg.ms_break_buffer_atr = ms_break_buffer_atr
            cfg.ms_mss_disp_atr = ms_mss_disp_atr
            cfg.ms_choch_plus = ms_choch_plus
            cfg.ms_swing_labels = ms_swing_labels
            cfg.ms_strong_weak = ms_strong_weak
            cfg.ms_max_events = ms_max_events

            cfg.ob_int_show = ob_int_show
            cfg.ob_int_last = ob_int_last
            cfg.ob_swing_show = ob_swing_show
            cfg.ob_swing_last = ob_swing_last
            cfg.ob_max_dist_atr = ob_max_dist_atr
            cfg.ob_leg_extreme = ob_type == 'Leg extreme'
            cfg.ob_require_displacement = ob_require_displacement
            cfg.ob_mitigation = ob_mitigation
            cfg.ob_mitigated_action = ob_mitigated_action
            cfg.ob_invalidation_close = ob_invalidation == 'Close'
            cfg.ob_breakers = ob_breakers
            cfg.ob_hide_older = ob_overlap == 'Hide older'
            cfg.ob_show_mid = ob_show_mid

            cfg.fvg_show = fvg_show
            cfg.fvg_threshold_atr = fvg_threshold_atr
            cfg.fvg_last = fvg_last
            cfg.fvg_fill = fvg_fill
            cfg.fvg_shrink = fvg_shrink
            cfg.fvg_ce = fvg_ce
            cfg.fvg_ifvg = fvg_ifvg

            cfg.liq_eq_show = liq_eq_show
            cfg.liq_eq_len = liq_eq_len
            cfg.liq_eq_tol_atr = liq_eq_tol_atr
            cfg.liq_eq_min_touches = liq_eq_min_touches
            cfg.liq_sweeps_show = liq_sweeps_show
            cfg.liq_sweep_window = liq_sweep_window
            # All three sources off means all three on, so alert_sweep always has something to sweep.
            any_source = liq_sweep_eq or liq_sweep_swing or liq_sweep_htf
            cfg.liq_sweep_eq = liq_sweep_eq or not any_source
            cfg.liq_sweep_swing = liq_sweep_swing or not any_source
            cfg.liq_sweep_htf = liq_sweep_htf or not any_source

            cfg.pd_show = pd_show
            cfg.pd_eq_band_pct = pd_eq_band_pct

            cfg.htf_daily = htf_daily
            cfg.htf_weekly = htf_weekly
            cfg.htf_monthly = htf_monthly
            cfg.htf_style = htf_style

            cfg.fvg_bull_color = sty_fvg_bull_color
            cfg.fvg_bear_color = sty_fvg_bear_color
            cfg.neutral_color = sty_neutral_color
            cfg.alr_any_internal = alr_any_internal
        else:
            apply_preset(cfg, gen_preset)

        # Inputs shown under every preset.
        cfg.history = gen_mode == 'History'
        cfg.ms_candle_color = ms_candle_color
        cfg.label_size = sty_label_size
        cfg.label_text = TEXT_FULL
        if sty_label_text == 'Off':
            cfg.label_text = TEXT_OFF
        elif sty_label_text == 'Short':
            cfg.label_text = TEXT_SHORT
        cfg.bull_color = sty_bull_color
        cfg.bear_color = sty_bear_color

        cfg.alr_any_direction = alr_any_direction
        cfg.alr_any_bos = alr_any_bos
        cfg.alr_any_choch = alr_any_choch
        cfg.alr_any_ob_new = alr_any_ob_new
        cfg.alr_any_ob_enter = alr_any_ob_enter
        cfg.alr_any_ob_mitigated = alr_any_ob_mitigated
        cfg.alr_any_ob_broken = alr_any_ob_broken
        cfg.alr_any_fvg_new = alr_any_fvg_new
        cfg.alr_any_fvg_enter = alr_any_fvg_enter
        cfg.alr_any_fvg_filled = alr_any_fvg_filled
        cfg.alr_any_ifvg = alr_any_ifvg
        cfg.alr_any_eq = alr_any_eq
        cfg.alr_any_sweep = alr_any_sweep
        cfg.alr_any_pd = alr_any_pd
        set_alert_events(cfg, alr_any_events)

        finish_config(cfg)
        self._cfg = cfg

        self._draw = Draw(self.chart, self.new_var(new_draw_queue()), cfg.history)
        self._data = self.new_var(new_data_out())
        # Index of the last bar whose closed state was processed (catch-up, spec §3.1).
        self._last_done = self.new_var(-1)
        # Whether the drawings held during history were drawn (materialize); both modes.
        self._shown = self.new_var(False)
        self._htf = HtfEngine(self, self.new_var(new_htf_state()), cfg, self._draw, self.new_var(new_period_agg()),
                              self.new_var(new_period_agg()))
        # Exactly one secondary context for the key levels below 1M (spec "Key levels"), whatever is shown: every
        # level is read under every preset (data outputs, key-level sweeps), and htf_daily / htf_weekly / htf_monthly
        # only decide which are drawn. Below 1D a daily one serves the day, week and month; from 1D to below 1W the
        # chart's own bars give the week and month (no context); on a weekly chart a monthly one serves the month.
        # A level not above the chart timeframe stays NaN.
        tf = self.time_frame
        if tf >= TimeFrame.from_str('1D') and tf < TimeFrame.from_str('1W'):
            self._htf.attach_chart(HTF_WEEK)
            self._htf.attach_chart(HTF_MONTH)
        elif tf < TimeFrame.from_str('1D'):
            k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17 = self.calc_on(
                KeyLevelSec, time_frame=TimeFrame.from_str('1D'), lookahead=True)
            self._htf.attach(HTF_DAY, [k0, k1, k2, k3, k4, k5])
            self._htf.attach(HTF_WEEK, [k6, k7, k8, k9, k10, k11])
            self._htf.attach(HTF_MONTH, [k12, k13, k14, k15, k16, k17])
        elif tf < TimeFrame.from_str('1M'):
            m0, m1, m2, m3, m4, m5 = self.calc_on(HtfSec, time_frame=TimeFrame.from_str('1M'), lookahead=True)
            self._htf.attach(HTF_MONTH, [m0, m1, m2, m3, m4, m5])
        self._fvg = FvgEngine(self, self.new_var(new_fvg_state()), cfg, self._draw)
        self._liq = LiquidityEngine(self, self.new_var(new_liq_state()), cfg, self._draw)
        self._struct = StructureEngine(self, self.new_var(new_struct_state()), cfg, self._draw)
        self._ob = ObEngine(self, self.new_var(new_ob_state()), cfg, self._draw)
        self._range = RangeEngine(self, self.new_var(new_range_state()), cfg, self._draw)

    def pre_calc(self):
        self._cfg.price_precision = self.info.price_precision
        self._cfg.tick = self.info.tick_size

    def calc(self):
        cfg = self._cfg
        _ = self.time[MAX_LOOKBACK + 1]
        _ = self.open[MAX_LOOKBACK + 1]
        _ = self.high[MAX_LOOKBACK + 1]
        _ = self.low[MAX_LOOKBACK + 1]
        _ = self.close[MAX_LOOKBACK + 1]
        _ = self.volume[MAX_LOOKBACK + 1]

        atr = Atr.new(cfg.atr_len)
        _ = atr[MAX_LOOKBACK + 1]
        # PivotHighLow returns (pivot highs, pivot lows) of its source; only one side of each call is used.
        int_ph, int_unused_l = PivotHighLow.new(self.high, cfg.ms_int_left, cfg.ms_int_right)
        int_unused_h, int_pl = PivotHighLow.new(self.low, cfg.ms_int_left, cfg.ms_int_right)
        swing_ph, swing_unused_l = PivotHighLow.new(self.high, cfg.ms_swing_left, cfg.ms_swing_right)
        swing_unused_h, swing_pl = PivotHighLow.new(self.low, cfg.ms_swing_left, cfg.ms_swing_right)
        eq_ph, eq_unused_l = PivotHighLow.new(self.high, cfg.liq_eq_len, cfg.liq_eq_len)
        eq_unused_h, eq_pl = PivotHighLow.new(self.low, cfg.liq_eq_len, cfg.liq_eq_len)

        self._draw.begin(self.bar_index, self.is_history)
        self._htf.aggregate()
        if not self._shown.get():
            if self._before_tail():
                self._draw.hold = True
            else:
                self.materialize()
                self._shown.set(True)
        ev = new_bar_events()
        data = self._data.get()
        catch_up = self.bar_index - 1 > self._last_done.get()
        # Catch-ups are rare and may run on the first tick after a commit, whose Go backup shares the records.
        if catch_up or (self._draw.same_bar and self.is_closed_bar):
            self.own_state()
        # Catch-up: the previous bar never got a closed update, so its events are emitted on this bar.
        if catch_up:
            self._process_bar(1, atr, int_ph[1], int_pl[1], swing_ph[1], swing_pl[1], eq_ph[1], eq_pl[1], ev, data)
            self._last_done.set(self.bar_index - 1)
        if self.is_closed_bar:
            self._process_bar(0, atr, int_ph[0], int_pl[0], swing_ph[0], swing_pl[0], eq_ph[0], eq_pl[0], ev, data)
            self._last_done.set(self.bar_index)

        swing_trend = self._struct.trend(L_SWING)
        if self.is_last_bar:
            self._range.draw_last(swing_trend)
            self._htf.draw_last()

        return (
            plot.BarColor(trend_color(cfg, swing_trend, self._struct.trend(L_INT))),
            event_option(ev, E_INT_BOS),
            event_option(ev, E_INT_CHOCH),
            event_option(ev, E_SWING_BOS),
            event_option(ev, E_SWING_CHOCH),
            event_option(ev, E_MSS),
            event_option(ev, E_OB_NEW),
            event_option(ev, E_OB_ENTER),
            event_option(ev, E_OB_MITIGATED),
            event_option(ev, E_OB_BROKEN),
            event_option(ev, E_FVG_NEW),
            event_option(ev, E_FVG_ENTER),
            event_option(ev, E_FVG_FILLED),
            event_option(ev, E_IFVG),
            event_option(ev, E_EQ),
            event_option(ev, E_SWEEP),
            event_option(ev, E_PD),
            any_selected(ev, cfg),
            data.trend_swing,
            data.trend_internal,
            data.range_top,
            data.range_bottom,
            data.pd_position,
            data.ob_bull_top,
            data.ob_bear_bottom,
            data.fvg_bull_top,
            data.fvg_bear_bottom,
            data.liq_bsl,
            data.liq_ssl,
            data.pdh,
            data.pdl,
            data.pwh,
            data.pwl,
            data.pmh,
            data.pml,
        )

    def _before_tail(self) -> bool:
        # Present mode shows only what is alive at the end, so most of the history needs no drawing at all: every
        # object the chart would get there is erased again before the end (spec "Memory"). The tail leaves the
        # drawings materialized at its start a few bars to reach the chart within the budget; a history that ends
        # fewer bars than (alive ops / 90) after a gap longer than the tail leaves the rest to the first realtime
        # closed updates.
        if not self.is_history:
            return False
        tf = timeframe_seconds(self.time_frame)
        if tf <= 0:
            return False
        return self.time[0] < self.last_bar_time - TAIL_BARS * tf

    def materialize(self) -> None:
        # Draws everything the engines hold, in the engine order of _process_bar; beyond the budget it is queued.
        self._htf.show_all()
        self._fvg.show_all()
        self._liq.show_all()
        self._struct.show_all()
        self._ob.show_all()

    def own_state(self) -> None:
        # A calc that repeats the previous calc's bar (the next tick, a key-level bar after the closed update)
        # runs on rolled-back state, and the rollback shares lists and records with the committed state: Python
        # restores a list field by reference, the Go clone is shallow. Processing a bar then would change the
        # committed state that the next rollback restores, so every engine first copies the lists and records it
        # changes in place. Drawings stay shared: they are only set to values derived from the records, which
        # the re-run sets again. Range and data state are plain or nested records, restored by value.
        self._htf.own()
        self._fvg.own()
        self._liq.own()
        self._struct.own()
        self._ob.own()

    def _process_bar(self, k: int, atr: SeriesF, int_ph: float, int_pl: float, swing_ph: float, swing_pl: float,
                     eq_ph: float, eq_pl: float, ev: BarEvents, data: DataOut) -> None:
        # The fixed engine order of spec §2.3; each engine reads the bar at offset k.
        begin_bar(ev)
        self._draw.flush()
        self._htf.read(k, ev, data)
        self._fvg.detect(k, atr, ev, data)
        self._liq.sweeps(k, ev, data)
        self._struct.breaks(k, atr, ev, data)
        self._struct.new_pivots(k, int_ph, int_pl, swing_ph, swing_pl, ev)
        self._liq.new_pivots(k, eq_ph, eq_pl, atr, ev, data)
        self._ob.create(k, ev, data)
        self._ob.update(k, atr, ev, data)
        self._fvg.update(k, ev, data)
        self._range.update(k, ev, data)
```

## SMI Ergodic Indicator

```py SMI Ergodic Indicator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color
from indie.algorithms import Tsi, Ema


@indicator('SMII', format=format.PRICE, precision=4)  # SMI Ergodic Indicator
@param.int('long_len', default=20, min=1, title='Long Length')
@param.int('short_len', default=5, min=1, title='Short Length')
@param.int('signal_len', default=5, min=1, title='Signal Length')
@plot.line(color=color.BLUE, title='SMI')
@plot.line(color=color.MAROON, title='Signal')
def Main(self, long_len, short_len, signal_len):
    tsi = Tsi.new(self.close, long_len, short_len)
    return tsi[0], Ema.new(tsi, signal_len)[0]
```

## SMI Ergodic Oscillator

```py SMI Ergodic Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color
from indie.algorithms import Tsi, Ema


@indicator('SMIO', format=format.PRICE, precision=4)  # SMI Ergodic Oscillator
@param.int('long_len', default=20, min=1, title='Long Length')
@param.int('short_len', default=5, min=1, title='Short Length')
@param.int('signal_len', default=5, min=1, title='Signal Length')
@plot.histogram(color=color.RED)
def Main(self, long_len, short_len, signal_len):
    tsi = Tsi.new(self.close, long_len, short_len)
    return tsi[0] - Ema.new(tsi, signal_len)[0]
```

## Smoothed Moving Average

```py Smoothed Moving Average theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Rma


@indicator('SMMA', overlay_main_pane=True)  # Smoothed Moving Average
@param.int('length', default=7, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@plot.line(color=color.PURPLE)
def Main(self, length, src):
    return Rma.new(src, length)[0]
```

## Stochastic Oscillator

```py Stochastic Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, band, color, level, plot
from indie.algorithms import Sma, Stoch


@indicator('Stoch', format=format.PRICE)  # Stochastic
@param.int('k_length', default=14, min=1, title='Fast K stochastic length')
@param.int('k_smoothing', default=1, min=1, title='Fast K stochastic smoothing')
@param.int('d_smoothing', default=3, min=1, title='Slow D stochastic smoothing')
@band(20, 80, fill_color=color.AQUA(0.1), line_color=color.GRAY, title='Background')
@level(50, line_color=color.GRAY(0.5), title='Middle Band')
@plot.line(color=color.BLUE, title='%K')
@plot.line(color=color.RED, title='%D')
def Main(self, k_length, k_smoothing, d_smoothing):
    k = Sma.new(Stoch.new(self.close, self.low, self.high, k_length), k_smoothing)
    d = Sma.new(k, d_smoothing)
    return k[0], d[0]
```

## Stochastic RSI

```py Stochastic RSI theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, band, color, level, plot
from indie.algorithms import Rsi, Stoch, Sma


@indicator('Stoch RSI', format=format.PRICE)  # Stochastic RSI
@param.int('k_smoothing', default=3, min=1, title='Fast K stochastic smoothing')
@param.int('d_smoothing', default=3, min=1, title='Slow D stochastic smoothing')
@param.int('rsi_length', default=14, min=1, title='RSI length')
@param.int('k_length', default=14, min=1, title='Stochastic Length')
@param.source('src', default=source.CLOSE, title='Source')
@band(20, 80, fill_color=color.AQUA(0.1), line_color=color.GRAY, title='Background')
@level(50, line_color=color.GRAY(0.5), title='Middle Band')
@plot.line(color=color.BLUE, title='K')
@plot.line(color=color.RED, title='D')
def Main(self, k_smoothing, d_smoothing, rsi_length, k_length, src):
    rsi = Rsi.new(src, rsi_length)
    k = Sma.new(Stoch.new(rsi, rsi, rsi, k_length), k_smoothing)
    d = Sma.new(k, d_smoothing)
    return k[0], d[0]
```

## Supertrend

```py Supertrend theme={null}
# indie:lang_version = 5
from math import nan
from indie import indicator, param, plot, color
from indie.algorithms import Supertrend


@indicator('Supertrend', overlay_main_pane=True)
@param.int('atr_period', default=10, min=1)
@param.float('factor', default=3.0)
@param.str('ma_algorithm', default='RMA', options=['RMA', 'SMA', 'EMA', 'WMA'])
@plot.line('middle', color=color.GRAY(0.5), title='Body Middle')  # TODO: support display.none
@plot.line('down', color=color.RED, title='Down Trend')
@plot.line('up', color=color.GREEN, title='Up Trend')
@plot.fill('down', 'middle', color=color.RED(0.1), title='Down-Middle Fill')
@plot.fill('middle', 'up', color=color.GREEN(0.1), title='Middle-Up Fill')
def Main(self, factor, atr_period, ma_algorithm):
    st, direction = Supertrend.new(factor, atr_period, ma_algorithm)
    st_down = st[0] if direction[0] > 0 else nan
    st_up = st[0] if direction[0] < 0 else nan
    middle = (self.open[0] + self.close[0]) / 2
    return middle, st_down, st_up, plot.Fill(), plot.Fill()
```

## Triple EMA

```py Triple EMA theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Ema


@indicator('TEMA', overlay_main_pane=True)  # Triple EMA
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@plot.line(color=color.BLUE)
def Main(self, length, src):
    ema1 = Ema.new(src, length)
    ema2 = Ema.new(ema1, length)
    ema3 = Ema.new(ema2, length)
    return 3 * (ema1[0] - ema2[0]) + ema3[0]
```

## Time Price Opportunity

```py Time Price Opportunity theme={null}
# indie:lang_version = 5
from indie import MainContext, color, format, indicator, param, plot, request_series
from indie.data import TpoProfile, sources
from indie.data.sources import session_types, tpo_merge_sessions


@indicator('Time Price Opportunity', format=format.PRICE, overlay_main_pane=True)
@param.calc_time_frame('profile_tf', default='1D', options=['1D', '1W', '1M'],
                       title='Profile period', extended_hours_param='extended_hours')
@param.str('block_size', default='30m', options=['30m', '1h', '2h', '4h'], title='Block size')
@param.int('row_size_ticks', default=0, min=0, title='Levels per Row (0 for auto)')
@param.bool('extended_hours', default=False, title='Include pre/post market')
@plot.tpo_profile(
    'tpo', title='TPO', palette=[color.BLUE, color.GREEN, color.ORANGE, color.PURPLE],
    value_area=0.7, initial_balance_blocks=6, initial_balance_visible=True,
    poc_visible=True, poc_color=color.ORANGE,
)
class Main(MainContext):
    def __init__(self, profile_tf, block_size, row_size_ticks, extended_hours):
        types = [session_types.MAIN_SESSION]
        merge_sessions = tpo_merge_sessions.GROUP_BY_TYPE
        if extended_hours:
            types = [session_types.PRE_MARKET, session_types.MAIN_SESSION, session_types.POST_MARKET]
            merge_sessions = tpo_merge_sessions.MERGE_ALL
        self._profiles = request_series[TpoProfile](
            source=sources.Tpo(session_types=types, merge_sessions=merge_sessions,
                               block_size=block_size, row_size_ticks=row_size_ticks),
            time_frame=profile_tf)

    def calc(self):
        self._profiles.request_subperiods(1)
        profiles = self._profiles.subperiods()
        if profiles is None or len(profiles.value()) == 0:
            return plot.TpoProfile()
        return plot.TpoProfile(profiles.value()[0])
```

## Trading Sessions

```py Trading Sessions theme={null}
# indie:lang_version = 5
from math import isnan
from indie import indicator, plot, color, TimeFrame, time_frame_unit


@indicator('Trading Sessions', overlay_main_pane=True)
@plot.background(color=color.YELLOW(0.07), title='Pre-market session')
@plot.background(color=color.BLUE(0.07), outline_color=color.BLUE, title='Post-market session')
def Main(self):
    if self.time_frame >= TimeFrame(1, time_frame_unit.DAY):
        return plot.Background(color=color.TRANSPARENT), plot.Background(color=color.TRANSPARENT)

    pre_market_background = plot.Background()
    if self.time[0] not in self.trading_session.pre_market:
        pre_market_background.color = color.TRANSPARENT

    after_hours_background = plot.Background()
    if self.time[0] not in self.trading_session.after_hours:
        after_hours_background.color = color.TRANSPARENT

    after_hours_background.outline_left = (
        not isnan(self.time[1]) and
        not self.trading_session.is_same_period(self.time[0], self.time[1])
    )

    return pre_market_background, after_hours_background
```

## Trend Strength Index

```py Trend Strength Index theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, level, plot, color, MutSeriesF
from indie.algorithms import Corr


@indicator('Trend Strength', format=format.PRICE, precision=2)  # Trend Strength Index
@param.int('length', default=14, min=2, title='Length')
@param.source('source', default=source.CLOSE, title='Source')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.BLUE, title='Trend Strength')
def Main(self, length, source):
    bar_idx = MutSeriesF.new(float(self.bar_index))
    return Corr.new(source, bar_idx, length)[0]
```

## TRIX

```py TRIX theme={null}
# indie:lang_version = 5
from math import log
from indie import indicator, format, param, level, color, plot, MutSeriesF
from indie.algorithms import Change, Ema


@indicator('TRIX', format=format.PRICE)
@param.int('length', default=18, min=1)
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.RED, title='TRIX')
def Main(self, length):
    return 10000 * Change.new(Ema.new(Ema.new(Ema.new(MutSeriesF.new(log(self.close[0])), length), length), length))[0]
```

## True Strength Indicator

```py True Strength Indicator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot
from indie.algorithms import Tsi, Ema


@indicator('TSI', format=format.PRICE, precision=4)  # True Strength Indicator
@param.int('long_len', default=25, min=1, title='Long Length')
@param.int('short_len', default=13, min=1, title='Short Length')
@param.int('signal_len', default=13, min=1, title='Signal Length')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.BLUE, title='TSI')
@plot.line(color=color.RED, title='Signal')
def Main(self, long_len, short_len, signal_len):
    tsi = Tsi.new(self.close, long_len, short_len)
    return 100 * tsi[0], 100 * Ema.new(tsi, signal_len)[0]
```

## Ultimate Oscillator

```py Ultimate Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color
from indie.algorithms import Uo


@indicator('UO', format=format.PRICE)  # Ultimate Oscillator
@param.int('fast_len', default=7, min=1, title='Fast Length')
@param.int('middle_len', default=14, min=1, title='Middle Length')
@param.int('slow_len', default=28, min=1, title='Slow Length')
@plot.line(color=color.RED)
def Main(self, fast_len, middle_len, slow_len):
    return Uo.new(fast_len, middle_len, slow_len)[0]
```

## Visible Range Volume Profile

```py Visible Range Volume Profile theme={null}
# indie:lang_version = 5
from datetime import datetime
from math import ceil, inf, isnan, nan
from indie import (IndieError, MainContext, Optional, TimeFrame, color, format, indicator, line_style, param, plot,
                   request_series, time_frame_unit)
from indie.drawings import price_histogram_display_mode, secondary_histogram_display_mode
from indie.data import VolumeFootprintProfile, sources
from indie.data.sources import session_types


def footprint_time_frame(chart: TimeFrame) -> Optional[str]:
    if chart.unit == TimeFrame.from_str('1T').unit or chart.to_seconds() < 60:
        return None
    if chart.unit == time_frame_unit.SECOND:
        if chart.count % 60 != 0:
            return None
        minutes = chart.count // 60
        if minutes % 15 == 0:
            return '15m'
        if minutes % 5 == 0:
            return '5m'
        return '1m'
    if chart.unit == time_frame_unit.DAY or chart.unit == time_frame_unit.WEEK or chart.unit == time_frame_unit.MONTH:
        return '1D'
    if chart.unit == time_frame_unit.HOUR:
        return '15m'
    if chart.unit == time_frame_unit.MINUTE:
        if chart.count % 15 == 0:
            return '15m'
        if chart.count % 5 == 0:
            return '5m'
        return '1m'
    return None


def calendar_time_to(frame: TimeFrame, timestamp: float) -> float:
    if frame.unit == time_frame_unit.WEEK:
        date = datetime.utcfromtimestamp(timestamp)
        return timestamp + float((7 * frame.count - date.weekday()) * 86400 -
                                 date.hour * 3600 - date.minute * 60 - date.second)
    if frame.unit == time_frame_unit.MONTH:
        month_date = datetime.utcfromtimestamp(timestamp)
        month = month_date.month - 1 + frame.count
        following = datetime(month_date.year + month // 12, month % 12 + 1, 1)
        return timestamp + (following - month_date).total_seconds()
    return nan


@indicator('VRVP', overlay_main_pane=True, format=format.VOLUME)
@param.str('row_size', default='Auto', options=['Auto', 'Auto Merge', 'Manual'], title='Row Size')
# Dashboard applies the manual price to the common grid of the visible profiles.
@param.float('row_size_price', default=0.0, min=0.0, title='Price per Row (0 = minimum)')
@plot.price_histogram_series(
    'vp', title='Volume Profile',
    layers=[plot.ProfileLayer('Buy', color.LIME(0.3), color.LIME(0.12), outline_color=color.LIME(0.5)),
            plot.ProfileLayer('Sell', color.RED(0.3), color.RED(0.12), outline_color=color.RED(0.5))],
    display_mode=price_histogram_display_mode.TOTAL,
    align=2,
    width_fraction=0.3,
    values_visible=True,
    totals_visible=True,
    total_color=color.BLUE(0.35), total_color_outside_value_area=color.BLUE(0.14),
    total_outline_color=color.BLUE(0.5),
    value_area=0.7,
    poc_visible=True, poc_color=color.GRAY, poc_line_style=line_style.SOLID,
    secondary_histogram=plot.SecondaryHistogram(
        secondary_histogram_display_mode.DELTA, visible=True, width=0.3,
        layers=[plot.SecondaryHistogramLayer(color.GREEN(0.3), color.GREEN(0.12),
                                             outline_color=color.GREEN(0.5), highlight_color=color.GREEN),
                plot.SecondaryHistogramLayer(color.ORANGE(0.3), color.ORANGE(0.12),
                                             outline_color=color.ORANGE(0.5), highlight_color=color.ORANGE)],
        highlights=plot.SecondaryHistogramHighlights(
            visible=True, strategy=plot.secondary_histogram_highlights_strategy.EXTREMES, persistent=True)),
    aggregation=plot.Aggregation(range=plot.VisibleRange(), reducer=plot.reducer.SUM),
)
class Main(MainContext):
    def __init__(self, row_size):
        if self.time_frame.unit == TimeFrame.from_str('1T').unit:
            raise IndieError('Volume Footprint data is unavailable for tick charts; choose a time-based chart')
        chosen = footprint_time_frame(self.time_frame)
        if chosen is None:
            raise IndieError('No compatible footprint detail; choose a minute or longer time-based chart')
        types = [session_types.MAIN_SESSION]
        if self.extended_hours:
            types = [session_types.MAIN_SESSION, session_types.PRE_MARKET, session_types.POST_MARKET]
        ticks = 0 if row_size == 'Auto' else 1
        self._footprints = request_series[VolumeFootprintProfile](
            source=sources.VolumeFootprint(session_types=types, row_size_ticks=ticks,
                                          row_size_scope='Request' if row_size == 'Auto' else 'Profile'),
            time_frame=TimeFrame.from_str(chosen.value()))
        self._profile = plot.PriceHistogramSeries(nan)

    def calc(self, row_size, row_size_price):
        time_to = calendar_time_to(self.time_frame, self.time[0])
        footprints = self._footprints
        footprints.request_subperiods(1)
        subperiods = footprints.subperiods()
        if subperiods is None:
            self._profile.reset(nan)
            self._profile.time_to = time_to
            return self._profile
        profiles = subperiods.value()
        if not isnan(time_to):
            count = len(profiles)
            while count > 0 and profiles[count - 1].profile_start_unix_seconds >= time_to:
                count -= 1
            profiles = profiles[:count]
        if len(profiles) == 0:
            self._profile.reset(0.0)
            self._profile.time_to = time_to
            return self._profile
        step = profiles[0].row_size
        for profile in profiles:
            step = profile.common_row_size(step)
        if isnan(step):
            self._profile.reset(nan)
            self._profile.time_to = time_to
            return self._profile
        levels = max(1, ceil(round(row_size_price / step, 9))) if row_size == 'Manual' else 1
        low = inf
        high = -inf
        for footprint in profiles:
            for level in footprint.rows:
                low = min(low, level.price)
                high = max(high, level.price)
        if high >= low:
            levels = max(levels, ceil((high - low) / (2046 * step)))
        output_row_size = levels * step
        self._profile.reset(output_row_size)
        self._profile.time_to = time_to
        self._profile.merge_rows_on_zoom = row_size == 'Auto Merge'
        values = [0.0, 0.0]
        for contribution in profiles:
            for row in contribution.rows:
                values[0] = row.volume_buy
                values[1] = row.volume_sell
                self._profile.add(row.price, values)
        return self._profile
```

## Volatility Stop

```py Volatility Stop theme={null}
# indie:lang_version = 5
from math import isnan, nan
from indie import indicator, param, source, plot, color, Var, MutSeries
from indie.algorithms import Atr, Tr


@indicator('VStop', overlay_main_pane=True)  # Volatility Stop
@param.source('src', default=source.CLOSE, title='Source')
@param.int('length', default=20, min=2, title='ATR Length')
@param.float('factor', default=2.0, min=0.25, step=0.25, title='Multiplier')
@plot.marker(title='VStop (Cross)', size=3, style=plot.marker_style.CROSS, position=plot.marker_position.CENTER)
@plot.line(title='VStop (Line)', display_options=plot.LineDisplayOptions())
def Main(self, src, length, factor):
    if isnan(src[0]):
        return plot.Marker(value=nan), plot.Line(value=nan)

    atr_val = Atr.new(length)[0]
    atr_mult = (atr_val * factor) if not isnan(atr_val) else Tr.new()[0]

    uptrend = MutSeries[bool].new(init=True)
    stop = Var[float].new(src[0])
    mn = Var[float].new(src[0])
    mx = Var[float].new(src[0])

    not_first = self.bar_index > 0
    mx.set(max(mx.get(), src[0]))
    mn.set(min(mn.get(), src[0]))
    prev_stop = stop.get()

    prev_trend = uptrend[0]
    vstop = nan
    if prev_trend:
        vstop = max(prev_stop, mx.get() - atr_mult)
    else:
        vstop = min(prev_stop, mn.get() + atr_mult)

    curr_trend = (src[0] >= vstop)
    if not_first and curr_trend != prev_trend:
        mx.set(src[0]); mn.set(src[0])
        vstop = (mx.get() - atr_mult) if curr_trend else (mn.get() + atr_mult)

    stop.set(vstop)
    uptrend[0] = curr_trend

    col = color.TEAL if curr_trend else color.RED
    return (
        plot.Marker(vstop, color=col),
        plot.Line(vstop, color=col)
    )
```

## Volume

```py Volume theme={null}
# indie:lang_version = 5
from math import nan

from indie import color, format, indicator, param, plot
from indie.algorithms import Sma


@indicator('Volume', format=format.VOLUME, overlay_main_pane=True)
@param.bool('show_ma', default=True, title='Show MA')
@param.int('ma_period', default=20, min=1, title='MA Period')
@param.color('up_color', default=color.GREEN(0.3), title='Up color')
@param.color('down_color', default=color.ORANGE(0.4), title='Down color')
@plot.columns('volume', title='Volume', base_value=0, rel_width=0.9,
              display_options=plot.ColumnsDisplayOptions(
                  pane=True, status_line=True, price_label=False, price_scale_id='volume'))
@plot.line('ma', title='MA', color=color.YELLOW,
           display_options=plot.LineDisplayOptions(
               pane=True, status_line=True, price_label=False, price_scale_id='volume'))
def Main(self, show_ma, ma_period, up_color, down_color):
    ma = Sma.new(self.volume, ma_period)[0]
    volume_color = up_color if self.close[0] >= self.open[0] else down_color
    return plot.Columns(self.volume[0], color=volume_color), ma if show_ma else nan
```

## Volume Oscillator

```py Volume Oscillator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, level, color, plot
from indie.algorithms import Ema
from indie.math import divide


@indicator('Volume Osc', format=format.PRICE)  # Volume Oscillator  # TODO: format=format.PERCENT
@param.int('short_len', default=5, min=1, title='Short Length')
@param.int('long_len', default=10, min=1, title='Long Length')
@level(0, line_color=color.GRAY, title='Zero')
@plot.line(color=color.BLUE, title='VO')
def Main(self, short_len, long_len):
    short = Ema.new(self.volume, short_len)[0]
    long = Ema.new(self.volume, long_len)[0]
    return 100 * divide(short - long, long)
```

## Vortex Indicator

```py Vortex Indicator theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, plot, color, MutSeriesF
from indie.algorithms import Sum, Atr
from indie.math import divide


@indicator('VI', format=format.PRICE, precision=4)  # Vortex Indicator
@param.int('length', default=14, min=2)
@plot.line(color=color.RED, title='VI -')
@plot.line(color=color.BLUE, title='VI +')
def Main(self, length):
    vmm = Sum.new(MutSeriesF.new(abs(self.low[0] - self.high[1])), length)[0]
    vmp = Sum.new(MutSeriesF.new(abs(self.high[0] - self.low[1])), length)[0]
    satr = Sum.new(Atr.new(1), length)[0]
    vim = divide(vmm, satr)
    vip = divide(vmp, satr)
    return vim, vip
```

## Volume Weighted Average Price

```py Volume Weighted Average Price theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Vwap


@indicator('VWAP', overlay_main_pane=True)  # Volume Weighted Average Price
@param.source('src', default=source.HLC3, title='Source')
# TODO: add Earnings, Dividends, Splits
@param.str('anchor', default='Session', options=['Session', 'Week', 'Month', 'Year'], title='Anchor')
@param.int('offset', default=0, min=-500, max=500, title='Offset')
@plot.line('vwap', title='VWAP', color=color.BLUE)
@plot.line('upper', title='Upper band', color=color.GREEN)
@plot.line('lower', title='Lower band', color=color.GREEN)
@plot.fill('upper', 'lower', color=color.GREEN(0.1), title='Background')
def Main(self, src, anchor, offset):
    std_dev_mult = 1.0
    main_line, upper, lower = Vwap.new(src, anchor, std_dev_mult)
    return (
        plot.Line(main_line[0], offset=offset),
        plot.Line(upper[0], offset=offset),
        plot.Line(lower[0], offset=offset),
        plot.Fill(offset=offset),
    )
```

## Volume Moving Average Weighted

```py Volume Moving Average Weighted theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Vwma


@indicator('VWMA', overlay_main_pane=True)  # Volume Weighted Moving Average
@param.int('length', default=20, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.int('offset', default=0, min=-500, max=500, title='Offset')
@plot.line(color=color.BLUE)
def Main(self, length, src, offset):
    result = Vwma.new(src, length)
    return plot.Line(result[0], offset=offset)
```

## Williams Alligator

```py Williams Alligator theme={null}
# indie:lang_version = 5
from indie import indicator, param, plot, color
from indie.algorithms import Rma


@indicator('Alligator', overlay_main_pane=True)  # Williams Alligator
@param.int('jaw_period', default=13, min=1, title='Jaw Period')
@param.int('teeth_period', default=8, min=1, title='Teeth Period')
@param.int('lips_period', default=5, min=1, title='Lips Period')
@param.int('jaw_offset', default=8, min=1, title='Jaw Offset')
@param.int('teeth_offset', default=5, min=1, title='Teeth Offset')
@param.int('lips_offset', default=3, min=1, title='Lips Offset')
@plot.line(color=color.BLUE, title='Jaw')
@plot.line(color=color.RED, title='Teeth')
@plot.line(color=color.GREEN, title='Lips')
def Main(self, jaw_period, teeth_period, lips_period, jaw_offset, teeth_offset, lips_offset):
    jaw = Rma.new(self.hl2, jaw_period)
    teeth = Rma.new(self.hl2, teeth_period)
    lips = Rma.new(self.hl2, lips_period)

    return (
        plot.Line(jaw[0], offset=jaw_offset),
        plot.Line(teeth[0], offset=teeth_offset),
        plot.Line(lips[0], offset=lips_offset),
    )
```

## Williams Fractals

```py Williams Fractals theme={null}
# indie:lang_version = 5
from math import nan
from indie import indicator, param, plot, color, SeriesF


def is_up_fractal(high: SeriesF, n: int) -> bool:
    center = high[n]
    right_ok = True
    for i in range(1, n + 1):
        if not (high[n - i] < center):
            right_ok = False
    if not right_ok:
        return False
    for k in range(5):
        flat_ok = True
        for j in range(1, k + 1):
            if not (high[n + j] <= center):
                flat_ok = False
        if flat_ok:
            left_ok = True
            for m in range(1, n + 1):
                if not (high[n + m + k] < center):
                    left_ok = False
            if left_ok:
                return True
    return False


def is_down_fractal(low: SeriesF, n: int) -> bool:
    center = low[n]
    right_ok = True
    for i in range(1, n + 1):
        if not (low[n - i] > center):
            right_ok = False
    if not right_ok:
        return False
    for k in range(5):
        flat_ok = True
        for j in range(1, k + 1):
            if not (low[n + j] >= center):
                flat_ok = False
        if flat_ok:
            left_ok = True
            for m in range(1, n + 1):
                if not (low[n + m + k] > center):
                    left_ok = False
            if left_ok:
                return True
    return False


@indicator('Fractals', overlay_main_pane=True)  # Williams Fractals
@param.int('periods', default=2, min=2, title='Periods')
@plot.marker(color=color.RED, style=plot.marker_style.CIRCLE,
             position=plot.marker_position.BELOW, size=2, title='Down Fractal')
@plot.marker(color=color.GREEN, style=plot.marker_style.CIRCLE,
             position=plot.marker_position.ABOVE, size=2, title='Up Fractal')
def Main(self, periods):
    # The fractal checks return early, so register the deepest offset unconditionally (Go series trim).
    _ = self.high[2 * periods + 4]
    _ = self.low[2 * periods + 4]
    down_value = nan
    up_value = nan
    if self.bar_index >= 2 * periods + 4:
        if is_down_fractal(self.low, periods):
            down_value = self.low[periods]
        if is_up_fractal(self.high, periods):
            up_value = self.high[periods]
    return plot.Marker(down_value, offset=-periods), plot.Marker(up_value, offset=-periods)
```

## Williams Percent Range

```py Williams Percent Range theme={null}
# indie:lang_version = 5
from indie import indicator, format, param, source, band, color, level, line_style, plot
from indie.algorithms import Highest, Lowest
from indie.math import divide


@indicator('Williams %R', format=format.PRICE)  # Williams Percent Range
@param.int('length', default=14, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@band(-20, -80, line_color=color.GRAY, fill_color=color.PURPLE(0.1), title='Background')
@level(-50, line_color=color.GRAY, line_style=line_style.DOTTED, title='Middle Level')
@plot.line(color=color.PURPLE, title='%R')
def Main(self, length, src):
    max = Highest.new(self.high, length)[0]
    min = Lowest.new(self.low, length)[0]
    return 100 * divide(src[0] - max, max - min)
```

## Moving Average Weighted

```py Moving Average Weighted theme={null}
# indie:lang_version = 5
from indie import indicator, param, source, plot, color
from indie.algorithms import Wma


@indicator('WMA', overlay_main_pane=True)  # Weighted Moving Average
@param.int('length', default=9, min=1)
@param.source('src', default=source.CLOSE, title='Source')
@param.int('offset', default=0, min=-500, max=500, title='Offset')
@plot.line(color=color.BLUE)
def Main(self, length, src, offset):
    result = Wma.new(src, length)
    return plot.Line(result[0], offset=offset)
```

## Woodies CCI

```py Woodies CCI theme={null}
# indie:lang_version = 5
from indie import indicator, param, level, color, line_style, plot, Color
from indie.algorithms import Cci


@indicator('Woodies CCI')
@param.int('cci_turbo_len', default=6, min=3, max=14, title='CCI Turbo Length')
@param.int('cci_14_len', default=14, min=7, max=20, title='CCI 14 Length')
@level(-100, line_color=color.GRAY, line_style=line_style.DOTTED, title='Minus Line')
@level(0, line_color=color.GRAY, line_style=line_style.SOLID, title='Zero Line')
@level(100, line_color=color.GRAY, line_style=line_style.DOTTED, title='Hundred Line')
@plot.histogram(title='CCI Turbo Histogram')
@plot.line(color=color.GREEN, title='CCI Turbo')
@plot.line(color=color.RED, title='CCI 14')
def Main(self, cci_turbo_len, cci_14_len):
    cci_turbo = Cci.new(self.close, cci_turbo_len)
    cci_14 = Cci.new(self.close, cci_14_len)
    last_5_down = cci_14[5] < 0 and cci_14[4] < 0 and cci_14[3] < 0 and cci_14[2] < 0 and cci_14[1] < 0
    last_5_up = cci_14[5] > 0 and cci_14[4] > 0 and cci_14[3] > 0 and cci_14[2] > 0 and cci_14[1] > 0

    hist_color = color.BLACK  # default value
    if last_5_up:
        hist_color = color.GREEN
    elif last_5_down:
        hist_color = color.RED
    elif cci_14[0] < 0:
        hist_color = color.GREEN
    else:
        hist_color = color.RED
    return plot.Histogram(cci_14[0], color=hist_color), cci_turbo[0], cci_14[0]
```

## Zig Zag

```py Zig Zag theme={null}
# indie:lang_version = 5
from math import isnan, nan
from indie import Optional, color, Color, Context, MainContext, Var, Algorithm, indicator, param
from indie.drawings import LineSegment, LabelAbs, AbsolutePosition, Chart, callout_position
from indie.algorithms import Sum, ZigZag


class Settings:
    def __init__(self,
                 line_color: Color,
                 dev_threshold: float = 5.0,
                 depth: int = 10,
                 extend_last: bool = True,
                 display_reversal_price: bool = True,
                 display_cumulative_volume: bool = True,
                 display_reversal_price_change: bool = True,
                 difference_price_mode: str = 'Absolute',
                 draw: bool = True,
                 allow_zig_zag_on_one_bar: bool = True):
        self.dev_threshold = dev_threshold
        self.depth = depth
        self.extend_last = extend_last
        self.display_reversal_price = display_reversal_price
        self.display_cumulative_volume = display_cumulative_volume
        self.display_reversal_price_change = display_reversal_price_change
        self.difference_price_mode = difference_price_mode
        self.draw = draw
        self.allow_zig_zag_on_one_bar = allow_zig_zag_on_one_bar
        self.line_color = line_color
        self.price_precision = 2


class Pivot:
    def __init__(self,
                 start: Optional[AbsolutePosition],
                 end: AbsolutePosition,
                 vol: float,
                 is_high: bool,
                 chart: Chart,
                 settings: Settings):
        self.ln = Optional[LineSegment]()
        self.lb = Optional[LabelAbs]()
        self.is_high = is_high
        self.vol = vol
        self.start = start
        self.end = end
        self.chart = chart

        if settings.draw and start is not None:
            self.ln = LineSegment(start.value(), end, color=settings.line_color, line_width=2)
            self.lb = make_pivot_label(is_high, end, settings)
        self.update_pivot(end, vol, settings)


    def update_pivot(self, end: AbsolutePosition,
                     vol: float, settings: Settings) -> None:
        self.end = end
        self.vol = vol
        if self.lb is not None:
            self.lb.value().position = self.end
            self.lb.value().text = price_rotation_aggregate(self.start.value().price, self.end.price,
                                                            self.vol, settings)
            self.chart.draw(self.lb.value())
        if self.ln is not None:
            self.ln.value().point_b = self.end
            self.chart.draw(self.ln.value())

    def delete(self) -> None:
        if self.ln is not None:
            self.chart.erase(self.ln.value())
        if self.lb is not None:
            self.chart.erase(self.lb.value())


class ZigZagPainter(Algorithm):
    def __init__(self, ctx: Context):
        super().__init__(ctx)
        self.last_pivot = ctx.new_var(Optional[Pivot]())
        self.sum_vol = ctx.new_var(0.0)

    def calc(self, chart: Chart, settings: Settings) -> None:
        ctx = self.ctx
        length = max(2, settings.depth // 2)
        if not isnan(ctx.volume[length]):
            self.sum_vol.set(self.sum_vol.get() + ctx.volume[length])

        new_high, upd_high, new_low, upd_low = ZigZag.new(
            length, length, settings.dev_threshold, settings.allow_zig_zag_on_one_bar)
        if new_high or upd_high:
            self._handle_zigzag_event(ctx.time[length], ctx.high[length],
                                      new_high, upd_high, True, chart, settings)
        if new_low or upd_low:
            self._handle_zigzag_event(ctx.time[length], ctx.low[length],
                                      new_low, upd_low, False, chart, settings)

        if settings.extend_last:
            zigzag_updated = new_high or upd_high or new_low or upd_low
            self._draw_extend(zigzag_updated, length, chart, settings)

    def _handle_zigzag_event(self, time: float, price: float,
                             new_pivot: bool, upd_pivot: bool, is_high: bool,
                             chart: Chart, settings: Settings) -> None:
        point = AbsolutePosition(time, price)
        if new_pivot and self.last_pivot.get() is None:
            self.last_pivot.set(Pivot(None, point, nan, is_high, chart, settings))
            self.sum_vol.set(0)
            return
        last_pivot = self.last_pivot.get().value()
        if upd_pivot:
            last_pivot.update_pivot(point, last_pivot.vol + self.sum_vol.get(), settings)
            self.sum_vol.set(0)
        elif new_pivot:
            self.last_pivot.set(Pivot(last_pivot.end, point, self.sum_vol.get(), is_high,
                                      chart, settings))
            self.sum_vol.set(0)

    def _draw_extend(self, zigzag_updated: bool, length: int,
                     chart: Chart, settings: Settings) -> None:
        ctx = self.ctx
        last_pivot = self.last_pivot.get()
        extend = Var[Optional[Pivot]].new(None)

        rem_vol = Sum.new(ctx.volume, length)[0]
        if ctx.is_last_bar and last_pivot is not None:
            is_high = not last_pivot.value().is_high
            cur_series = ctx.high if is_high else ctx.low
            end = AbsolutePosition(ctx.time[0], cur_series[0])
            extend_vol = self.sum_vol.get() + rem_vol
            if extend.get() is None:  # there was no extend before, create a new one
                extend.set(Pivot(last_pivot.value().end, end, extend_vol, is_high,
                                 chart, settings))
            elif zigzag_updated:  # existing extend is obsolete, recreate it
                extend.get().value().delete()
                extend.set(Pivot(last_pivot.value().end, end, extend_vol, is_high,
                                 chart, settings))
            else:  # update right point of the extend
                extend.get().value().update_pivot(end, extend_vol, settings)


def price_rotation_diff(start: float, end: float, settings: Settings) -> str:
    diff = end - start
    sign = '+' if diff > 0 else ''
    diff_str = ''
    if settings.difference_price_mode == 'Absolute':
        diff_str = str(round(diff, settings.price_precision))
    else:
        diff_str = str(round(diff * 100 / start, 2)) + '%'
    return '(' + sign + diff_str + ')'


def to_vol_format(v: float) -> str:
    if v > 1000000:
        return str(round(v / 1000000, 3)) + 'M'
    if v > 1000:
        return str(round(v / 1000, 3)) + 'K'
    if v == 0:
        return '0'
    return str(v)


def price_rotation_aggregate(start: float, end: float, vol: float, settings: Settings) -> str:
    s = ''
    if settings.display_reversal_price:
        s += str(round(end, settings.price_precision)) + ' '
    if settings.display_reversal_price_change:
        s += price_rotation_diff(start, end, settings) + ' '
    if settings.display_cumulative_volume:
        s += '\n' + to_vol_format(vol)
    return s


def make_pivot_label(is_high: bool, point: AbsolutePosition,
                     settings: Settings) -> Optional[LabelAbs]:
    if (not settings.display_reversal_price and
            not settings.display_reversal_price_change and
            not settings.display_cumulative_volume):
        return None
    txt_color = color.RED
    callout_pos = callout_position.BOTTOM_RIGHT  # TODO: callout_position.BOTTOM
    if is_high:
        txt_color = color.GREEN
        callout_pos = callout_position.TOP_RIGHT  # TODO: callout_position.TOP
    return LabelAbs(text='', position=point, text_color=txt_color, callout_position=callout_pos,
                    font_size=11, bg_color=color.TRANSPARENT)  # TODO: text_align=text_align.CENTER


@indicator('Zig Zag', overlay_main_pane=True)
@param.float('deviation_input', default=5.0, min=0.00001, max=100.0, step=0.5,
             title='Price deviation for reversals (%)')
@param.int('depth_input', default=10, min=2, title='Pivot legs')
@param.color('line_color', default=color.BLUE, title='Line color')
@param.bool('extend_input', default=True, title='Extend to last bar')
@param.bool('show_price_input', default=True, title='Display reversal price')
@param.bool('show_vol_input', default=True, title='Display cumulative volume')
@param.bool('show_chg_input', default=True, title='Display reversal price change')
@param.str('price_diff_input', default='Absolute', options=['Absolute', 'Percent'],
           title='Price Reversal')
class Main(MainContext):
    def __init__(self, deviation_input, depth_input, line_color, extend_input,
                 show_price_input, show_vol_input, show_chg_input, price_diff_input):
        self._settings = Settings(
            line_color, deviation_input,
            depth_input, extend_input,
            show_price_input, show_vol_input,
            show_chg_input, price_diff_input,
        )

    def pre_calc(self):
        self._settings.price_precision = self.info.price_precision

    def calc(self):
        ZigZagPainter.new(self.chart, self._settings)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.