# =============================================================================
# DISCLAIMER
# =============================================================================
# This is sample code for learning only. It is not advice, and it is not a recommendation to trade.
# This code can have bugs. Read the code and check it yourself. Test it first on Sandbox (UAT / Test — NOT live).
# You are fully responsible for any live trade and for any loss. Markets are risky. You can lose money.
# INFINN (HKKR Finserv Pvt Ltd) is not responsible for losses from using this code.
# Questions: support@infinn.in
# =============================================================================
"""
INFINN example: options Straddle / Strangle with stoploss and profit booking.

Educational example code — not investment advice or a recommended strategy.
Test on Sandbox (UAT / Test — NOT live) first. Options selling carries unlimited risk.

Under the SEBI retail algo framework, a strategy you run through the API may need
exchange approval / registration through your broker before you use it live.
Questions: support@infinn.in

What it does
------------
1. Logs in with the INFINN Python SDK (``pip install infinn``, 0.1.2 or later).
2. Reads the index spot price, rounds it to the ATM strike.
3. Picks the CE and PE contracts (ATM for a straddle, ATM ± distance for a strangle)
   from the option chain, with lot size and tick size from the API.
4. Places both legs (SELL by default, BUY also allowed).
5. Watches prices (WebSocket if available, else REST polling) and live MTM.
6. Exits on: per-leg stoploss (% or points), combined stoploss / target (rupees, points
   or % of premium), trailing stop, profit lock, time exit, daily max loss / max profit,
   lost price feed, an error, or Ctrl+C. Every exit squares off open legs safely (with retries).
7. Optional: entry window + combined-premium entry filter, re-entry after a stoploss.

Strategy Builder: the docs page /examples/strategy-builder/ fills only the
BUILDER_SETTINGS block below; everything else is this same tested program.

Safety defaults
---------------
* ENV = "sandbox"  (Sandbox / UAT / Test — NOT live)
* DRY_RUN = True   (no orders are sent; fills are simulated at the live price)
* Live needs ENV="live" AND --confirm-live AND typing a confirmation.
* API key / secret come ONLY from environment variables INFINN_API_KEY and
  INFINN_API_SECRET (read by the SDK). Never put them in this file.

Run
---
    python straddle_strangle.py                       # dry run on Sandbox
    python straddle_strangle.py --entry now           # dry run, enter immediately
    python straddle_strangle.py --place-orders        # real orders on Sandbox
    python straddle_strangle.py --mode strangle --otm 200 --lots 1
"""

from __future__ import annotations

import argparse
import logging
import math
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Callable

# ═══════════════════════════════════════════════════════════════════════════
#  CONFIG — edit these values (or override them with command-line flags)
# ═══════════════════════════════════════════════════════════════════════════


@dataclass
class Config:
    # ── What to trade ─────────────────────────────────────────────────────
    UNDERLYING: str = "NIFTY"          # NIFTY | BANKNIFTY | SENSEX | CRUDEOIL | CRUDEOILM
    EXPIRY: str = "auto"               # auto/current = nearest unexpired (on expiry day, rolls to the next
                                       # one after the session cutoff) | next = 2nd nearest | monthly = last
                                       # expiry of the nearest month | or a date, e.g. "25-NOV-2026"
    MODE: str = "straddle"             # straddle (both ATM) | strangle (both OTM)
    STRANGLE_BY: str = "points"        # strangle only: points | strikes | premium
    STRANGLE_OTM_POINTS: float = 200   # STRANGLE_BY=points:  CE = ATM + X, PE = ATM - X
    STRANGLE_OTM_STRIKES: int = 2      # STRANGLE_BY=strikes: CE/PE this many strikes away from ATM
    STRANGLE_PREMIUM: float = 50.0     # STRANGLE_BY=premium: OTM CE/PE whose LTP is closest to this
    SIDE: str = "SELL"                 # SELL = short straddle/strangle, BUY = long
    LOTS: int = 1                      # lots per leg
    MAX_LOTS: int = 2                  # safety cap; the script refuses more than this
    PRODUCT: str = "auto"              # auto (I for NFO/BFO, M for MCX) | I = intraday (MIS) | M = NRML
    MCX_QTY_IN_LOTS: bool = False      # MCX quantity is sent as lots x lot size (units); set True only if your
                                       # account's MCX orders expect the number of lots instead

    # ── When (IST, 24-hour HH:MM) ─────────────────────────────────────────
    ENTRY_TIME: str = "09:20"          # or "now"
    LAST_ENTRY_TIME: str | None = None # no new entry / re-entry after this (None = until EXIT_TIME)
    ENTRY_MIN_PREMIUM: float | None = None  # enter only if CE+PE LTP (points) >= this
    ENTRY_MAX_PREMIUM: float | None = None  # enter only if CE+PE LTP (points) <= this
    ENTRY_RECHECK_SECS: float = 15     # how often the entry filter is re-checked inside the window
    EXIT_TIME: str = "15:15"           # hard time exit — every open leg is closed

    # ── Stoploss & profit booking ─────────────────────────────────────────
    LEG_SL_PCT: float | None = 30.0    # per-leg SL, % move against you on that leg's premium
    LEG_SL_POINTS: float | None = None # per-leg SL in premium points (use this OR LEG_SL_PCT)
    LEG_SL_ACTION: str = "exit_leg"    # exit_leg (close only that leg) | exit_all
    MOVE_SL_TO_COST: bool = False      # after one leg's SL, move the other leg's SL to its entry price

    MTM_UNIT: str = "rupees"           # unit for the combined numbers below: rupees | points | pct
                                       # (pct = % of the combined entry premium)
    COMBINED_SL: float | None = 3000   # exit all when combined MTM <= -COMBINED_SL
    COMBINED_TARGET: float | None = 2000  # exit all when combined MTM >= COMBINED_TARGET
    TRAIL_START: float | None = None   # start trailing once MTM reaches this profit
    TRAIL_GAP: float | None = None     # then exit if MTM falls this much below its best level
    LOCK_TRIGGER: float | None = None  # profit lock: once MTM reaches this...
    LOCK_MIN: float | None = None      # ...exit if MTM falls back to this locked profit

    REENTRY_ON_SL: bool = False        # after a stoploss closes everything, enter again (fresh ATM)
    MAX_REENTRIES: int = 0             # how many re-entries per run (0-5)
    REENTRY_COOLDOWN_MINS: float = 5   # wait this long after the SL exit before re-entering

    MAX_LOSS_PER_DAY_RS: float | None = 5000  # whole-account day P&L limit (rupees)
    MAX_PROFIT_PER_DAY_RS: float | None = None  # whole-account day profit: exit all and stop

    # ── Orders ────────────────────────────────────────────────────────────
    ORDER_TYPE: str = "LIMIT"          # LIMIT (recommended for options) | MARKET
    LIMIT_BUFFER_PCT: float = 2.0      # LIMIT price = LTP ± this %, so it fills like a market order
    ENTRY_FILL_TIMEOUT_SECS: float = 20
    EXIT_FILL_TIMEOUT_SECS: float = 10
    EXIT_RETRIES: int = 5              # square-off attempts per leg (price buffer widens each time)
    MARKET_FALLBACK_ON_EXIT: bool = True  # last square-off attempt uses MARKET
    FREEZE_QTY_OVERRIDE: dict = field(default_factory=dict)
    # ^ Used only when the API does not return freeze quantity. Fill from the latest
    #   NSE / BSE circular, e.g. {"NIFTY": 1800}. Empty = rely on MAX_LOTS.

    # ── Engine ────────────────────────────────────────────────────────────
    POLL_SECONDS: float = 1.0          # how often the monitor loop checks prices
    USE_WEBSOCKET: bool = True         # needs: pip install "infinn[ticker]"
    WS_FIRST_PRICE_WAIT_SECS: float = 8  # wait this long for a first WebSocket price when REST has none
    STALE_PRICE_EXIT_SECS: float = 30  # no fresh price this long -> exit all (safety)
    HTTP_TIMEOUT_SECS: float = 10      # per request; Sandbox Limits can be slow
    CHECK_MARGIN: bool = True          # read Limits before entry (skipped if it times out)

    # ── Safety ────────────────────────────────────────────────────────────
    ENV: str = "sandbox"               # sandbox (UAT / Test — NOT live) | live
    DRY_RUN: bool = True               # True = no orders sent
    CONFIRM_LIVE: bool = False         # must be True (--confirm-live) for env=live
    SESSION_FILE: str = "infinn_session.json"  # plain JSON session from the SDK (reused today)
    LOG_FILE: str = "straddle_strangle.log"


# ═══════════════════════════════════════════════════════════════════════════
#  BUILDER SETTINGS — filled by the INFINN Strategy Builder page. Empty = the
#  Config defaults above. Command-line flags still override these values.
# ═══════════════════════════════════════════════════════════════════════════
# >>> BUILDER SETTINGS START
BUILDER_SETTINGS: dict = {}
# <<< BUILDER SETTINGS END


