"""Provider-independent NSE derivative contracts and paper-trade validation.""" from datetime import date, datetime, timedelta, timezone from decimal import Decimal, InvalidOperation import csv import io import json import math import os import re import sqlite3 import threading import time from typing import Protocol import requests IST = timezone(timedelta(hours=5, minutes=30)) PUBLIC_REFERENCE_URL = "https://images.dhan.co/api-data/api-scrip-master-detailed.csv" _PUBLIC_REFERENCE_KEY = "fo_public_reference_v1" _REFERENCE_TTL = 86400 _REFERENCE_MAX_AGE = 2 * _REFERENCE_TTL _LAST_QUOTE_MAX_AGE = 5 * 86400 _FAILED_SNAPSHOT_RETRY_SECS = 5 _LAST_QUOTE_FIELDS = ("contract_id", "price", "source", "upstream", "quote_time", "observed_at", "as_of", "timestamp_basis", "underlying_price", "provider_iv", "volume", "open_interest", "context_quantity_basis") def fetch_contract_snapshot(contract): from fo_quotes import fetch_contract_snapshot as fetch return fetch(contract) def number(value, name, *, allow_zero=False): try: result = Decimal(str(value)) except (InvalidOperation, ValueError, TypeError): raise ValueError(f"{name} must be a finite number") from None if not result.is_finite() or result < 0 or result > Decimal("1e12") or (result == 0 and not allow_zero): raise ValueError(f"{name} must be {'non-negative' if allow_zero else 'positive'}") return result def integer(value, name): if isinstance(value, bool) or not re.fullmatch(r"[1-9][0-9]{0,6}", str(value)): raise ValueError(f"{name} must be a positive integer") return int(value) def validate_contract(raw, instrument_type, *, today=None): if not isinstance(raw, dict): raise ValueError("contract details are required") kind = str(instrument_type).upper() if kind not in {"OPTION", "FUTURE"}: raise ValueError("instrument_type must be OPTION or FUTURE") underlying = str(raw.get("underlying", "")).upper().removesuffix(".NS").strip() if not re.fullmatch(r"[A-Z0-9&_.-]{1,40}", underlying): raise ValueError("A valid underlying symbol is required") underlying_type = str(raw.get("underlying_type", "")).upper() if raw.get("exchange", "NSE") != "NSE" or underlying_type not in {"STOCK", "INDEX"}: raise ValueError("Only NSE stock/index contracts are supported") try: expiry = date.fromisoformat(str(raw.get("expiry", ""))) except ValueError: raise ValueError("expiry must be a valid YYYY-MM-DD date") from None if expiry < (today or datetime.now(IST).date()): raise ValueError("Expired contracts cannot be opened") if today is None: now = datetime.now(IST) if expiry == now.date() and (now.hour, now.minute) >= (15, 30): raise ValueError("Expired contracts cannot be opened") lot_size = integer(raw.get("lot_size"), "lot_size") tick_size = number(raw.get("tick_size"), "tick_size") option_type, strike = None, None if kind == "OPTION": option_type = str(raw.get("option_type", "")).upper() if option_type not in {"CE", "PE"}: raise ValueError("option_type must be CE or PE") strike = number(raw.get("strike"), "strike") identity = ":".join(["NSE", kind, underlying_type, underlying, expiry.isoformat(), format(strike.normalize(), "f") if strike is not None else "", option_type or ""]) return {"contract_id": identity, "exchange": "NSE", "instrument_type": kind, "underlying": underlying, "underlying_type": underlying_type, "expiry": expiry.isoformat(), "strike": float(strike) if strike is not None else None, "option_type": option_type, "lot_size": lot_size, "tick_size": float(tick_size)} def contract_for_trade(trade): raw = trade.get("contract_data") or "{}" return json.loads(raw) if isinstance(raw, str) else raw def is_derivative(trade): return trade.get("instrument_type", "EQUITY") in {"OPTION", "FUTURE"} def contract_label(contract): label = f"{contract['underlying']} {contract['expiry']}" return label + (f" {contract['strike']:g} {contract['option_type']}" if contract["option_type"] else " FUT") def forecast_windows(contract, *, now=None): from market_calendar import is_trading_day, next_trading_day current = (now or datetime.now(IST)).astimezone(IST) expiry = datetime.fromisoformat(contract["expiry"] + "T15:30:00+05:30") today_end = current.replace(hour=15, minute=0, second=0, microsecond=0) next_session = next_trading_day(current.date() + timedelta(days=1)) next_end = datetime.combine(next_session, datetime.min.time(), IST).replace(hour=15, minute=30) windows = {} for timeframe, end_at in (("INTRADAY", today_end), ("1D", next_end)): if current >= expiry: status = "expired" elif end_at > expiry: status = "after_expiry" elif timeframe == "INTRADAY" and (not is_trading_day(current.date()) or current >= end_at): status = "session_closed" else: status = "not_trained" windows[timeframe] = {"end_at": end_at.isoformat(), "eligible": status == "not_trained", "status": status} return windows def search_terms(query): def expiry_term(match): day, month, year = match.groups() for pattern in ("%d %b %Y", "%d %B %Y"): try: expiry = datetime.strptime(f"{day} {month} {year or '2000'}", pattern) return expiry.strftime("%Y-%m-%d" if year else "-%m-%d") except ValueError: continue return match.group() query = re.sub(r"\b(\d{1,2})(?:ST|ND|RD|TH)?\s+([A-Z]{3,9})(?:\s+(\d{4})\b(?!\s+(?:CE|PE|CALLS?|PUTS?)\b))?", expiry_term, query.upper()) aliases = {"FUT": "FUTURE", "FUTURES": "FUTURE", "OPTIONS": "OPTION", "CALL": "CE", "CALLS": "CE", "PUT": "PE", "PUTS": "PE"} return [aliases.get(term, term) for term in query.split()] def contract_matches(contract, terms): for term in terms: if re.fullmatch(r"\d+(?:\.\d+)?", term): if contract["strike"] is None or Decimal(term) != Decimal(str(contract["strike"])): return False elif re.fullmatch(r"(?:\d{4})?-\d{2}-\d{2}", term): if not contract["expiry"].endswith(term): return False elif term in {"CE", "PE"}: if contract["option_type"] != term: return False elif term in {"OPTION", "FUTURE"}: if contract["instrument_type"] != term: return False elif term not in contract["underlying"] and term != contract["contract_id"]: return False return True def matching_contracts(contracts, terms): symbols = {contract["underlying"] for contract in contracts} exact_symbol = next((term for term in terms if term in symbols), None) matches = [contract for contract in contracts if (not exact_symbol or contract["underlying"] == exact_symbol) and contract_matches(contract, terms)] return sorted(matches, key=lambda contract: (contract["expiry"], contract["underlying"], contract["strike"] or 0, contract["option_type"] or "")) def validate_price(trade, value): contract = contract_for_trade(trade) price = number(value, "contract price", allow_zero=trade["instrument_type"] == "OPTION") if price % Decimal(str(contract["tick_size"])): raise ValueError("Contract price must be a multiple of tick_size") return float(price) def validate_trade(data): contract = validate_contract(data.get("contract"), data.get("instrument_type")) direction = str(data.get("direction", "")).upper() if direction not in {"LONG", "SHORT"}: raise ValueError("direction must be LONG or SHORT") source = data.get("price_source", "manual") if source not in {"manual", "market"}: raise ValueError("price_source must be manual or market") lots = integer(data.get("lots"), "lots") entry = number(data.get("entry_price"), "entry_price") tick = Decimal(str(contract["tick_size"])) levels = {"entry_price": entry} for field in ("stop_loss", "target"): if data.get(field) not in (None, ""): levels[field] = number(data[field], field) for field, value in levels.items(): if value % tick: raise ValueError(f"{field} must be a multiple of tick_size") stop, target = levels.get("stop_loss"), levels.get("target") if stop is not None and ((direction == "LONG" and stop >= entry) or (direction == "SHORT" and stop <= entry)): raise ValueError("Stop loss is on the wrong side of the contract entry price") if target is not None and ((direction == "LONG" and target <= entry) or (direction == "SHORT" and target >= entry)): raise ValueError("Target is on the wrong side of the contract entry price") margin = None if data.get("margin_estimate") not in (None, ""): margin = float(number(data["margin_estimate"], "margin_estimate")) if (contract["instrument_type"] == "FUTURE" or direction == "SHORT") and margin is None: raise ValueError("A manual margin estimate is required for futures and sold options") return {"ticker": contract["contract_id"], "name": contract_label(contract), "direction": direction, "entry_price": float(entry), "shares": lots * contract["lot_size"], "stop_loss": float(stop) if stop is not None else None, "target": float(target) if target is not None else None, "instrument_type": contract["instrument_type"], "contract_data": json.dumps(contract), "price_source": source, "margin_estimate": margin, "strategy": "F&O"} class FoUnavailable(ValueError): pass class FoProvider(Protocol): def capabilities(self) -> dict: ... def quote(self, contract: dict) -> dict: ... def chain(self, contracts: list[dict]) -> dict: ... def margin(self, contract: dict, direction: str, quantity: int, price: float) -> float: ... def parse_reference_csv(text): rows = ({(key or "").strip(): (value or "").strip() for key, value in raw.items()} for raw in csv.DictReader(io.StringIO(text))) return _validated_references(rows) def _validated_references(rows): contracts, ambiguous = {}, set() for row in rows: try: contract = validate_contract(row, row.get("instrument_type")) mappings = row.get("provider_ids") or {} if isinstance(mappings, str): mappings = json.loads(mappings) if not isinstance(mappings, dict): continue allowed = {"security_id", "underlying_security_id", "underlying_segment", "symbol"} contract["provider_ids"] = {name: {key: str(value)[:80] for key, value in mapping.items() if key in allowed} for name, mapping in mappings.items() if re.fullmatch(r"[a-z0-9_]{1,20}", name) and isinstance(mapping, dict)} identity = contract["contract_id"] if identity in contracts and contract != contracts[identity]: ambiguous.add(identity) contracts[identity] = contract except (ValueError, TypeError): continue return [contract for identity, contract in contracts.items() if identity not in ambiguous] def parse_public_reference_csv(lines): def references(): kinds = {"OPTIDX": ("OPTION", "INDEX"), "OPTSTK": ("OPTION", "STOCK"), "FUTIDX": ("FUTURE", "INDEX"), "FUTSTK": ("FUTURE", "STOCK")} for row in csv.DictReader(lines): kind = kinds.get(row.get("INSTRUMENT")) security_id = row.get("SECURITY_ID", "") if row.get("EXCH_ID") != "NSE" or row.get("SEGMENT") != "D" or not kind or not security_id.isdigit(): continue try: lot = number(row.get("LOT_SIZE"), "lot_size") if lot != lot.to_integral_value(): continue expiry = datetime.fromisoformat(row.get("SM_EXPIRY_DATE", "")).date().isoformat() yield {"underlying": row.get("UNDERLYING_SYMBOL"), "underlying_type": kind[1], "instrument_type": kind[0], "expiry": expiry, "lot_size": int(lot), "tick_size": number(row.get("TICK_SIZE"), "tick_size") / 100, "strike": row.get("STRIKE_PRICE"), "option_type": row.get("OPTION_TYPE"), "provider_ids": {"dhan": {"security_id": security_id}}} except (ValueError, TypeError): continue return _validated_references(references()) def normalize_quote(raw, *, now=None): now = time.time() if now is None else now result = {"source": str(raw.get("source") or "unknown")[:40]} for field in ("price", "bid", "ask", "bid_quantity", "ask_quantity", "observed_at", "trade_time"): value = raw.get(field) try: parsed = float(value) result[field] = parsed if not isinstance(value, bool) and math.isfinite(parsed) and parsed >= 0 else None except (ValueError, TypeError, OverflowError): result[field] = None observed, traded = result["observed_at"], result["trade_time"] crossed = result["bid"] is not None and result["ask"] is not None and result["bid"] > result["ask"] result["stale"] = bool(raw.get("stale") or not result["price"] or observed is None or traded is None or not -5 <= now - observed <= 15 or not -5 <= now - traded <= 90 or crossed) result["is_live"] = not result["stale"] return result def execution_price(quote, direction, quantity): quote = normalize_quote(quote) side = "ask" if direction == "LONG" else "bid" if quote["stale"] or not quote[side] or (quote[side + "_quantity"] or 0) < quantity: raise FoUnavailable("Fresh contract bid/ask with sufficient displayed quantity is required") return quote[side] class FoService: def __init__(self, provider=None, name="manual"): self.provider, self.name = provider, name self._lock = threading.Lock() self._catalog = [] self._catalog_key = None self._reference_state = "not_configured" self._reference_source = "csv" self._reference_lock = threading.Lock() self._reference_loading = False self._reference_loaded = False self._reference_at = 0.0 self._reference_retry_at = 0.0 self._quotes = {} self._chains = {} self._snapshots = {} self._snapshot_lock = threading.Lock() self._last_quotes = None self._last_quote_lock = threading.Lock() def _refresh_public_reference(self): try: deadline = time.monotonic() + 60 with requests.get(PUBLIC_REFERENCE_URL, stream=True, timeout=(5, 10)) as response: response.raise_for_status() response.encoding = "utf-8-sig" if int(response.headers.get("Content-Length", "0")) > 64_000_000: raise ValueError("Reference response is too large") def bounded_lines(): size = 0 for line in response.iter_lines(decode_unicode=True): size += len(line.encode("utf-8")) + 1 if size > 64_000_000 or time.monotonic() > deadline: raise ValueError("Reference download exceeded its budget") yield line rows = parse_public_reference_csv(bounded_lines()) if not rows: raise ValueError("Public reference contains no valid NSE contracts") from database import save_app_result_cache saved_at = time.time() try: save_app_result_cache(_PUBLIC_REFERENCE_KEY, {"contracts": rows}, saved_at) except (sqlite3.Error, OSError): pass with self._reference_lock: self._catalog = rows self._reference_at = saved_at self._reference_state = "available" except (requests.RequestException, OSError, ValueError, TypeError): with self._reference_lock: self._reference_state = "unavailable" self._reference_retry_at = time.time() + 60 finally: with self._reference_lock: self._reference_loading = False def _public_contracts(self): self._reference_source = "dhan_public" now = time.time() start_refresh = False with self._reference_lock: if not self._reference_loaded: from database import get_app_result_cache try: cached = get_app_result_cache(_PUBLIC_REFERENCE_KEY) if cached and 0 <= now - cached["saved_at"] <= _REFERENCE_MAX_AGE: rows = cached["result"].get("contracts", []) if isinstance(rows, list) and all(isinstance(row, dict) and "expiry" in row for row in rows): self._catalog = _validated_references(rows) if self._catalog: self._reference_at = cached["saved_at"] except (sqlite3.Error, OSError, ValueError, TypeError, KeyError): pass self._reference_loaded = True age = now - self._reference_at if self._reference_at and 0 <= age < _REFERENCE_TTL: self._reference_state = "available" elif not self._reference_loading and now >= self._reference_retry_at: self._reference_loading = True self._reference_state = "loading" start_refresh = True if self._catalog and self._reference_at and 0 <= age <= _REFERENCE_MAX_AGE and age >= _REFERENCE_TTL: self._reference_state = "stale" rows = self._catalog if self._reference_at and 0 <= age <= _REFERENCE_MAX_AGE else [] if start_refresh: threading.Thread(target=self._refresh_public_reference, daemon=True, name="fo-reference-refresh").start() return rows def contracts(self, underlying="", instrument_type="", expiry=""): path = os.getenv("FO_REFERENCE_CSV", "") if not path and os.getenv("FO_AUTO_REFERENCE", "1") == "1": rows = self._public_contracts() return self._filter_contracts(rows, underlying, instrument_type, expiry) self._reference_source = "csv" try: info = os.stat(path) if path else None key = (path, info.st_mtime_ns, info.st_size) if info else None if info and (info.st_size > 25_000_000 or time.time() - info.st_mtime > 7 * 86400): raise ValueError("Reference file is too large or stale") with self._lock: if key != self._catalog_key: with open(path, encoding="utf-8-sig") as source: self._catalog = parse_reference_csv(source.read()) self._catalog_key = key self._reference_state = "available" if info else "not_configured" rows = self._catalog if info else [] except (OSError, ValueError): self._reference_state = "unavailable" rows = [] return self._filter_contracts(rows, underlying, instrument_type, expiry) def _filter_contracts(self, rows, underlying, instrument_type, expiry): symbol = underlying.upper().removesuffix(".NS").strip() now = datetime.now(IST) today = now.date().isoformat() return [dict(row) for row in rows if (row["expiry"] > today or (row["expiry"] == today and (now.hour, now.minute) < (15, 30))) and (not symbol or row["underlying"] == symbol) and (not instrument_type or row["instrument_type"] == instrument_type) and (not expiry or row["expiry"] == expiry)] def status(self): rows = self.contracts() caps = self.provider.capabilities() if self.provider else {} return {"provider": self.name, "manual_available": True, "reference_state": self._reference_state, "reference_count": len(rows), "reference_source": self._reference_source, "capabilities": {key: caps.get(key) is True for key in ("quotes", "option_chain", "margin")}} def resolve(self, contract_id): contract = next((row for row in self.contracts() if row["contract_id"] == contract_id), None) if contract is None: raise FoUnavailable("Contract reference is unavailable; use confirmed manual specifications") return contract def quote(self, contract): if not self.provider or not self.provider.capabilities().get("quotes"): raise FoUnavailable("Live derivative quotes are unavailable; manual recording is available") identity = contract.get("contract_id") if not identity: raise FoUnavailable("A reference contract is required for live quotes") if not self._lock.acquire(timeout=8): raise FoUnavailable("Derivative quotes are busy; retry shortly") try: cached = self._quotes.get(identity) if cached and time.time() - cached["observed_at"] < 5: return normalize_quote(cached) try: quote = normalize_quote(self.provider.quote(contract)) except (ValueError, OSError): if cached: return {**normalize_quote(cached), "stale": True, "is_live": False} raise FoUnavailable("Derivative quote provider is unavailable") from None if quote["observed_at"] is not None: self._quotes[identity] = quote return quote finally: self._lock.release() def _last_quotes_path(self): hf_data = "/data" base = hf_data if os.path.isdir(hf_data) and os.access(hf_data, os.W_OK) else os.path.dirname(os.path.abspath(__file__)) return os.environ.get("FO_LAST_QUOTES_PATH") or os.path.join(base, ".fo_last_quotes.json") def _remember_quote(self, identity, quote): if not identity or not isinstance(quote, dict) or quote.get("quote_time") is None: return with self._last_quote_lock: if self._last_quotes is None: self._last_quotes = self._read_last_quotes() previous = self._last_quotes.get(identity) if previous and previous.get("quote_time") == quote["quote_time"]: return self._last_quotes[identity] = {key: quote.get(key) for key in _LAST_QUOTE_FIELDS} while len(self._last_quotes) > 500: self._last_quotes.pop(next(iter(self._last_quotes))) path = self._last_quotes_path() try: with open(path + ".tmp", "w") as handle: json.dump(self._last_quotes, handle) handle.flush() os.fsync(handle.fileno()) os.replace(path + ".tmp", path) except OSError: pass def _read_last_quotes(self): try: with open(self._last_quotes_path()) as handle: data = json.load(handle) return data if isinstance(data, dict) else {} except (OSError, ValueError): return {} def _last_known_quote(self, identity): with self._last_quote_lock: if self._last_quotes is None: self._last_quotes = self._read_last_quotes() saved = self._last_quotes.get(identity) try: price = float(number(saved["price"], "last price")) quote_time = float(number(saved["quote_time"], "last quote time")) except (TypeError, KeyError, ValueError): return None if time.time() - quote_time > _LAST_QUOTE_MAX_AGE: return None return {**saved, "price": price, "quote_time": quote_time, "stale": True, "is_live": False, "executable": False, "last_known": True} def watchlist_quote(self, contract): identity = contract.get("contract_id") try: quote = self._watchlist_quote(contract) except FoUnavailable: fallback = self._last_known_quote(identity) if fallback is None: raise return fallback self._remember_quote(identity, quote) from fo_quotes import remember_contract_quote remember_contract_quote(contract, quote) return quote def _watchlist_quote(self, contract): try: return self.quote(contract) except FoUnavailable: pass identity = contract.get("contract_id") with self._snapshot_lock: cached = self._snapshots.get(identity) if cached and time.monotonic() - cached[0] < (_FAILED_SNAPSHOT_RETRY_SECS if isinstance(cached[1], str) else 30): if isinstance(cached[1], str): raise FoUnavailable(cached[1]) quote = dict(cached[1]) if quote.get("quote_time") is not None: quote["stale"] = time.time() - quote["quote_time"] > 120 return quote try: quote = fetch_contract_snapshot(contract) except FoUnavailable as exc: with self._snapshot_lock: if len(self._snapshots) >= 500: self._snapshots.clear() self._snapshots[identity] = (time.monotonic(), str(exc)) raise with self._snapshot_lock: if len(self._snapshots) >= 500: self._snapshots.clear() self._snapshots[identity] = (time.monotonic(), quote) return quote def chart(self, contract, *, interval="5m", refresh=False): from fo_quotes import fetch_contract_chart return fetch_contract_chart(contract, interval=interval, refresh=refresh) def chain(self, underlying, expiry): if not self.provider or not self.provider.capabilities().get("option_chain"): raise FoUnavailable("Live option chain is unavailable; manual contract selection is available") contracts = self.contracts(underlying, "OPTION", expiry) if not contracts: raise FoUnavailable("No reference option contracts for this underlying and expiry") key = (underlying, expiry) if not self._lock.acquire(timeout=8): raise FoUnavailable("Option chain is busy; retry shortly") try: cached = self._chains.get(key) if cached and time.time() - cached["observed_at"] < 4: return dict(cached) result = self.provider.chain(contracts) result["observed_at"] = time.time() result["stale"] = False self._chains[key] = result return result except (ValueError, OSError): if cached: return {**cached, "stale": True} raise FoUnavailable("Option chain provider is unavailable") from None finally: self._lock.release() def margin(self, contract, direction, lots, price): if not self.provider or not self.provider.capabilities().get("margin"): raise FoUnavailable("Provider margin is unavailable; enter a clearly labeled manual estimate") quantity = integer(lots, "lots") * contract["lot_size"] if direction not in {"LONG", "SHORT"}: raise ValueError("direction must be LONG or SHORT") return float(number(self.provider.margin(contract, direction, quantity, float(number(price, "price"))), "margin")) _service = None _service_name = None _service_lock = threading.Lock() _provider_factories = {} def register_provider(name, factory): _provider_factories[name] = factory def prepare_entry(data): data = dict(data) if data.get("contract_id"): contract = get_service().resolve(data["contract_id"]) data["contract"] = contract data["instrument_type"] = contract["instrument_type"] else: contract = validate_contract(data.get("contract"), data.get("instrument_type")) contract["provider_ids"] = {} order_type = str(data.get("order_type", "MARKET")).upper() if order_type not in {"MARKET", "LIMIT"}: raise ValueError("order_type must be MARKET or LIMIT") quote = None if data.get("price_source", "manual") == "market": if not data.get("contract_id"): raise FoUnavailable("Live entries require a reference contract") from market_calendar import market_status if market_status().get("status") != "OPEN": raise FoUnavailable("Live paper entries are available only during market hours") quantity = integer(data.get("lots"), "lots") * contract["lot_size"] quote = get_service().quote(contract) price = execution_price(quote, data.get("direction"), quantity) if order_type == "MARKET": data["entry_price"] = price if get_service().status()["capabilities"]["margin"] and ( contract["instrument_type"] == "FUTURE" or data.get("direction") == "SHORT"): data["margin_estimate"] = get_service().margin(contract, data["direction"], data["lots"], data["entry_price"]) contract["margin_source"] = "provider_estimate" fields = validate_trade(data) from costs import derivative_fee_schedule, derivative_leg_cost contract["fee_schedule"] = derivative_fee_schedule(contract["instrument_type"]) contract["reference_source"] = "reference_csv" if data.get("contract_id") else "manual_specifications" contract["margin_source"] = contract.get("margin_source", "manual_estimate") if quote: contract["entry_quote"] = quote fields["contract_data"] = json.dumps(contract) fields["order_type"] = order_type fields["status"] = "PENDING" if order_type == "LIMIT" else "OPEN" side = "BUY" if fields["direction"] == "LONG" else "SELL" fields["entry_cost"] = derivative_leg_cost(fields["entry_price"], fields["shares"], side, contract["fee_schedule"]) if fields["status"] == "OPEN" else 0 return fields def expiry_state(trade, now=None): now = now or datetime.now(IST) expiry = contract_for_trade(trade)["expiry"] day = now.date().isoformat() if day > expiry or (day == expiry and (now.hour, now.minute) >= (15, 30)): return "expired_unresolved" if trade.get("status") in {"OPEN", "PENDING"} else "closed" if day == expiry and (now.hour, now.minute) >= (15, 20): return "pre_expiry_exit_due" return "active" def position_quote(trade): quote = None state = expiry_state(trade) if state in {"active", "pre_expiry_exit_due"}: try: contract = contract_for_trade(trade) quote = get_service().watchlist_quote(contract) if quote.get("contract_id") not in {None, contract.get("contract_id")}: raise FoUnavailable("Quote does not match the position contract") price = float(number(quote.get("price"), "contract valuation")) except (FoUnavailable, ValueError, TypeError, AttributeError): quote = None if quote and trade.get("mark_price") is not None and trade.get("mark_observed_at") is not None: try: manual_time = float(number(trade["mark_observed_at"], "manual mark time")) quote_time = float(number(quote.get("quote_time") or quote.get("trade_time"), "quote time")) if manual_time >= quote_time: quote = None except (ValueError, TypeError): quote = None if quote: return {**quote, "current_price": price, "mark_source": quote.get("source", "market"), "valuation_only": True, "expiry_state": state} return {"current_price": trade.get("mark_price"), "mark_source": "manual" if trade.get("mark_price") is not None else None, "observed_at": trade.get("mark_observed_at"), "is_live": False, "stale": True, "valuation_only": True, "expiry_state": state} def automatic_price(trade, *, opening=False): if trade.get("price_source") == "manual" or expiry_state(trade) == "expired_unresolved": raise FoUnavailable("Manual or expired contracts require an explicit recorded fill/exit") from market_calendar import market_status if market_status().get("status") != "OPEN": raise FoUnavailable("Derivative market is closed") direction = trade["direction"] if not opening: direction = "SHORT" if direction == "LONG" else "LONG" return execution_price(get_service().quote(contract_for_trade(trade)), direction, trade["shares"]) SNAPSHOT_EXIT_MAX_AGE_SECS = 300 def snapshot_exit_price(trade): """NSE last-traded price used to trigger a stop/target on a manually recorded position. Delayed (about a minute) and without bid/ask, so it is only ever used for stop/target exits while the market is open and the snapshot is recent; never for fills or expiry settlement. """ if expiry_state(trade) not in {"active", "pre_expiry_exit_due"}: raise FoUnavailable("Expired contracts require an explicit recorded exit") from market_calendar import market_status if market_status().get("status") != "OPEN": raise FoUnavailable("Derivative market is closed") contract = contract_for_trade(trade) quote = get_service().watchlist_quote(contract) if quote.get("last_known") or quote.get("contract_id") not in {None, contract.get("contract_id")}: raise FoUnavailable("No current quote for this exact contract") stamp = float(number(quote.get("quote_time") or quote.get("trade_time"), "quote time")) if not -5 <= time.time() - stamp <= SNAPSHOT_EXIT_MAX_AGE_SECS: raise FoUnavailable("Contract snapshot is too old to trigger an exit") price = Decimal(str(number(quote.get("price"), "contract price"))) tick = Decimal(str(contract["tick_size"])) return float((price / tick).to_integral_value() * tick) def get_service(): global _service, _service_name name = os.getenv("FO_PROVIDER", "manual").lower() with _service_lock: if _service is None or name != _service_name: factory = _provider_factories.get(name) if name == "dhan" and factory is None: from fo_dhan import DhanFoProvider factory = DhanFoProvider _service = FoService(provider=factory() if factory else None, name=name) _service_name = name return _service