stocks / modules /chart /confluence_levels.py
user
python version
ee446e8
Raw History Blame Contribute Delete
7.46 kB
"""Multi-timeframe confluence levels for the /chart "Confluence Levels" tool.
Concept (user-defined, Option A): a support level is more significant when
several intraday grids see it at the same time. The day's minute bars are
aggregated to coarser grids (5m/15m/30m/1h/4h); each grid contributes its
zigzag swing LOWS β€” the same pivot structure the retest tool marks β€” and a
price zone is "confluent" when at least `min_grids` of those grids each have
a swing low within `tol_pct` of the same price. Levels are drawn strongest
first (most agreeing grids), never overlapping, capped at `max_levels`.
Supports only: pivots above the day's last close are excluded up front β€” a
grid's swing low that price has already broken is not a support zone, and
counting it would inflate grid agreement in places the overlay never draws
(consistent with the retest tool, which only marks pullback LOWS).
"""
from __future__ import annotations
from typing import Any, cast
import pandas as pd
from modules.chart.retest_levels import MIN_MOVE_PCT, bars_from_premarket, zigzag
# Intraday grids the confluence tool runs on. "1m" is deliberately excluded:
# it is the raw structure the retest tool already draws, and its hundreds of
# noise pivots would sit within tolerance of almost any zone, diluting the
# "several independent grids agree" signal.
GRID_TIMEFRAMES = ("5m", "15m", "30m", "1h", "4h")
RESAMPLE_RULES = {
"5m": "5min",
"15m": "15min",
"30m": "30min",
"1h": "1h",
"4h": "4h",
}
# How close two grids' swing lows must be to count as the same zone (relative,
# same order of magnitude as the retest tool's 3-4 cent touch tolerance).
TOUCH_PCT = 0.0025
# Minimum number of distinct grids that must agree for a zone to be drawn.
MIN_GRIDS = 3
# Cap on drawn confluence levels: strongest-first order kept.
MAX_CONFLUENCE_LEVELS = 8
def resample_minutes(bars: pd.DataFrame, timeframe: str) -> pd.DataFrame:
"""Aggregate enriched minute bars to a coarser intraday timeframe.
`bars` is a data_manager minute frame (a `time` column "HH:MM" NY plus
OHLCV). The frame is regrouped on its datetime index at the requested
wall-clock grid and reduced to OHLCV; each aggregated bar is labeled with
its bin's wall-clock time. Ported verbatim from the original retest
histogram tool, where the bin-placement semantics were tested.
"""
rule = RESAMPLE_RULES[timeframe]
frame = bars
if not isinstance(bars.index, pd.DatetimeIndex) and "timestamp" in bars.columns:
frame = bars.set_index("timestamp")
agg = cast(
pd.DataFrame,
(
frame[["open", "high", "low", "close", "volume"]]
.resample(rule)
.agg(
{
"open": "first",
"high": "max",
"low": "min",
"close": "last",
"volume": "sum",
}
)
.dropna(subset=["open"]) # type: ignore[call-overload] # pandas 3.x dropna stubs are incomplete # empty overnight bins
),
)
out = agg.copy()
out["time"] = cast(pd.DatetimeIndex, out.index).strftime("%H:%M")
return out
def grid_pivots(bars: pd.DataFrame, timeframe: str) -> list[float]:
"""Swing-low prices of one resampled grid (support-side candidates).
Runs the retest tool's zigzag on the grid's OHLC bars (min-move relative
to the grid's first close) and keeps the LOW pivots only, deduplicated
and sorted. Grids with fewer than 3 aggregated bars can't form a swing
(same floor as the retest run detection) and contribute nothing.
"""
frame = resample_minutes(bars, timeframe)
if len(frame) < 3:
return []
start_px = float(cast(Any, frame["close"].iloc[0]))
ext = zigzag(
cast(pd.Series, frame["high"]),
cast(pd.Series, frame["low"]),
MIN_MOVE_PCT * start_px,
cast(pd.Series, frame["open"]),
cast(pd.Series, frame["close"]),
)
# Drop the zigzag's bar-0 "H" exactly like the retest tool β€” grid pivots
# must be real swings, otherwise the day's opening bar doubles as a pivot.
if ext and ext[0][0] == "H" and ext[0][1] == 0:
ext = ext[1:]
return sorted({round(float(price), 6) for kind, _, price in ext if kind == "L"})
def cluster_confluence(
pivots_by_grid: dict[str, list[float]],
tol_pct: float,
min_grids: int,
max_levels: int,
) -> list[dict[str, Any]]:
"""Greedy strongest-first confluence zones from per-grid swing lows.
Repeatedly picks the pivot price supported by the most distinct grids
within `tol_pct` (ties β†’ lowest price), emits it, and removes every pivot
inside that zone from every grid so zones never overlap. Stops when the
strongest remaining zone has fewer than `min_grids` grids or `max_levels`
zones were emitted. Each emitted zone is {"price", "count", "grids"}
with grids in GRID_TIMEFRAMES order.
The greedy pass below drains each grid as it consumes a zone, so work on
a copy: the caller's mapping is an input, not scratch space.
"""
pivots_by_grid = {g: list(v) for g, v in pivots_by_grid.items()}
grids = [g for g in pivots_by_grid if pivots_by_grid[g]]
levels: list[dict[str, Any]] = []
while len(levels) < max_levels:
prices = sorted({p for g in grids for p in pivots_by_grid[g]})
if not prices:
break
best_price: float | None = None
best_grids: list[str] = []
for p in prices:
zone = [g for g in grids if any(p * (1 - tol_pct) <= x <= p * (1 + tol_pct) for x in pivots_by_grid[g])]
if len(zone) > len(best_grids) or (
len(zone) == len(best_grids) and best_price is not None and p < best_price
):
best_price, best_grids = p, zone
if best_price is None or len(best_grids) < min_grids:
break
levels.append(
{
"price": round(best_price, 6),
"count": len(best_grids),
"grids": best_grids,
}
)
lo = best_price * (1 - tol_pct)
hi = best_price * (1 + tol_pct)
for g in grids:
pivots_by_grid[g] = [x for x in pivots_by_grid[g] if not (lo <= x <= hi)]
return levels
def compute_confluence_levels(
bars: pd.DataFrame,
min_grids: int = MIN_GRIDS,
tol_pct: float = TOUCH_PCT,
max_levels: int = MAX_CONFLUENCE_LEVELS,
) -> dict[str, Any]:
"""Zones where at least `min_grids` intraday grids agree on a swing low.
`bars` is a data_manager minute frame (a `time` column "HH:MM" NY plus
OHLCV), premarket and later (>= 04:00). Returns {"levels":
[{"price", "count", "grids"}, ...]} β€” strongest-first, non-overlapping,
at or below the day's last close (support side). A day with no multi-grid
agreement (flat, vertical ramp, thin data) yields no levels.
"""
all_bars = bars_from_premarket(bars)
if all_bars.empty:
return {"levels": []}
last_close = float(cast(Any, all_bars["close"].iloc[-1]))
pivots_by_grid: dict[str, list[float]] = {}
for g in GRID_TIMEFRAMES:
pivots = [p for p in grid_pivots(all_bars, g) if p <= last_close * (1 + tol_pct)]
if pivots:
pivots_by_grid[g] = pivots
return {"levels": cluster_confluence(pivots_by_grid, tol_pct, min_grids, max_levels)}