# Index spot tokens and option segments. Strike step is only a fallback; the
# script prefers the step it sees in the option chain.
# For index names, fut_exch / fut_search are an optional fallback: used when the
# spot quote is missing, outside px_band, or disagrees with the near-month future.
# If spot_exch is None, the future IS the reference (commodities).
UNDERLYINGS = {
    "NIFTY": {"spot_exch": "NSE", "spot_token": "26000", "spot_search": "NIFTY INDEX", "opt_exch": "NFO", "step": 50,
              "fut_exch": "NFO", "fut_search": "NIFTY", "px_band": (5000, 80000)},
    "BANKNIFTY": {"spot_exch": "NSE", "spot_token": "26009", "spot_search": "NIFTY BANK", "opt_exch": "NFO", "step": 100,
                  "fut_exch": "NFO", "fut_search": "BANKNIFTY", "px_band": (10000, 150000)},
    "SENSEX": {"spot_exch": "BSE", "spot_token": "1", "spot_search": "SENSEX", "opt_exch": "BFO", "step": 100,
               "fut_exch": "BFO", "fut_search": "SENSEX", "px_band": (20000, 200000)},
    # Commodity: no spot index — the near-month futures price is the reference.
    # Strike step 50 is from the tick-recorder ATM grid (ATM ±10×50). Lot size and tick
    # are read from the API at runtime (ls / ti). Typical published sizes — check before
    # live; no official Noren/MCX contract master was on the box: CRUDEOIL 100 bbl,
    # CRUDEOILM 10 bbl, tick 0.10 (engine tests, mcx_crude_bt, OpenAlgo/Angel scrip
    # master 2026-09-02). Session 09:00–23:30 IST; during US daylight time the close may
    # be 23:55 IST (Compliance-unconfirmed). last_entry / latest_exit below are the
    # non-DST caps; the engine extends them by 25 minutes when US DST is in effect.
    "CRUDEOIL": {"spot_exch": None, "fut_exch": "MCX", "fut_search": "CRUDEOIL", "opt_exch": "MCX", "step": 50,
                 "product": "M", "last_entry": "23:15", "latest_exit": "23:20", "px_band": (1000, 50000)},
    "CRUDEOILM": {"spot_exch": None, "fut_exch": "MCX", "fut_search": "CRUDEOILM", "opt_exch": "MCX", "step": 50,
                  "product": "M", "last_entry": "23:15", "latest_exit": "23:20", "px_band": (1000, 50000)},
}

IST = timezone(timedelta(hours=5, minutes=30))
EXPIRY_ROLL_BUFFER_MINS = 15  # on expiry day, current/auto rolls this many minutes before the close


def _nth_sunday(year: int, month: int, n: int) -> datetime:
    """n=1 is the first Sunday of the month."""
    first = datetime(year, month, 1)
    first_sun = 1 + (6 - first.weekday()) % 7
    return datetime(year, month, first_sun + (n - 1) * 7)


def us_dst_in_effect(now: datetime) -> bool:
    """True when US daylight time is in effect (2nd Sunday of March 02:00 ET to
    1st Sunday of November 02:00 ET). Used only to pick the MCX close: 23:30 IST
    normally, 23:55 IST during US DST. The calendar switch is treated as 12:30 IST
    (start) and 11:30 IST (end). The 23:55 close is Compliance-unconfirmed."""
    if now.tzinfo is not None:
        now = now.astimezone(IST)
    else:
        now = now.replace(tzinfo=IST)
    start = _nth_sunday(now.year, 3, 2).replace(hour=12, minute=30, tzinfo=IST)
    end = _nth_sunday(now.year, 11, 1).replace(hour=11, minute=30, tzinfo=IST)
    return start <= now < end


def mcx_session_times(now: datetime) -> dict:
    """MCX session close and conservative entry/exit caps for ``now`` (IST)."""
    dst = us_dst_in_effect(now)
    return {
        "close": "23:55" if dst else "23:30",
        "latest_exit": "23:45" if dst else "23:20",
        "last_entry": "23:40" if dst else "23:15",
        "dst": dst,
    }


def expiry_roll_cutoff(underlying: str, now: datetime) -> tuple[int, int]:
    """HH,MM IST at or after which EXPIRY=current/auto skips today's expiry."""
    u = UNDERLYINGS[underlying]
    close = mcx_session_times(now)["close"] if u.get("fut_exch") == "MCX" else "15:30"
    h, m = parse_hhmm(close)
    total = max(0, h * 60 + m - EXPIRY_ROLL_BUFFER_MINS)
    return divmod(total, 60)


EXIT_OK, EXIT_CONFIG, EXIT_ENTRY_FAILED, EXIT_SQUAREOFF_INCOMPLETE, EXIT_LOGIN = 0, 2, 3, 4, 5

log = logging.getLogger("straddle")


# ═══════════════════════════════════════════════════════════════════════════
#  Data
# ═══════════════════════════════════════════════════════════════════════════


class ConfigError(Exception):
    pass


class EntryFailed(Exception):
    pass


@dataclass
class Leg:
    name: str                 # "CE" or "PE"
    exch: str
    tsym: str
    token: str
    strike: float
    side: str                 # SELL or BUY (entry side)
    qty: int
    lot_size: int
    tick: float = 0.05
    entry_price: float | None = None
    filled_qty: int = 0       # currently open quantity
    exit_price: float | None = None
    sl_price: float | None = None
    ltp: float | None = None
    ltp_time: float = 0.0
    realised: float = 0.0     # rupees booked on this leg
    exit_reason: str = ""

    @property
    def is_open(self) -> bool:
        return self.filled_qty > 0

    @property
    def sign(self) -> int:
        """+1 for a BUY leg, -1 for a SELL leg (profit when price falls)."""
        return 1 if self.side == "BUY" else -1

    def points(self) -> float:
        """Per-unit P&L in premium points (open legs use LTP, closed use exit price)."""
        if self.entry_price is None:
            return 0.0
        px = self.ltp if self.is_open else self.exit_price
        if px is None:
            return 0.0
        return self.sign * (px - self.entry_price)

    def rupees(self) -> float:
        if self.is_open:
            return self.realised + self.points() * self.filled_qty
        return self.realised


# ═══════════════════════════════════════════════════════════════════════════
#  Helpers
# ═══════════════════════════════════════════════════════════════════════════


def parse_hhmm(text: str) -> tuple[int, int]:
    h, m = text.strip().split(":")
    h, m = int(h), int(m)
    if not (0 <= h < 24 and 0 <= m < 60):
        raise ValueError(text)
    return h, m


def round_to_tick(price: float, tick: float, up: bool) -> float:
    tick = tick if tick and tick > 0 else 0.05
    steps = price / tick
    steps = math.ceil(steps - 1e-9) if up else math.floor(steps + 1e-9)
    return round(max(steps, 1) * tick, 2)


def to_float(value, default: float | None = None) -> float | None:
    try:
        if value in (None, "", "NA"):
            return default
        return float(value)
    except (TypeError, ValueError):
        return default


def parse_expiry(text: str) -> datetime | None:
    for fmt in ("%d-%b-%Y", "%d%b%Y", "%d-%b-%y", "%d%b%y", "%Y-%m-%d"):
        try:
            return datetime.strptime(text.strip().title(), fmt)
        except (ValueError, AttributeError):
            continue
    return None


def retry(fn: Callable, *, tries: int = 3, delay: float = 0.7, what: str = "call", sleeper=time.sleep):
    """Retry a READ call on network/timeout errors. Never use for placing orders."""
    from infinn import InfinnNetworkError

    last = None
    for i in range(tries):
        try:
            return fn()
        except InfinnNetworkError as exc:  # timeout / connection reset
            last = exc
            log.warning("%s failed (%s), attempt %d/%d", what, type(exc).__name__, i + 1, tries)
            if i + 1 < tries:
                sleeper(delay * (i + 1))
    raise last  # type: ignore[misc]


# ═══════════════════════════════════════════════════════════════════════════
#  Strategy engine
# ═══════════════════════════════════════════════════════════════════════════


