Sleepyfx's picture
download
raw
12.4 kB
"""engine/nwog.py — SleepyFX Elite NWOG + NDOG Detection engine.
Converted from ICT/SMC PineScript concepts. Called by FastAPI api/main.py.
All public functions are synchronous — FastAPI wraps in run_in_executor.
NWOG (New Week Opening Gap):
- Weekly open: 18:00 Sunday New York time.
- Gap ≥ 1 tick vs prior Friday close → create box at open.
- Auto mode: automatic gap detection.
- Manual mode: user-defined level (passed in config).
- Tap detection: price trades within ATR/2 of box boundaries → tapped=True.
NDOG (New Day Opening Gap):
- Daily open: 18:00 NY time each trading day.
- Same gap detection and tap logic, no manual mode.
Example input:
bars = [OHLCBar(timestamp=1700000000000, open=1.0900, high=1.0920,
low=1.0890, close=1.0910, volume=12345), ...]
config = {
'symbol': 'EURUSD',
'timezone': 'America/New_York',
'nwog_manual_high': None, # float or None
'nwog_manual_low': None, # float or None
'tick_size': 0.0001,
}
Example output:
TrueOpenResult(
nwog=GapLevel(high=1.0915, low=1.0905, tapped=True, mode='auto'),
ndog=NDOGLevel(high=1.0912, low=1.0900, tapped=False),
error=None
)
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Optional
import pandas as pd
from engine.cycle import OHLCBar
logger = logging.getLogger(__name__)
# ── Constants ─────────────────────────────────────────────────────────────────
_NY_TZ = 'America/New_York'
_WEEK_OPEN_H = 18 # 6 PM Sunday NY = weekly open
_DAY_OPEN_H = 18 # 6 PM NY = daily open (ICT session start)
_ATR_PERIOD = 14
_DEFAULT_TICK = 0.0001
# ── Dataclasses ───────────────────────────────────────────────────────────────
@dataclass
class GapLevel:
"""Opening gap box (NWOG)."""
high: Optional[float] = None
low: Optional[float] = None
tapped: bool = False
mode: str = 'auto' # 'auto' | 'manual'
@dataclass
class NDOGLevel:
"""New Day Opening Gap level."""
high: Optional[float] = None
low: Optional[float] = None
tapped: bool = False
@dataclass
class TrueOpenResult:
"""Result returned to /api/analysis → analysis.trueOpen."""
nwog: GapLevel = None
ndog: NDOGLevel = None
error: Optional[str] = None
def __post_init__(self):
if self.nwog is None:
self.nwog = GapLevel()
if self.ndog is None:
self.ndog = NDOGLevel()
# ── Internal helpers ──────────────────────────────────────────────────────────
def _to_df(bars: list[OHLCBar], tz: str) -> pd.DataFrame:
"""Convert OHLCBar list to a TZ-aware OHLC DataFrame.
Args:
bars: OHLC bars, newest LAST.
tz: IANA timezone string.
Returns:
TZ-aware OHLC DataFrame indexed by Timestamps.
"""
df = pd.DataFrame([vars(b) for b in bars])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
df.set_index('timestamp', inplace=True)
df.index = df.index.tz_convert(tz)
return df
def _atr(df: pd.DataFrame, period: int = _ATR_PERIOD) -> float:
"""Compute ATR(period) from OHLC DataFrame.
Args:
df: OHLC DataFrame.
period: ATR period length.
Returns:
ATR float, or 0.0 when insufficient data.
"""
if len(df) < period + 1:
return 0.0
trs = []
highs = df['high'].values
lows = df['low'].values
closes = df['close'].values
for i in range(1, len(df)):
tr = max(
highs[i] - lows[i],
abs(highs[i] - closes[i - 1]),
abs(lows[i] - closes[i - 1]),
)
trs.append(tr)
return float(sum(trs[-period:]) / period)
def _find_weekly_open(df: pd.DataFrame) -> Optional[pd.Timestamp]:
"""Find the most recent weekly open timestamp (18:00 Sunday NY time).
Args:
df: TZ-aware OHLC DataFrame.
Returns:
Timestamp of the most recent Sunday 18:00 bar, or None.
"""
# Sunday = 6 in pandas dayofweek
sundays_18 = df[
(df.index.dayofweek == 6) &
(df.index.hour == _WEEK_OPEN_H) &
(df.index.minute == 0)
]
if sundays_18.empty:
# Fallback: nearest Sunday-ish bar (some data may skip exact 18:00)
sundays = df[df.index.dayofweek == 6]
if sundays.empty:
return None
# Get the first bar on the most recent Sunday at or after 18:00
last_sunday = sundays.index[-1].normalize() + pd.Timedelta(hours=18)
candidates = df[df.index >= last_sunday]
return candidates.index[0] if not candidates.empty else None
return sundays_18.index[-1]
def _find_daily_open(df: pd.DataFrame) -> Optional[pd.Timestamp]:
"""Find the most recent daily open timestamp (18:00 NY time).
Args:
df: TZ-aware OHLC DataFrame.
Returns:
Timestamp of the most recent 18:00 bar, or None.
"""
opens_18 = df[
(df.index.hour == _DAY_OPEN_H) &
(df.index.minute == 0)
]
if opens_18.empty:
# Fallback: most recent bar at or after 18:00 on any day
today = df.index[-1].normalize()
candidates = df[df.index >= today + pd.Timedelta(hours=_DAY_OPEN_H)]
if candidates.empty:
return None
return candidates.index[0]
return opens_18.index[-1]
def _prior_close_before(df: pd.DataFrame, open_ts: pd.Timestamp) -> Optional[float]:
"""Get the close price of the last bar strictly before open_ts.
Args:
df: TZ-aware OHLC DataFrame.
open_ts: Session open timestamp.
Returns:
Close price float, or None when no prior bar exists.
"""
prior = df[df.index < open_ts]
if prior.empty:
return None
return float(prior['close'].iloc[-1])
def _gap_box(
open_price: float,
prior_close: float,
tick_size: float,
) -> Optional[tuple[float, float]]:
"""Compute the gap box high/low from the opening price and prior close.
Gap must be at least 1 tick to qualify.
Args:
open_price: Session open price.
prior_close: Close of the last bar before the session open.
tick_size: Minimum price increment for this instrument.
Returns:
(box_high, box_low) tuple, or None when gap < 1 tick.
"""
gap = open_price - prior_close
if abs(gap) < tick_size:
return None
if gap > 0:
# Gap up: open above prior close
box_high = open_price
box_low = prior_close
else:
# Gap down: open below prior close
box_high = prior_close
box_low = open_price
return round(box_high, 6), round(box_low, 6)
def _is_tapped(
df: pd.DataFrame,
open_ts: pd.Timestamp,
box_high: float,
box_low: float,
atr: float,
) -> bool:
"""Determine whether price has tapped the gap box since its creation.
Tap: price trades within ATR/2 of the box boundaries (high or low).
Args:
df: TZ-aware OHLC DataFrame.
open_ts: Session open timestamp (gap creation point).
box_high: Gap box upper boundary.
box_low: Gap box lower boundary.
atr: Current ATR value for the proximity threshold.
Returns:
True when a tap has occurred.
"""
subsequent = df[df.index > open_ts]
if subsequent.empty or atr == 0.0:
return False
proximity = atr / 2.0
highs = subsequent['high'].values
lows = subsequent['low'].values
for i in range(len(subsequent)):
if (
abs(highs[i] - box_high) <= proximity or
abs(lows[i] - box_low) <= proximity or
(lows[i] <= box_high and highs[i] >= box_low) # price traded through box
):
return True
return False
# ── Public API ────────────────────────────────────────────────────────────────
def compute(bars: list[OHLCBar], config: dict) -> TrueOpenResult:
"""Detect NWOG and NDOG opening gaps and their tap status.
NWOG:
Locates the most recent Sunday 18:00 NY weekly open.
Computes gap box vs prior Friday close.
Checks whether price has tapped the box since opening.
Manual mode: uses config['nwog_manual_high'] and ['nwog_manual_low']
when both are set — skips auto-detection.
NDOG:
Locates the most recent 18:00 NY daily open.
Same gap box and tap logic.
Args:
bars: List of 15m OHLC bars, newest LAST. Minimum 10 required.
config: Runtime config dict with keys:
'symbol' — ticker string
'timezone' — IANA timezone (default: 'America/New_York')
'tick_size' — float (default: 0.0001)
'nwog_manual_high' — float | None (manual NWOG override)
'nwog_manual_low' — float | None (manual NWOG override)
Returns:
TrueOpenResult with NWOG and NDOG level data.
On any error returns TrueOpenResult(error=str(e)) — never raises.
"""
try:
if not bars or len(bars) < 10:
return TrueOpenResult(error='insufficient_bars')
tz = config.get('timezone', _NY_TZ)
tick_size = float(config.get('tick_size', _DEFAULT_TICK))
manual_h = config.get('nwog_manual_high')
manual_l = config.get('nwog_manual_low')
df = _to_df(bars, tz)
atr = _atr(df)
# ── NWOG ─────────────────────────────────────────────────────────────
nwog = GapLevel(mode='auto')
if manual_h is not None and manual_l is not None:
# Manual mode: user supplied levels directly
nwog.high = float(manual_h)
nwog.low = float(manual_l)
nwog.mode = 'manual'
nwog.tapped = _is_tapped(
df = df,
open_ts = df.index[0], # check entire visible range
box_high = nwog.high,
box_low = nwog.low,
atr = atr,
)
else:
# Auto mode: detect from weekly open bar
weekly_open_ts = _find_weekly_open(df)
if weekly_open_ts is not None:
open_price = float(df.loc[weekly_open_ts, 'open'])
prior_close = _prior_close_before(df, weekly_open_ts)
if prior_close is not None:
box = _gap_box(open_price, prior_close, tick_size)
if box is not None:
nwog.high = box[0]
nwog.low = box[1]
nwog.tapped = _is_tapped(df, weekly_open_ts, box[0], box[1], atr)
# ── NDOG ─────────────────────────────────────────────────────────────
ndog = NDOGLevel()
daily_open_ts = _find_daily_open(df)
if daily_open_ts is not None:
open_price = float(df.loc[daily_open_ts, 'open'])
prior_close = _prior_close_before(df, daily_open_ts)
if prior_close is not None:
box = _gap_box(open_price, prior_close, tick_size)
if box is not None:
ndog.high = box[0]
ndog.low = box[1]
ndog.tapped = _is_tapped(df, daily_open_ts, box[0], box[1], atr)
return TrueOpenResult(nwog=nwog, ndog=ndog)
except Exception as exc:
logger.error('nwog compute error: %s', exc, exc_info=True)
return TrueOpenResult(error=str(exc))

Xet Storage Details

Size:
12.4 kB
·
Xet hash:
a0537d370dd8ca154466a52057ddf5a00d451a26ab802352b9f6778fe92456b7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.