class StraddleStrangle:
    def __init__(self, api, cfg: Config, *, clock: Callable[[], datetime] | None = None,
                 sleeper: Callable[[float], None] = time.sleep, monotonic: Callable[[], float] = time.monotonic):
        self.api = api
        self.cfg = cfg
        self.now = clock or (lambda: datetime.now(IST))
        self.sleep = sleeper
        self.mono = monotonic
        self.legs: list[Leg] = []
        self.peak: float | None = None
        self.start_day_pnl: float = 0.0
        self.ticker = None
        self.run_id = self.now().strftime("%H%M%S")
        self.exit_reason = ""
        self.squareoff_ok = True
        self.reference: dict = {}
        self.ws_px: dict[str, float] = {}
        self.ws_subs: set[tuple[str, str]] = set()
        self.ws_started = -1e9
        self.cycle = 0                 # 0 = first entry, 1.. = re-entries
        self.booked_rs = 0.0           # rupees booked by earlier cycles (re-entry)
        self.history: list[Leg] = []   # legs of earlier cycles
        self.last_reason = ""          # reason that closed the last open leg
        self.no_entry = False

    @property
    def product(self) -> str:
        p = (self.cfg.PRODUCT or "auto").strip().upper()
        if p == "AUTO":
            return UNDERLYINGS[self.cfg.UNDERLYING].get("product", "I")
        return p

    # ── public entry point ────────────────────────────────────────────────
    def run(self) -> int:
        try:
            self.validate()
            self.preflight()
            self.wait_until_entry()
            while True:
                if not self.wait_entry_filter():
                    break
                self.check_quantity()
                self.enter()
                self.monitor()
                if not self.squareoff_ok or not self.want_reentry():
                    break
                self.next_cycle()
        except ConfigError as exc:
            log.error("CONFIG: %s", exc)
            return EXIT_CONFIG
        except EntryFailed as exc:
            log.error("ENTRY FAILED: %s", exc)
            self.square_off("ENTRY_FAILED")
            return EXIT_SQUAREOFF_INCOMPLETE if not self.squareoff_ok else EXIT_ENTRY_FAILED
        except KeyboardInterrupt:
            log.warning("Ctrl+C received — squaring off all open legs")
            self.square_off("CTRL_C")
        except Exception as exc:
            log.exception("Unexpected error: %s — squaring off all open legs", type(exc).__name__)
            self.square_off("ERROR")
            return EXIT_SQUAREOFF_INCOMPLETE if not self.squareoff_ok else EXIT_ENTRY_FAILED
        finally:
            self.stop_ticker()
            self.summary()
        return EXIT_OK if self.squareoff_ok else EXIT_SQUAREOFF_INCOMPLETE

    # ── 1. validate config ────────────────────────────────────────────────
    def validate(self) -> None:
        c = self.cfg
        c.UNDERLYING = c.UNDERLYING.strip().upper()
        c.MODE = c.MODE.strip().lower()
        c.SIDE = c.SIDE.strip().upper()
        c.ORDER_TYPE = c.ORDER_TYPE.strip().upper()
        c.MTM_UNIT = c.MTM_UNIT.strip().lower()
        c.ENV = c.ENV.strip().lower()
        if c.UNDERLYING not in UNDERLYINGS:
            raise ConfigError(f"UNDERLYING must be one of {list(UNDERLYINGS)}")
        if c.MODE not in ("straddle", "strangle"):
            raise ConfigError("MODE must be straddle or strangle")
        if c.SIDE not in ("SELL", "BUY"):
            raise ConfigError("SIDE must be SELL or BUY")
        if c.ORDER_TYPE not in ("LIMIT", "MARKET"):
            raise ConfigError("ORDER_TYPE must be LIMIT or MARKET")
        if c.MTM_UNIT not in ("rupees", "points", "pct"):
            raise ConfigError("MTM_UNIT must be rupees, points or pct")
        if c.LEG_SL_ACTION not in ("exit_leg", "exit_all"):
            raise ConfigError("LEG_SL_ACTION must be exit_leg or exit_all")
        if not (1 <= int(c.LOTS) <= int(c.MAX_LOTS)):
            raise ConfigError(f"LOTS must be between 1 and MAX_LOTS ({c.MAX_LOTS})")
        c.STRANGLE_BY = str(c.STRANGLE_BY).strip().lower()
        c.EXPIRY = str(c.EXPIRY).strip()
        if c.STRANGLE_BY not in ("points", "strikes", "premium"):
            raise ConfigError("STRANGLE_BY must be points, strikes or premium")
        if c.MODE == "strangle" and c.STRANGLE_BY == "points" and c.STRANGLE_OTM_POINTS <= 0:
            raise ConfigError("STRANGLE_OTM_POINTS must be > 0 for a strangle")
        if c.MODE == "strangle" and c.STRANGLE_BY == "strikes" and not (1 <= int(c.STRANGLE_OTM_STRIKES) <= 20):
            raise ConfigError("STRANGLE_OTM_STRIKES must be 1-20")
        if c.MODE == "strangle" and c.STRANGLE_BY == "premium" and not (c.STRANGLE_PREMIUM and c.STRANGLE_PREMIUM > 0):
            raise ConfigError("STRANGLE_PREMIUM must be > 0")
        if c.EXPIRY.lower() not in ("auto", "current", "next", "monthly") and parse_expiry(c.EXPIRY) is None:
            raise ConfigError("EXPIRY must be auto, current, next, monthly or a date like 25-NOV-2026")
        if c.LEG_SL_PCT is not None and c.LEG_SL_POINTS is not None:
            raise ConfigError("set LEG_SL_PCT or LEG_SL_POINTS, not both")
        if (c.LOCK_TRIGGER is None) != (c.LOCK_MIN is None):
            raise ConfigError("set both LOCK_TRIGGER and LOCK_MIN, or neither")
        if c.LOCK_TRIGGER is not None and not (0 <= c.LOCK_MIN < c.LOCK_TRIGGER):
            raise ConfigError("LOCK_MIN must be >= 0 and below LOCK_TRIGGER")
        if (c.ENTRY_MIN_PREMIUM is not None and c.ENTRY_MAX_PREMIUM is not None
                and c.ENTRY_MIN_PREMIUM > c.ENTRY_MAX_PREMIUM):
            raise ConfigError("ENTRY_MIN_PREMIUM is above ENTRY_MAX_PREMIUM")
        if not (0 <= int(c.MAX_REENTRIES) <= 5):
            raise ConfigError("MAX_REENTRIES must be 0-5")
        if c.REENTRY_COOLDOWN_MINS < 0:
            raise ConfigError("REENTRY_COOLDOWN_MINS must be >= 0")
        if c.LAST_ENTRY_TIME:
            if parse_hhmm(c.LAST_ENTRY_TIME) > parse_hhmm(c.EXIT_TIME):
                raise ConfigError("LAST_ENTRY_TIME must be before EXIT_TIME")
            if c.ENTRY_TIME.lower() != "now" and parse_hhmm(c.LAST_ENTRY_TIME) < parse_hhmm(c.ENTRY_TIME):
                raise ConfigError("LAST_ENTRY_TIME must not be before ENTRY_TIME")
        if (c.TRAIL_START is None) != (c.TRAIL_GAP is None):
            raise ConfigError("set both TRAIL_START and TRAIL_GAP, or neither")
        for name in ("COMBINED_SL", "COMBINED_TARGET", "TRAIL_GAP", "LEG_SL_PCT", "LEG_SL_POINTS",
                     "MAX_LOSS_PER_DAY_RS", "MAX_PROFIT_PER_DAY_RS", "LOCK_TRIGGER",
                     "ENTRY_MIN_PREMIUM", "ENTRY_MAX_PREMIUM"):
            v = getattr(c, name)
            if v is not None and v <= 0:
                raise ConfigError(f"{name} must be a positive number (or None to switch it off)")
        parse_hhmm(c.EXIT_TIME)
        latest = self.session_caps().get("latest_exit")
        if latest and parse_hhmm(c.EXIT_TIME) > parse_hhmm(latest):
            log.warning("EXIT_TIME %s is too close to the session end — using %s IST", c.EXIT_TIME, latest)
            c.EXIT_TIME = latest
        if c.ENTRY_TIME.lower() != "now":
            parse_hhmm(c.ENTRY_TIME)
        if c.ENV in ("live", "prod", "production"):
            if not c.CONFIRM_LIVE:
                raise ConfigError("ENV=live needs --confirm-live. Test on Sandbox (UAT / Test — NOT live) first.")
        elif c.ENV not in ("sandbox", "uat", "test"):
            raise ConfigError("ENV must be sandbox or live")
        if getattr(self.api, "env", "sandbox") != ("live" if c.ENV in ("live", "prod", "production") else "sandbox"):
            raise ConfigError("SDK client env does not match Config.ENV")
        log.info("Config OK: %s %s %s x%d lot(s) | env=%s | DRY_RUN=%s",
                 c.SIDE, c.UNDERLYING, c.MODE, c.LOTS, c.ENV, c.DRY_RUN)

    # ── 2. preflight: day P&L and margin ──────────────────────────────────
    def preflight(self) -> None:
        pnl = self.day_pnl()
        self.start_day_pnl = pnl or 0.0
        log.info("Account day P&L before entry: %.2f", self.start_day_pnl)
        lim = self.cfg.MAX_LOSS_PER_DAY_RS
        if lim is not None and self.start_day_pnl <= -lim:
            raise ConfigError(f"day loss {self.start_day_pnl:.2f} already beyond MAX_LOSS_PER_DAY_RS {lim}")
        if self.cfg.CHECK_MARGIN:
            try:
                limits = self.api.limits()  # Sandbox Limits may time out — not fatal
                cash = to_float(limits.get("cash")) if isinstance(limits, dict) else None
                log.info("Limits read OK%s", f" (cash {cash:.2f})" if cash is not None else "")
            except Exception as exc:
                log.warning("Limits not available (%s) — continuing; the broker RMS still checks margin",
                            type(exc).__name__)

    def day_pnl(self) -> float | None:
        """Realised + unrealised P&L across today's positions (whole account)."""
        from infinn import InfinnAPIError

        try:
            rows = retry(self.api.positions, what="PositionBook", sleeper=self.sleep)
        except InfinnAPIError as exc:
            if "no data" in str(exc).lower():
                return 0.0
            log.warning("PositionBook error: %s", exc)
            return None
        except Exception as exc:
            log.warning("PositionBook unavailable (%s)", type(exc).__name__)
            return None
        if not isinstance(rows, list):
            return 0.0
        return sum((to_float(r.get("rpnl"), 0.0) or 0.0) + (to_float(r.get("urmtom"), 0.0) or 0.0) for r in rows)

    # ── 3. wait for entry time ────────────────────────────────────────────
    def session_caps(self) -> dict:
        """Close, last_entry and latest_exit for this underlying at self.now()."""
        u = UNDERLYINGS[self.cfg.UNDERLYING]
        if u.get("fut_exch") == "MCX":
            return mcx_session_times(self.now())
        return {"close": "15:30", "latest_exit": u.get("latest_exit"), "last_entry": u.get("last_entry"), "dst": False}

    def wait_until_entry(self) -> None:
        eh, em = parse_hhmm(self.cfg.EXIT_TIME)
        caps = self.session_caps()
        last = caps.get("last_entry")
        close_lbl = caps.get("close") or "15:30"
        if last:
            le = parse_hhmm(last)
            n = self.now()
            if (n.hour, n.minute) >= le:
                raise ConfigError(f"no new {self.cfg.UNDERLYING} entry after {last} IST (session ends {close_lbl})")
        if self.cfg.ENTRY_TIME.lower() == "now":
            now = self.now()
            if (now.hour, now.minute) >= (eh, em):
                raise ConfigError(f"it is already past EXIT_TIME {self.cfg.EXIT_TIME} — use --exit HH:MM")
            return
        h, m = parse_hhmm(self.cfg.ENTRY_TIME)
        while True:
            now = self.now()
            if (now.hour, now.minute) >= (eh, em):
                raise ConfigError("entry time is after EXIT_TIME — nothing to do today")
            if last and (now.hour, now.minute) >= parse_hhmm(last):
                raise ConfigError(f"no new {self.cfg.UNDERLYING} entry after {last} IST (session ends {close_lbl})")
            if (now.hour, now.minute) >= (h, m):
                return
            log.info("Waiting for entry time %s IST (now %s)", self.cfg.ENTRY_TIME, now.strftime("%H:%M:%S"))
            self.sleep(min(30.0, max(1.0, ((h * 60 + m) - (now.hour * 60 + now.minute)) * 60 - now.second)))

    # ── 4. find ATM and the two contracts ─────────────────────────────────
    def futures_price(self) -> float:
        """Near-month futures LTP (commodities have no spot index)."""
        c = self.cfg
        u = UNDERLYINGS[c.UNDERLYING]
        res = retry(lambda: self.api.search_instrument(u["fut_search"], u["fut_exch"]),
                    what="futures search", sleeper=self.sleep)
        rows = (res.get("values") or []) if isinstance(res, dict) else []
        n = len(c.UNDERLYING)
        futs = []
        for r in rows:
            tsym = str(r.get("tsym", "")).upper()
            inst = str(r.get("instname", "")).upper()
            optt = str(r.get("optt", "")).upper()
            if not (tsym.startswith(c.UNDERLYING) and tsym[n:n + 1].isdigit()):   # CRUDEOIL skips the mini, and vice versa
                continue
            if inst.startswith("OPT") or optt in ("CE", "PE"):
                continue
            if inst and not inst.startswith("FUT"):
                continue
            exd = r.get("exd")
            if not exd:
                try:
                    exd = self.api.security_info(u["fut_exch"], r["token"]).get("exd")
                except Exception:
                    exd = None
            d = parse_expiry(exd) if exd else None
            if d is not None:
                futs.append((d, r))
        today = self.now().replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)
        futs = sorted([x for x in futs if x[0] >= today], key=lambda x: x[0])
        if not futs:
            raise EntryFailed(f"no {c.UNDERLYING} futures contract found on {u['fut_exch']}")
        n = self.now()
        if futs[0][0].date() == today.date():
            ch, cm = expiry_roll_cutoff(c.UNDERLYING, n)
            later = [x for x in futs if x[0].date() > today.date()]
            if (n.hour, n.minute) >= (ch, cm) and later:
                log.info("Front-month future expires today and it is at or after %02d:%02d IST — using the next contract %s",
                         ch, cm, later[0][1].get("tsym"))
                futs = later
        d, fut = futs[0]
        px = retry(lambda: self.api.ltp(u["fut_exch"], fut["token"]), what="futures LTP", sleeper=self.sleep)
        if not px and c.USE_WEBSOCKET:
            log.info("No REST price for %s — trying the WebSocket feed", fut.get("tsym"))
            px = self.wait_ws_price(u["fut_exch"], str(fut["token"]), c.WS_FIRST_PRICE_WAIT_SECS)
        if not px:
            raise EntryFailed(f"no price for {fut.get('tsym')} from REST or WebSocket"
                              + (" (Sandbox MCX sends no prices — test CRUDEOIL/CRUDEOILM on live data only after Kamal's OK)"
                                 if self.cfg.ENV == "sandbox" else ""))
        self.reference = {"tsym": fut.get("tsym"), "token": str(fut.get("token")), "expiry": d.strftime("%d-%b-%Y")}
        log.info("Reference price: near-month future %s (exp %s) LTP %.2f", fut.get("tsym"), self.reference["expiry"], float(px))
        return float(px)

    def _sane_px(self, px, label: str) -> float | None:
        """Drop missing, non-numeric, non-positive, or obviously out-of-band quotes."""
        try:
            v = float(px)
        except (TypeError, ValueError):
            return None
        if not math.isfinite(v) or v <= 0:
            return None
        band = UNDERLYINGS[self.cfg.UNDERLYING].get("px_band")
        if band and not (band[0] <= v <= band[1]):
            log.warning("%s %.2f is outside the sanity band %.0f–%.0f — ignoring it", label, v, band[0], band[1])
            return None
        return v

    def _try_index_futures(self) -> float | None:
        """Near-month futures LTP for an index. Optional; never used as the only source for commodities."""
        u = UNDERLYINGS[self.cfg.UNDERLYING]
        if not u.get("spot_exch") or not u.get("fut_exch"):
            return None
        try:
            return self._sane_px(self.futures_price(), "index futures")
        except Exception as exc:
            log.info("index futures fallback not used (%s)", type(exc).__name__ if not str(exc) else exc)
            return None

    def _spot_from_search(self) -> float | None:
        u = UNDERLYINGS[self.cfg.UNDERLYING]
        try:
            res = retry(lambda: self.api.search_instrument(u["spot_search"], u["spot_exch"]),
                        what="spot search", sleeper=self.sleep)
        except Exception as exc:
            log.warning("spot search failed (%s)", type(exc).__name__)
            return None
        for row in (res.get("values") or []) if isinstance(res, dict) else []:
            if str(row.get("instname", "")).upper() == "INDEX" or str(row.get("tsym", "")).upper() == u["spot_search"]:
                try:
                    px = retry(lambda: self.api.ltp(u["spot_exch"], row["token"]), what="spot LTP", sleeper=self.sleep)
                except Exception:
                    px = None
                px = self._sane_px(px, "spot search LTP")
                if px:
                    return px
        return None

    def spot_price(self) -> float:
        # A forced reference is set when CE/PE premiums show the first ATM was wrong.
        forced = getattr(self, "_forced_ref", None)
        if forced:
            return float(forced)
        u = UNDERLYINGS[self.cfg.UNDERLYING]
        # Commodities have no spot index — the near-month future is the reference.
        if not u.get("spot_exch") and u.get("fut_exch"):
            return self.futures_price()
        token_px = None
        try:
            token_px = self._sane_px(
                retry(lambda: self.api.ltp(u["spot_exch"], u["spot_token"]), what="spot LTP", sleeper=self.sleep),
                "spot LTP by token",
            )
        except Exception as exc:
            log.warning("spot LTP by token failed (%s) — trying symbol search", type(exc).__name__)
        search_px = self._spot_from_search() if not token_px else None
        spot_px = token_px or search_px
        fut_px = self._try_index_futures()
        if fut_px and spot_px and abs(fut_px - spot_px) / spot_px > 0.015:
            log.warning(
                "spot %.2f and near-month futures %.2f disagree by more than 1.5%% — using futures as the ATM reference",
                spot_px, fut_px,
            )
            return fut_px
        if fut_px and not spot_px:
            log.info("spot unavailable or rejected — using near-month futures %.2f as the ATM reference", fut_px)
            return fut_px
        if spot_px:
            if token_px:
                log.info("%s spot by token: %.2f", self.cfg.UNDERLYING, spot_px)
            else:
                log.info("%s spot by symbol search: %.2f", self.cfg.UNDERLYING, spot_px)
            return spot_px
        raise EntryFailed(f"could not read {self.cfg.UNDERLYING} spot or futures price")

    def resolve_legs(self) -> None:
        c = self.cfg
        u = UNDERLYINGS[c.UNDERLYING]
        spot = self.spot_price()
        step = u["step"]
        atm = round(spot / step) * step
        log.info("%s reference price %.2f -> ATM %d (step %d)", c.UNDERLYING, spot, atm, step)

        seed = self.find_seed_contract(atm)
        by = c.STRANGLE_BY if c.MODE == "strangle" else "points"
        dist = 0 if c.MODE == "straddle" else (c.STRANGLE_OTM_POINTS if by == "points" else 0)
        if by == "strikes":
            need = int(c.STRANGLE_OTM_STRIKES) + 3
        elif by == "premium":
            need = 15
        else:
            need = int(math.ceil(dist / step)) + 3
        chain = retry(lambda: self.api.option_chain(u["opt_exch"], seed["tsym"], atm, count=need),
                      what="option chain", sleeper=self.sleep)
        if not chain:
            raise EntryFailed("option chain is empty")
        strikes = sorted({to_float(r.get("strprc")) for r in chain if to_float(r.get("strprc"))})
        if len(strikes) >= 2:
            step = min(b - a for a, b in zip(strikes, strikes[1:]) if b > a) or step
            atm = round(spot / step) * step
        if by == "strikes":
            dist = int(c.STRANGLE_OTM_STRIKES) * step
        ce_strike = atm + (round(dist / step) * step if dist else 0)
        pe_strike = atm - (round(dist / step) * step if dist else 0)
        if by == "premium":
            ce_strike = self.strike_by_premium(chain, "CE", atm, u["opt_exch"])
            pe_strike = self.strike_by_premium(chain, "PE", atm, u["opt_exch"])

        def pick(optt: str, strike: float) -> dict:
            for r in chain:
                if str(r.get("optt", "")).upper() == optt and abs((to_float(r.get("strprc")) or -1) - strike) < 1e-6:
                    return r
            raise EntryFailed(f"{optt} {strike:g} not found in option chain")

        self.legs = []
        for name, strike in (("CE", ce_strike), ("PE", pe_strike)):
            row = pick(name, strike)
            lot = int(to_float(row.get("ls"), 0) or 0)
            tick = to_float(row.get("ti"), 0.0) or 0.0
            if lot <= 0 or tick <= 0:
                info = retry(lambda: self.api.security_info(u["opt_exch"], row["token"]),
                             what="security info", sleeper=self.sleep)
                lot = lot or int(to_float(info.get("ls"), 0) or 0)
                tick = tick or to_float(info.get("ti"), 0.05) or 0.05
            if lot <= 0:
                raise EntryFailed(f"lot size not available for {row.get('tsym')}")
            self.legs.append(Leg(name=name, exch=u["opt_exch"], tsym=row["tsym"], token=str(row["token"]),
                                 strike=strike, side=c.SIDE, qty=int(c.LOTS) * lot, lot_size=lot, tick=tick))
        for leg in self.legs:
            log.info("Leg %s: %s %s qty %d (lot %d, tick %.2f)", leg.name, leg.side, leg.tsym, leg.qty, leg.lot_size, leg.tick)
        self._atm_spot_used = spot
        self._atm_step_used = step

    def _check_atm_premiums(self) -> bool:
        """If CE and PE last prices already on the legs look very uneven, the
        index quote may be wrong. Try the near-month future once, then re-pick.
        Uses leg.ltp set by refresh_price, so it does not make extra LTP calls.
        Returns True if legs were re-picked (caller must refresh prices again).
        Live verification of SENSEX BSE|1 on Sandbox is still pending (market hours).
        """
        if getattr(self, "_atm_rechecked", False):
            return False
        ce = next((l for l in self.legs if l.name == "CE"), None)
        pe = next((l for l in self.legs if l.name == "PE"), None)
        if not ce or not pe:
            return False
        ce_px, pe_px = ce.ltp, pe.ltp
        if not ce_px or not pe_px or min(ce_px, pe_px) <= 0:
            return False
        ratio = max(ce_px, pe_px) / min(ce_px, pe_px)
        # A true ATM straddle has similar premiums. 4x (or more) is a clear red flag.
        # The 12 Nov Sandbox SENSEX run saw CE 158.95 vs PE 3650 at strike 75500.
        if ratio < 4.0:
            return False
        spot = getattr(self, "_atm_spot_used", None)
        step = getattr(self, "_atm_step_used", None) or UNDERLYINGS[self.cfg.UNDERLYING]["step"]
        log.warning(
            "CE LTP %.2f and PE LTP %.2f at strikes %g / %g look very uneven (%.1fx). "
            "The index price %s may be wrong — checking the near-month future",
            ce_px, pe_px, ce.strike, pe.strike, ratio,
            ("%.2f" % spot) if spot is not None else "unknown",
        )
        fut = self._try_index_futures()
        if not fut:
            log.warning("No futures reference to correct the ATM. Check the strikes before any live use.")
            return False
        new_atm = round(fut / step) * step
        old_atm = round((spot if spot is not None else new_atm) / step) * step
        if abs(new_atm - old_atm) < step:
            log.info("Futures %.2f rounds to the same ATM %d — leaving strikes as they are", fut, old_atm)
            return False
        log.warning("Re-picking legs from futures %.2f -> ATM %d (was %d)", fut, new_atm, old_atm)
        self._forced_ref = fut
        self._atm_rechecked = True
        self.resolve_legs()
        return True

    def strike_by_premium(self, chain: list, optt: str, atm: float, exch: str) -> float:
        """OTM strike (CE above ATM, PE below) whose LTP is closest to STRANGLE_PREMIUM."""
        want = float(self.cfg.STRANGLE_PREMIUM)
        best = None
        for r in chain:
            k = to_float(r.get("strprc"))
            if str(r.get("optt", "")).upper() != optt or k is None:
                continue
            if (optt == "CE" and k <= atm) or (optt == "PE" and k >= atm):
                continue
            try:
                px = to_float(self.api.ltp(r.get("exch") or exch, str(r["token"])))
            except Exception:
                px = None
            if not px or px <= 0:
                continue
            key = (abs(px - want), abs(k - atm))
            if best is None or key < best[0]:
                best = (key, k, px)
        if best is None:
            raise EntryFailed(f"no {optt} prices in the option chain to pick a strike by premium")
        log.info("%s by premium: strike %g LTP %.2f (wanted %.2f)", optt, best[1], best[2], want)
        return best[1]

    def find_seed_contract(self, atm: float) -> dict:
        """Any option on the chosen expiry — the option chain call needs one symbol."""
        c = self.cfg
        u = UNDERLYINGS[c.UNDERLYING]
        res = retry(lambda: self.api.search_instrument(f"{c.UNDERLYING} {int(atm)}", u["opt_exch"]),
                    what="option search", sleeper=self.sleep)
        rows = (res.get("values") or []) if isinstance(res, dict) else []
        n = len(c.UNDERLYING)
        cands = [r for r in rows
                 if str(r.get("tsym", "")).upper().startswith(c.UNDERLYING)
                 and str(r.get("tsym", ""))[n:n + 1].isdigit()          # skips NIFTYNXT50 etc.
                 and (str(r.get("optt", "")).upper() in ("CE", "PE") or str(r.get("instname", "")).upper().startswith("OPT"))]
        if not cands:
            raise EntryFailed(f"no {c.UNDERLYING} options found for strike {int(atm)}")
        today = self.now().replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)
        dated = []
        mode = c.EXPIRY.lower()
        for r in cands[:12 if mode in ("auto", "current") else 40]:
            exd = r.get("exd")
            if not exd:
                try:
                    exd = self.api.security_info(u["opt_exch"], r["token"]).get("exd")
                except Exception:
                    exd = None
            d = parse_expiry(exd) if exd else None
            if d is not None:
                dated.append((d, r))
        future = sorted([(d, r) for d, r in dated if d >= today], key=lambda x: x[0])
        if mode == "next":
            days = sorted({d for d, _ in future})
            if len(days) < 2:
                raise EntryFailed("next expiry not found; set EXPIRY to a date")
            log.info("Next expiry: %s", days[1].strftime("%d-%b-%Y"))
            return next(r for d, r in future if d == days[1])
        if mode == "monthly":
            if not future:
                raise EntryFailed("could not work out the monthly expiry; set EXPIRY to a date")
            first = future[0][0]
            d, r = max([x for x in future if (x[0].year, x[0].month) == (first.year, first.month)], key=lambda x: x[0])
            log.info("Monthly expiry: %s", d.strftime("%d-%b-%Y"))
            return r
        if mode not in ("auto", "current"):
            want = parse_expiry(c.EXPIRY)
            if want is None:
                raise ConfigError("EXPIRY must look like 25-NOV-2026 (or 'auto')")
            for d, r in dated:
                if d.date() == want.date():
                    return r
            raise EntryFailed(f"no contract for expiry {c.EXPIRY}")
        if future:
            n = self.now()
            first = future[0][0]
            if first.date() == today.date():
                ch, cm = expiry_roll_cutoff(c.UNDERLYING, n)
                if (n.hour, n.minute) >= (ch, cm):
                    later = [x for x in future if x[0].date() > today.date()]
                    if later:
                        log.info("Today is expiry day and it is at or after %02d:%02d IST — using the next expiry %s",
                                 ch, cm, later[0][0].strftime("%d-%b-%Y"))
                        return later[0][1]
                    raise EntryFailed(
                        f"today is expiry day for {c.UNDERLYING} and it is at or after "
                        f"{ch:02d}:{cm:02d} IST, but no later expiry was found"
                    )
            log.info("Nearest expiry: %s", first.strftime("%d-%b-%Y"))
            return future[0][1]
        raise EntryFailed("could not work out the nearest expiry; set EXPIRY explicitly")

    # ── 5. lot size / freeze quantity checks ──────────────────────────────
    def check_quantity(self) -> None:
        c = self.cfg
        for leg in self.legs:
            if leg.qty % leg.lot_size:
                raise ConfigError(f"{leg.tsym}: qty {leg.qty} is not a multiple of lot size {leg.lot_size}")
            freeze = None
            try:
                info = self.api.security_info(leg.exch, leg.token)
                freeze = to_float(info.get("frzqty"))
            except Exception as exc:
                log.debug("security_info for freeze qty failed: %s", exc)
            if not freeze:
                freeze = to_float(c.FREEZE_QTY_OVERRIDE.get(c.UNDERLYING))
            if freeze:
                if leg.qty > freeze:
                    raise ConfigError(f"{leg.tsym}: qty {leg.qty} is above freeze qty {freeze:g} — reduce LOTS")
                log.info("%s qty %d within freeze qty %g", leg.tsym, leg.qty, freeze)
            else:
                log.info("%s: freeze qty not returned by API; MAX_LOTS=%d cap applies", leg.tsym, c.MAX_LOTS)

    # ── prices ────────────────────────────────────────────────────────────
    # REST GetQuotes is tried first; the WebSocket touchline feed is used when it is
    # connected (and is the only price source on some Sandbox segments, e.g. MCX).
    ATO_SENTINEL = 42949672.95

    def ensure_ticker(self, instruments: list[tuple[str, str]]) -> None:
        if not self.cfg.USE_WEBSOCKET or not hasattr(self.api, "ticker"):
            return
        for exch, token in instruments:
            self.ws_subs.add((exch, str(token)))
        t = self.ticker
        if t is not None and (getattr(t, "connected", False) or self.mono() - self.ws_started < 10):
            try:
                t.subscribe(list(self.ws_subs))
            except Exception:
                pass
            return
        if t is not None:  # dropped: reconnect (at most every 10 s)
            log.warning("WebSocket disconnected — reconnecting")
            self.stop_ticker()
        try:
            t = self.api.ticker()

            def on_ticks(ticks):
                for tk in ticks:
                    lp = to_float(tk.get("lp"))
                    if lp and lp > 0 and abs(lp - self.ATO_SENTINEL) > 1e-6:
                        self.ws_px[str(tk.get("tk", ""))] = lp

            t.on_ticks = on_ticks
            t.on_error = lambda e: log.debug("ticker error: %s", type(e).__name__)
            t.subscribe(list(self.ws_subs))
            t.connect(threaded=True)
            self.ticker, self.ws_started = t, self.mono()
            log.info("WebSocket price feed started (REST polling is the fallback)")
        except Exception as exc:
            log.info("WebSocket not used (%s) — polling prices over REST", type(exc).__name__)
            self.ticker = None

    def ws_connected(self) -> bool:
        return self.ticker is not None and bool(getattr(self.ticker, "connected", False))

    def wait_ws_price(self, exch: str, token: str, wait: float) -> float | None:
        self.ensure_ticker([(exch, token)])
        if self.ticker is None:
            return None
        t0 = self.mono()
        while self.mono() - t0 < wait:
            px = self.ws_px.get(str(token))
            if px:
                return px
            self.sleep(0.25)
        return self.ws_px.get(str(token))

    def stop_ticker(self) -> None:
        if self.ticker is not None:
            try:
                self.ticker.close()
            except Exception:
                pass
            self.ticker = None

    def refresh_price(self, leg: Leg) -> float | None:
        ws = self.ws_px.get(leg.token)
        if ws and self.ws_connected():
            leg.ltp, leg.ltp_time = ws, self.mono()   # live connection = fresh price
            return leg.ltp
        try:
            px = self.api.ltp(leg.exch, leg.token)
            if px and px > 0:
                leg.ltp, leg.ltp_time = float(px), self.mono()
                return leg.ltp
        except Exception as exc:
            log.warning("price for %s failed (%s)", leg.tsym, type(exc).__name__)
        if leg.ltp is None and self.cfg.USE_WEBSOCKET:
            px = self.wait_ws_price(leg.exch, leg.token, self.cfg.WS_FIRST_PRICE_WAIT_SECS)
            if px:
                leg.ltp, leg.ltp_time = px, self.mono()
        return leg.ltp

    # ── orders ────────────────────────────────────────────────────────────
    def limit_price(self, leg: Leg, txn: str, attempt: int = 0) -> float:
        ltp = leg.ltp or 0.0
        buf = self.cfg.LIMIT_BUFFER_PCT / 100.0 * (attempt + 1)
        if txn == "BUY":
            return round_to_tick(ltp * (1 + buf) + leg.tick, leg.tick, up=True)
        return round_to_tick(max(ltp * (1 - buf) - leg.tick, leg.tick), leg.tick, up=False)

    def send_order(self, leg: Leg, txn: str, qty: int, tag: str, *, market: bool = False, attempt: int = 0) -> tuple[str, float]:
        """Place one order. Returns (order_id, price_used). Never retried blindly."""
        from infinn import InfinnNetworkError

        use_market = market or self.cfg.ORDER_TYPE == "MARKET"
        price = 0.0 if use_market else self.limit_price(leg, txn, attempt)
        log.info("%sORDER %s %s qty %d %s%s [%s]", "DRY-RUN " if self.cfg.DRY_RUN else "", txn, leg.tsym, qty,
                 "MARKET" if use_market else "LIMIT ", "" if use_market else f"{price:.2f}", tag)
        if self.cfg.DRY_RUN:
            return f"DRY-{tag}", price
        try:
            res = self.api.place_order(exchange=leg.exch, tradingsymbol=leg.tsym, transaction_type=txn,
                                       quantity=self.order_qty(leg, qty), order_type="MARKET" if use_market else "LIMIT",
                                       product=self.product, price=price, tag=tag)
        except InfinnNetworkError:
            # The request may have reached the server. Look for our tag before doing anything else.
            log.warning("PlaceOrder timed out — checking the order book for tag %s", tag)
            self.sleep(1.0)
            oid = self.find_order_by_tag(tag)
            if oid:
                return oid, price
            raise
        oid = str(res.get("norenordno") or "")
        if not oid:
            raise RuntimeError(f"PlaceOrder returned no order id: {res.get('emsg') or res}")
        return oid, price

    def order_qty(self, leg: Leg, qty: int) -> int:
        """Units by default; number of lots for MCX only if MCX_QTY_IN_LOTS is set."""
        if leg.exch == "MCX" and self.cfg.MCX_QTY_IN_LOTS:
            return qty // leg.lot_size
        return qty

    def find_order_by_tag(self, tag: str) -> str | None:
        try:
            book = retry(self.api.orders, what="OrderBook", sleeper=self.sleep)
        except Exception:
            return None
        for o in book if isinstance(book, list) else []:
            if str(o.get("remarks", "")) == tag:
                return str(o.get("norenordno"))
        return None

    def wait_fill(self, leg: Leg, oid: str, qty: int, timeout: float, dry_price: float) -> tuple[str, int, float | None]:
        """Wait for an order to finish. Returns (status, filled_qty, avg_price)."""
        if self.cfg.DRY_RUN:
            return "COMPLETE", qty, leg.ltp  # simulated fill at the live price
        t0 = self.mono()
        status, filled, avg = "PENDING", 0, None
        while True:
            try:
                hist = self.api.order_history(oid)
                row = hist[0] if isinstance(hist, list) and hist else (hist if isinstance(hist, dict) else {})
                status = str(row.get("status", "")).upper()
                filled = int(to_float(row.get("fillshares"), 0) or 0)
                avg = to_float(row.get("avgprc"))
                if status in ("COMPLETE", "REJECTED", "CANCELED", "CANCELLED"):
                    if status == "REJECTED":
                        log.error("Order %s rejected: %s", oid, row.get("rejreason", ""))
                    return status, filled, avg
            except Exception as exc:
                log.warning("order status %s failed (%s)", oid, type(exc).__name__)
            if self.mono() - t0 >= timeout:
                return status or "TIMEOUT", filled, avg
            self.sleep(0.5)

    def cancel(self, oid: str) -> None:
        if self.cfg.DRY_RUN:
            return
        try:
            self.api.cancel_order(oid)
        except Exception as exc:
            log.warning("cancel %s failed (%s)", oid, type(exc).__name__)

    # ── 6. entry ──────────────────────────────────────────────────────────
    def enter(self) -> None:
        self.ensure_ticker([(leg.exch, leg.token) for leg in self.legs])
        for leg in self.legs:
            if not self.refresh_price(leg):
                raise EntryFailed(f"no price for {leg.tsym}")
        if self._check_atm_premiums():
            for leg in self.legs:
                if not self.refresh_price(leg):
                    raise EntryFailed(f"no price for {leg.tsym}")
        for leg in self.legs:
            tag = f"SS{self.run_id}{self.cyc()}{leg.name}E"
            oid, px = self.send_order(leg, leg.side, leg.qty, tag)
            status, filled, avg = self.wait_fill(leg, oid, leg.qty, self.cfg.ENTRY_FILL_TIMEOUT_SECS, px)
            if status not in ("COMPLETE", "REJECTED", "CANCELED", "CANCELLED") and filled < leg.qty:
                self.cancel(oid)
                # re-read once after cancel: a fill may have landed in between
                if not self.cfg.DRY_RUN:
                    _, filled2, avg2 = self.wait_fill(leg, oid, leg.qty, 3, px)
                    filled, avg = max(filled, filled2), avg2 or avg
            if filled > 0:
                leg.filled_qty = filled
                leg.entry_price = avg or leg.ltp
            if filled < leg.qty:
                raise EntryFailed(f"{leg.tsym} filled {filled}/{leg.qty} (status {status}) — not trading a half position")
            self.set_leg_sl(leg)
            log.info("ENTRY %s %s %d @ %.2f%s", leg.side, leg.tsym, leg.filled_qty, leg.entry_price,
                     f" | leg SL {leg.sl_price:.2f}" if leg.sl_price else "")

    def set_leg_sl(self, leg: Leg) -> None:
        pct = self.cfg.LEG_SL_PCT
        pts = self.cfg.LEG_SL_POINTS
        if leg.entry_price is not None and pct is None and pts is not None:
            d = pts if leg.side == "SELL" else -pts
            leg.sl_price = round(max(leg.entry_price + d, 0.0), 2)
            return
        if pct is None or leg.entry_price is None:
            leg.sl_price = None
            return
        f = (1 + pct / 100.0) if leg.side == "SELL" else (1 - pct / 100.0)
        leg.sl_price = round(leg.entry_price * f, 2)

    # ── 7. monitor ────────────────────────────────────────────────────────
    def mtm(self) -> float:
        """Combined MTM in the configured unit (rupees or points)."""
        if self.cfg.MTM_UNIT == "points":
            return sum(leg.points() for leg in self.legs)
        if self.cfg.MTM_UNIT == "pct":
            prem = self.entry_premium_rs()
            return 100.0 * self.mtm_rupees() / prem if prem > 0 else 0.0
        return sum(leg.rupees() for leg in self.legs)

    def entry_premium_rs(self) -> float:
        """Combined entry premium in rupees (entry price x entry quantity, both legs)."""
        return sum((leg.entry_price or 0.0) * leg.qty for leg in self.legs)

    def total_rupees(self) -> float:
        """This run's P&L in rupees: earlier cycles (re-entry) + current legs."""
        return self.booked_rs + self.mtm_rupees()

    def mtm_rupees(self) -> float:
        return sum(leg.rupees() for leg in self.legs)

    def check_exits(self) -> tuple[str, list[Leg]] | None:
        """Return (reason, legs_to_close) or None. Pure decision logic — easy to test."""
        c = self.cfg
        open_legs = [leg for leg in self.legs if leg.is_open]
        if not open_legs:
            return None
        now = self.now()
        if (now.hour, now.minute) >= parse_hhmm(c.EXIT_TIME):
            return "TIME_EXIT", open_legs
        stale = [leg for leg in open_legs if self.mono() - leg.ltp_time > c.STALE_PRICE_EXIT_SECS]
        if stale:
            return "PRICE_FEED_LOST", open_legs
        if c.MAX_LOSS_PER_DAY_RS is not None and self.start_day_pnl + self.total_rupees() <= -c.MAX_LOSS_PER_DAY_RS:
            return "MAX_LOSS_PER_DAY", open_legs
        for leg in open_legs:
            if leg.sl_price is not None and leg.ltp is not None:
                hit = leg.ltp >= leg.sl_price if leg.side == "SELL" else leg.ltp <= leg.sl_price
                if hit:
                    return f"LEG_SL_{leg.name}", (open_legs if c.LEG_SL_ACTION == "exit_all" else [leg])
        m = self.mtm()
        if c.COMBINED_SL is not None and m <= -c.COMBINED_SL:
            return "COMBINED_SL", open_legs
        if c.COMBINED_TARGET is not None and m >= c.COMBINED_TARGET:
            return "TARGET", open_legs
        if c.MAX_PROFIT_PER_DAY_RS is not None and self.start_day_pnl + self.total_rupees() >= c.MAX_PROFIT_PER_DAY_RS:
            return "MAX_PROFIT_PER_DAY", open_legs
        if c.TRAIL_START is not None or c.LOCK_TRIGGER is not None:
            self.peak = m if self.peak is None else max(self.peak, m)
        if c.LOCK_TRIGGER is not None and c.LOCK_MIN is not None:
            if self.peak >= c.LOCK_TRIGGER and m <= c.LOCK_MIN:
                return "PROFIT_LOCK", open_legs
        if c.TRAIL_START is not None and c.TRAIL_GAP is not None:
            if self.peak >= c.TRAIL_START and m <= self.peak - c.TRAIL_GAP:
                return "TRAIL_SL", open_legs
        return None

    def monitor(self) -> None:
        log.info("Monitoring… (Ctrl+C squares off everything)")
        last_print = 0.0
        while any(leg.is_open for leg in self.legs):
            if self.ticker is not None and not self.ws_connected():
                self.ensure_ticker([])
            for leg in self.legs:
                if leg.is_open:
                    self.refresh_price(leg)
            decision = self.check_exits()
            if decision:
                reason, legs = decision
                self.square_off(reason, legs)
                if not any(leg.is_open for leg in self.legs):
                    self.last_reason = reason
                if reason.startswith("LEG_SL") and self.cfg.MOVE_SL_TO_COST:
                    for other in self.legs:
                        if other.is_open:
                            other.sl_price = other.entry_price
                            log.info("SL for %s moved to cost %.2f", other.tsym, other.entry_price)
                if not self.squareoff_ok:
                    return
                continue
            if self.mono() - last_print >= 10:
                last_print = self.mono()
                prices = " | ".join(f"{l.name} {l.ltp:.2f}" for l in self.legs if l.is_open and l.ltp is not None)
                log.info("MTM %.2f %s | %s", self.mtm(), self.cfg.MTM_UNIT, prices)
            self.sleep(self.cfg.POLL_SECONDS)

    # ── entry window, entry filter, re-entry ──────────────────────────────
    def cyc(self) -> str:
        return f"R{self.cycle}" if self.cycle else ""

    def entry_closed(self) -> bool:
        """True once no new entry is allowed (LAST_ENTRY_TIME, MCX last entry, or EXIT_TIME)."""
        n = self.now()
        hm = (n.hour, n.minute)
        if hm >= parse_hhmm(self.cfg.EXIT_TIME):
            return True
        if self.cfg.LAST_ENTRY_TIME and hm > parse_hhmm(self.cfg.LAST_ENTRY_TIME):
            return True
        last = self.session_caps().get("last_entry")
        return bool(last and hm >= parse_hhmm(last))

    def wait_entry_filter(self) -> bool:
        """Pick the legs; if a premium filter is set, wait inside the entry window until it passes.
        Returns False (nothing traded) when the window closes first."""
        c = self.cfg
        while True:
            if self.entry_closed():
                self.no_entry = True
                self.exit_reason = self.exit_reason or "NO_ENTRY_WINDOW_CLOSED"
                log.warning("Entry window closed — no %sentry", "re-" if self.cycle else "")
                return False
            self.resolve_legs()
            if c.ENTRY_MIN_PREMIUM is None and c.ENTRY_MAX_PREMIUM is None:
                return True
            self.ensure_ticker([(leg.exch, leg.token) for leg in self.legs])
            pxs = [self.refresh_price(leg) for leg in self.legs]
            if all(pxs):
                comb = sum(pxs)
                lo_ok = c.ENTRY_MIN_PREMIUM is None or comb >= c.ENTRY_MIN_PREMIUM
                hi_ok = c.ENTRY_MAX_PREMIUM is None or comb <= c.ENTRY_MAX_PREMIUM
                log.info("Entry filter: combined premium %.2f (min %s, max %s) -> %s", comb,
                         c.ENTRY_MIN_PREMIUM, c.ENTRY_MAX_PREMIUM, "OK" if lo_ok and hi_ok else "wait")
                if lo_ok and hi_ok:
                    return True
            self.sleep(max(1.0, float(c.ENTRY_RECHECK_SECS)))

    def want_reentry(self) -> bool:
        c = self.cfg
        sl_exit = self.last_reason == "COMBINED_SL" or self.last_reason.startswith("LEG_SL")
        if not (c.REENTRY_ON_SL and sl_exit and self.cycle < int(c.MAX_REENTRIES)):
            return False
        if c.MAX_LOSS_PER_DAY_RS is not None and self.start_day_pnl + self.total_rupees() <= -c.MAX_LOSS_PER_DAY_RS:
            log.warning("No re-entry: daily max loss reached")
            return False
        if self.entry_closed():
            log.info("No re-entry: entry window closed")
            return False
        return True

    def next_cycle(self) -> None:
        c = self.cfg
        self.booked_rs += self.mtm_rupees()
        self.history.extend(self.legs)
        self.legs = []
        self.peak = None
        self.cycle += 1
        log.warning("RE-ENTRY %d/%d after %s — waiting %.1f min cooldown", self.cycle, c.MAX_REENTRIES,
                    self.last_reason, c.REENTRY_COOLDOWN_MINS)
        self.last_reason = ""
        self.exit_reason = ""          # summary shows the reason that ended the last cycle
        end = self.mono() + float(c.REENTRY_COOLDOWN_MINS) * 60
        while self.mono() < end and not self.entry_closed():
            self.sleep(min(30.0, max(0.5, end - self.mono())))

    # ── 8. square-off ─────────────────────────────────────────────────────
    def square_off(self, reason: str, legs: list[Leg] | None = None) -> None:
        targets = [leg for leg in (legs or self.legs) if leg.is_open]
        if not targets:
            return
        self.exit_reason = self.exit_reason or reason
        log.warning("EXIT (%s): closing %s", reason, ", ".join(l.tsym for l in targets))
        for leg in targets:
            if not self.close_leg(leg, reason):
                self.squareoff_ok = False
                log.critical("MANUAL ACTION NEEDED: %s %d still open — square it off in the trading app now",
                             leg.tsym, leg.filled_qty)

    def close_leg(self, leg: Leg, reason: str) -> bool:
        txn = "BUY" if leg.side == "SELL" else "SELL"
        retries = max(1, int(self.cfg.EXIT_RETRIES))
        for attempt in range(retries):
            last = attempt == retries - 1
            try:
                self.refresh_price(leg)
                market = last and self.cfg.MARKET_FALLBACK_ON_EXIT
                tag = f"SS{self.run_id}{self.cyc()}{leg.name}X{attempt}"
                oid, px = self.send_order(leg, txn, leg.filled_qty, tag, market=market, attempt=attempt)
                status, filled, avg = self.wait_fill(leg, oid, leg.filled_qty, self.cfg.EXIT_FILL_TIMEOUT_SECS, px)
                if status not in ("COMPLETE", "REJECTED", "CANCELED", "CANCELLED") and filled < leg.filled_qty:
                    self.cancel(oid)
                if filled > 0:
                    exit_px = avg or leg.ltp or px
                    leg.realised += leg.sign * (exit_px - (leg.entry_price or exit_px)) * filled
                    leg.filled_qty -= filled
                    leg.exit_price = exit_px
                if leg.filled_qty <= 0:
                    leg.filled_qty = 0
                    leg.exit_reason = reason
                    log.info("EXIT %s %s @ %.2f (%s) | leg P&L %.2f", txn, leg.tsym, leg.exit_price or 0, reason, leg.realised)
                    return True
                log.warning("square-off %s not complete (status %s), retry %d/%d", leg.tsym, status, attempt + 1, retries)
            except Exception as exc:
                log.error("square-off %s error (%s), retry %d/%d", leg.tsym, type(exc).__name__, attempt + 1, retries)
            self.sleep(1.0)
        return False

    # ── 9. summary ────────────────────────────────────────────────────────
    def summary(self) -> None:
        if not self.legs and not self.history:
            return
        log.info("-------- Summary (%s) --------", "DRY RUN" if self.cfg.DRY_RUN else self.cfg.ENV)
        for l in self.history + self.legs:
            log.info("%s %s %s entry %s exit %s open %d P&L %.2f %s", l.name, l.side, l.tsym,
                     f"{l.entry_price:.2f}" if l.entry_price else "-", f"{l.exit_price:.2f}" if l.exit_price else "-",
                     l.filled_qty, l.rupees(), l.exit_reason)
        log.info("Total P&L (rupees): %.2f | exit reason: %s | re-entries: %d", self.total_rupees(),
                 self.exit_reason or "-", self.cycle)


# ═══════════════════════════════════════════════════════════════════════════
#  Login and command line
# ═══════════════════════════════════════════════════════════════════════════


def login(cfg: Config):
    """Reuse today's saved session if still valid, else browser login (UPPERCASE ID + password + TOTP)."""
    import os
    from infinn import Infinn, InfinnError

    api = Infinn(env=cfg.ENV, timeout=cfg.HTTP_TIMEOUT_SECS)
    log.info("Environment: %s", api.label)
    if os.path.exists(cfg.SESSION_FILE):
        try:
            api.load_session(cfg.SESSION_FILE)
            api.user_details()
            log.info("Reused saved session from %s", cfg.SESSION_FILE)
            return api
        except InfinnError as exc:
            log.info("Saved session not usable (%s) — logging in again", type(exc).__name__)
    print("\nOpen this link, log in (User ID in CAPITALS + password + TOTP):\n  " + api.login_url())
    redirect = input("\nPaste the FULL address-bar URL after login (it contains code=): ").strip()
    api.generate_session(redirect)
    api.save_session(cfg.SESSION_FILE)
    log.info("Login OK; session saved to %s (valid for today only)", cfg.SESSION_FILE)
    return api


def parse_args(argv: list[str] | None, cfg: Config) -> Config:
    p = argparse.ArgumentParser(description="INFINN Straddle / Strangle example (Sandbox first).")
    p.add_argument("--underlying", choices=list(UNDERLYINGS))
    p.add_argument("--mode", choices=["straddle", "strangle"])
    p.add_argument("--side", choices=["SELL", "BUY"])
    p.add_argument("--otm", type=float, help="strangle distance from ATM in points")
    p.add_argument("--lots", type=int)
    p.add_argument("--expiry", help="auto or e.g. 25-NOV-2026")
    p.add_argument("--entry", help="HH:MM IST or now")
    p.add_argument("--exit", dest="exit_time", help="HH:MM IST hard exit")
    p.add_argument("--env", choices=["sandbox", "uat", "live"])
    p.add_argument("--place-orders", action="store_true", help="turn DRY_RUN off (send real orders to the chosen env)")
    p.add_argument("--confirm-live", action="store_true", help="required together with --env live")
    p.add_argument("--session-file")
    p.add_argument("--no-websocket", action="store_true")
    a = p.parse_args(argv)
    for attr, key in (("underlying", "UNDERLYING"), ("mode", "MODE"), ("side", "SIDE"), ("otm", "STRANGLE_OTM_POINTS"),
                      ("lots", "LOTS"), ("expiry", "EXPIRY"), ("entry", "ENTRY_TIME"), ("exit_time", "EXIT_TIME"),
                      ("env", "ENV"), ("session_file", "SESSION_FILE")):
        v = getattr(a, attr)
        if v is not None:
            setattr(cfg, key, v)
    if a.place_orders:
        cfg.DRY_RUN = False
    if a.confirm_live:
        cfg.CONFIRM_LIVE = True
    if a.no_websocket:
        cfg.USE_WEBSOCKET = False
    return cfg


DISCLAIMER = (
    "This is sample code for learning only. It is not advice, and it is not a recommendation to trade.\n"
    "This code can have bugs. Read the code and check it yourself. Test it first on Sandbox (UAT / Test — NOT live).\n"
    "You are fully responsible for any live trade and for any loss. Markets are risky. You can lose money.\n"
    "INFINN (HKKR Finserv Pvt Ltd) is not responsible for losses from using this code.\n"
    "Questions: support@infinn.in\n"
)

def print_disclaimer() -> None:
    """Print the disclaimer once to the console when the program starts."""
    print("=" * 72)
    print(DISCLAIMER, end="" if DISCLAIMER.endswith("\n") else "\n")
    print("=" * 72)


def setup_logging(path: str) -> None:
    class ISTFormatter(logging.Formatter):
        def formatTime(self, record, datefmt=None):
            return datetime.fromtimestamp(record.created, IST).strftime("%Y-%m-%d %H:%M:%S IST")

    fmt = ISTFormatter("%(asctime)s %(levelname)-7s %(message)s")
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    for h in (logging.StreamHandler(sys.stdout), logging.FileHandler(path, encoding="utf-8")):
        h.setFormatter(fmt)
        root.addHandler(h)
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("websocket").setLevel(logging.WARNING)


def main(argv: list[str] | None = None) -> int:
    cfg = parse_args(argv, Config(**BUILDER_SETTINGS))
    setup_logging(cfg.LOG_FILE)
    print_disclaimer()
    live = cfg.ENV.lower() in ("live", "prod", "production")
    if live:
        if not cfg.CONFIRM_LIVE:
            log.error("ENV=live needs --confirm-live. Stopping.")
            return EXIT_CONFIG
        if not cfg.DRY_RUN:
            typed = input("LIVE orders with REAL money. Type  I UNDERSTAND  to continue: ").strip()
            if typed != "I UNDERSTAND":
                log.error("Live confirmation not given. Stopping.")
                return EXIT_CONFIG
    if not cfg.DRY_RUN:
        log.warning("DRY_RUN is OFF — orders WILL be sent to %s", "LIVE" if live else "Sandbox (UAT / Test — NOT live)")
    try:
        api = login(cfg)
    except Exception as exc:
        log.error("Login failed: %s", exc)
        return EXIT_LOGIN
    return StraddleStrangle(api, cfg).run()


if __name__ == "__main__":
    sys.exit(main())
