PaperTrade / tests /test_fo.py
Khanna, Videh Rakesh Rakesh
Claude Sonnet 5.5
F&O: AI-first card, NSE-based entry price and stop/target exits, resilient first load
4640591
Raw History Blame Contribute Delete
59.6 kB
import json import time from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timezone from threading import Event from unittest.mock import Mock, patch, mock_open import pytest import fo import fo_quotes @pytest.fixture(autouse=True) def isolate_snapshot_downloads(monkeypatch): import database histories = {} get_cached = database.get_app_result_cache save_cached = database.save_app_result_cache def get_history(key): return histories.get(key) if key.startswith("fo_chart:") else get_cached(key) def save_history(key, result, saved_at=None): if key.startswith("fo_chart:"): histories[key] = {"result": result, "saved_at": saved_at} else: save_cached(key, result, saved_at) monkeypatch.setattr(database, "get_app_result_cache", get_history) monkeypatch.setattr(database, "save_app_result_cache", save_history) fo_quotes._payloads.clear() yield fo_quotes._payloads.clear() def contract(**updates): return {"exchange": "NSE", "underlying": "NIFTY", "underlying_type": "INDEX", "expiry": "2099-10-29", "strike": 25000, "option_type": "PE", "lot_size": 25, "tick_size": 0.05, **updates} def payload(**updates): return {"instrument_type": "OPTION", "contract": contract(), "lots": 2, "direction": "LONG", "entry_price": 100, "price_source": "manual", **updates} def test_put_buy_is_long_premium_and_uses_lots_not_client_shares(): result = fo.validate_trade(payload(shares=9999)) assert result["direction"] == "LONG" assert result["shares"] == 50 assert json.loads(result["contract_data"])["option_type"] == "PE" @pytest.mark.parametrize("updates", [ {"lots": 0}, {"lots": 1.5}, {"lots": True}, {"entry_price": "nan"}, {"entry_price": "inf"}, {"entry_price": -1}, {"entry_price": 100.01}, {"direction": "BEARISH"}, {"stop_loss": 101}, {"target": 99}, {"margin_estimate": "nan"}, {"contract": None}, ]) def test_manual_trade_rejects_invalid_inputs(updates): with pytest.raises(ValueError): fo.validate_trade(payload(**updates)) @pytest.mark.parametrize("updates", [ {"underlying": "<script>"}, {"underlying_type": "OTHER"}, {"exchange": "BSE"}, {"expiry": "2020-01-01"}, {"expiry": "2099-02-30"}, {"lot_size": 0}, {"tick_size": 0}, {"option_type": "CALL"}, {"strike": 0}, ]) def test_contract_validation(updates): with pytest.raises(ValueError): fo.validate_contract(contract(**updates), "OPTION", today=date(2026, 10, 14)) def test_contract_identity_separates_strikes_expiries_and_instruments(): contracts = [contract(), contract(strike=25100), contract(expiry="2099-11-26")] identities = {fo.validate_contract(raw, "OPTION")["contract_id"] for raw in contracts} identities.add(fo.validate_contract(contract(), "FUTURE")["contract_id"]) assert len(identities) == 4 @pytest.mark.parametrize("now,expiry,today_status,one_day_status,target", [ ("2026-10-16T10:00:00+05:30", "2026-10-19", "not_trained", "not_trained", "2026-10-19"), ("2026-10-19T10:00:00+05:30", "2026-10-19", "not_trained", "after_expiry", "2026-10-20"), ("2026-10-16T15:00:00+05:30", "2026-10-19", "session_closed", "not_trained", "2026-10-19"), ("2026-10-17T10:00:00+05:30", "2026-10-19", "session_closed", "not_trained", "2026-10-19"), ("2026-10-19T15:30:00+05:30", "2026-10-19", "expired", "expired", "2026-10-20"), ("2026-10-01T10:00:00+05:30", "2026-10-05", "not_trained", "not_trained", "2026-10-05"), ]) def test_derivative_forecast_windows_stop_at_expiry(now, expiry, today_status, one_day_status, target): windows = fo.forecast_windows(contract(expiry=expiry), now=datetime.fromisoformat(now)) assert windows["INTRADAY"]["status"] == today_status assert windows["1D"]["status"] == one_day_status assert windows["1D"]["end_at"] == target + "T15:30:00+05:30" assert windows["INTRADAY"]["eligible"] == (today_status == "not_trained") assert windows["1D"]["eligible"] == (one_day_status == "not_trained") def test_margin_is_required_for_futures_and_sold_options(): for updates in ({"instrument_type": "FUTURE"}, {"direction": "SHORT"}): with pytest.raises(ValueError, match="margin estimate"): fo.validate_trade(payload(**updates)) assert fo.validate_trade(payload(**updates, margin_estimate=50000))["margin_estimate"] == 50000 @pytest.mark.parametrize("kind,side", [("OPTION", "LONG"), ("OPTION", "SHORT"), ("FUTURE", "LONG"), ("FUTURE", "SHORT")]) def test_manual_entry_valuation_uses_exact_contract_snapshot_not_old_manual_mark(kind, side): reference = fo.validate_contract(contract(), kind) trade = {"contract_data": json.dumps(reference), "instrument_type": kind, "direction": side, "status": "OPEN", "price_source": "manual", "entry_price": 100, "shares": 50, "mark_price": 110, "mark_observed_at": 1000} snapshot = {"price": 90, "source": "nse_snapshot", "quote_time": 2000, "observed_at": 2000, "stale": False, "is_live": False, "executable": False} with patch("fo.get_service") as service: service.return_value.watchlist_quote.return_value = snapshot result = fo.position_quote(trade) assert result["current_price"] == 90 assert result["mark_source"] == "nse_snapshot" assert result["valuation_only"] is True service.return_value.watchlist_quote.assert_called_once_with(reference) with pytest.raises(fo.FoUnavailable, match="Manual"): fo.automatic_price(trade) @pytest.mark.parametrize("quote_time", [1000, None]) def test_newer_manual_mark_is_not_overwritten_by_an_older_snapshot(quote_time): reference = fo.validate_contract(contract(), "OPTION") trade = {"contract_data": json.dumps(reference), "instrument_type": "OPTION", "direction": "LONG", "status": "OPEN", "price_source": "manual", "entry_price": 100, "shares": 50, "mark_price": 90, "mark_observed_at": 2000} with patch("fo.get_service") as service: service.return_value.watchlist_quote.return_value = {"price": 110, "source": "nse_snapshot", "quote_time": quote_time, "observed_at": 3000, "is_live": False} result = fo.position_quote(trade) assert result["current_price"] == 90 assert result["mark_source"] == "manual" assert result["observed_at"] == 2000 def test_position_valuation_rejects_another_contract_quote(): reference = fo.validate_contract(contract(), "OPTION") other = fo.validate_contract(contract(strike=25100), "OPTION") trade = {"contract_data": json.dumps(reference), "instrument_type": "OPTION", "direction": "LONG", "status": "OPEN", "price_source": "manual", "mark_price": 90, "mark_observed_at": 1000} with patch("fo.get_service") as service: service.return_value.watchlist_quote.return_value = {"contract_id": other["contract_id"], "price": 150, "source": "nse_snapshot", "quote_time": 2000} result = fo.position_quote(trade) assert result["current_price"] == 90 assert result["mark_source"] == "manual" @pytest.mark.parametrize("updates", [{"current_price": None}, {"current_price": float("nan")}, {"current_price": -1}, {"entry_price": 0}, {"shares": "bad"}, {"direction": "BEARISH"}]) def test_unusable_valuation_never_retains_an_old_profit(updates): from database import position_pnl trade = {"entry_price": 100, "current_price": 90, "shares": 50, "direction": "LONG", "unrealised_pnl": 500, "unrealised_pnl_pct": 10, **updates} result = position_pnl(trade) assert result["unrealised_pnl"] is None assert result["unrealised_pnl_pct"] is None assert trade["unrealised_pnl"] == 500 @pytest.mark.parametrize("side,expected", [("LONG", -5000), ("SHORT", 5000)]) def test_zero_option_mark_is_a_real_total_loss_or_gain(side, expected): from database import position_pnl result = position_pnl({"entry_price": 100, "current_price": 0, "shares": 50, "direction": side}) assert result["unrealised_pnl"] == expected def test_manual_service_remains_available_without_any_provider(): service = fo.FoService() with patch.dict("os.environ", {"FO_REFERENCE_CSV": ""}): status = service.status() assert status["manual_available"] assert not status["capabilities"]["quotes"] assert service.contracts() == [] with pytest.raises(fo.FoUnavailable): service.quote(contract()) def test_watchlist_quote_uses_contract_snapshot_without_enabling_execution(): service = fo.FoService() reference = fo.validate_contract(contract(strike=22900, expiry="2099-10-19"), "OPTION") snapshot = {"price": 123.5, "source": "nse_snapshot", "is_live": False} with patch("fo.fetch_contract_snapshot", return_value=snapshot, create=True) as fetch: assert service.watchlist_quote(reference) == snapshot fetch.assert_called_once_with(reference) with pytest.raises(fo.FoUnavailable): service.quote(reference) def test_watchlist_quote_prefers_configured_live_provider(): service = fo.FoService() quote = {"price": 123.5, "source": "dhan", "is_live": True} with patch.object(service, "quote", return_value=quote), patch("fo.fetch_contract_snapshot", create=True) as fetch: assert service.watchlist_quote(contract()) == quote fetch.assert_not_called() def test_watchlist_snapshots_do_not_block_other_contracts(): service = fo.FoService() first = fo.validate_contract(contract(strike=22800), "OPTION") second = fo.validate_contract(contract(strike=22850), "OPTION") started, release = Event(), Event() def fetch(reference): if reference["contract_id"] == first["contract_id"]: started.set() assert release.wait(2) return {"contract_id": reference["contract_id"], "price": reference["strike"] / 100} with patch("fo.fetch_contract_snapshot", side_effect=fetch), ThreadPoolExecutor(max_workers=2) as workers: pending = workers.submit(service.watchlist_quote, first) try: assert started.wait(2) assert service.watchlist_quote(second)["contract_id"] == second["contract_id"] finally: release.set() assert pending.result(timeout=2)["contract_id"] == first["contract_id"] @pytest.fixture def option_snapshot(): return {"records": {"timestamp": "16-Oct-2026 09:30:00", "data": [{"PE": { "underlying": "NIFTY", "expiryDate": "29-10-2099", "strikePrice": 25000, "identifier": "OPTIDXNIFTY29-10-2099PE25000.00", "lastPrice": 108.2, }}]}} def test_contract_snapshot_is_timestamped_display_only(option_snapshot): reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp() with patch("fo_quotes.time.time", return_value=now): result = fo_quotes._parse_snapshot(option_snapshot, reference, "nse_snapshot") assert result["price"] == 108.2 assert result["contract_id"] == reference["contract_id"] assert result["source"] == "nse_snapshot" assert result["quote_time"] == now - 60 assert result["as_of"] == "2026-10-16T09:30:00+05:30" assert not result["is_live"] and not result["executable"] and not result["stale"] assert result["trade_time"] is None def test_snapshot_retains_timestamped_derivative_model_context(option_snapshot): option_snapshot["records"]["data"][0]["PE"].update({"underlyingValue": 22950, "impliedVolatility": 20, "totalTradedVolume": 17, "openInterest": 30}) now = datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp() with patch("fo_quotes.time.time", return_value=now): quote = fo_quotes._parse_snapshot(option_snapshot, fo.validate_contract(contract(), "OPTION"), "nse_snapshot") assert quote["underlying_price"] == 22950 assert quote["provider_iv"] == 20 assert quote["volume"] == 17 * 25 assert quote["open_interest"] == 30 * 25 assert quote["context_quantity_basis"] == "units" @pytest.mark.parametrize("underlying,underlying_type", [ ("NIFTY", "INDEX"), ("BANKNIFTY", "INDEX"), ("FINNIFTY", "INDEX"), ("MIDCPNIFTY", "INDEX"), ("NIFTYNXT50", "INDEX"), ("RELIANCE", "STOCK"), ("SBIN", "STOCK"), ]) @pytest.mark.parametrize("kind,side", [("OPTION", "CE"), ("OPTION", "PE"), ("FUTURE", "")]) @pytest.mark.parametrize("strike", [22800, 22850, 22900]) def test_snapshots_match_each_index_stock_strike_and_instrument(underlying, underlying_type, kind, side, strike): reference = fo.validate_contract(contract(underlying=underlying, underlying_type=underlying_type, strike=strike, option_type=side), kind) instrument = ("OPT" if kind == "OPTION" else "FUT") + ("IDX" if underlying_type == "INDEX" else "STK") suffix = f"{side}{strike}.00" if kind == "OPTION" else "XX0.00" row = {"underlying": underlying, "expiryDate": "29-Oct-2099", "strikePrice": strike, "optionType": side, "instrumentType": instrument, "identifier": f"{instrument}{underlying}29-10-2099{suffix}", "lastPrice": 108.2} data = {"timestamp": "16-Oct-2026 09:30:00", "data": [row]} with patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp()): quote = fo_quotes._parse_snapshot(data, reference, "nse_snapshot") assert quote["contract_id"] == reference["contract_id"] assert quote["price"] == 108.2 assert not quote["is_live"] and not quote["executable"] def test_snapshot_download_is_shared_across_strikes_and_option_sides(option_snapshot, monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") rows = option_snapshot["records"]["data"] rows.clear() for strike, side, price in [(22800, "PE", 80), (22850, "PE", 90), (22900, "CE", 120)]: rows.append({side: {"underlying": "NIFTY", "expiryDate": "29-10-2099", "strikePrice": strike, "identifier": f"OPTIDXNIFTY29-10-2099{side}{strike}.00", "lastPrice": price}}) with patch("fo_quotes._SnapshotSession"), patch("jugaad_data.nse.NSELive.index_option_chain", return_value=option_snapshot) as fetch: with patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp()): for strike, side, price in [(22800, "PE", 80), (22850, "PE", 90), (22900, "CE", 120)]: reference = fo.validate_contract(contract(strike=strike, option_type=side), "OPTION") assert fo_quotes.fetch_contract_snapshot(reference)["price"] == price fetch.assert_called_once() @pytest.mark.parametrize("updates,source", [ ({"underlying": "BANKNIFTY"}, "jugaad"), ({"underlying": "RELIANCE", "underlying_type": "STOCK"}, "jugaad"), ({"expiry": "2099-11-26"}, "jugaad"), ({"instrument_type": "FUTURE"}, "jugaad"), ({}, "nse_snapshot"), ]) def test_snapshot_download_cache_separates_feeds(updates, source): reference = fo.validate_contract(contract(), "OPTION") other = {**reference, **updates} with patch("fo_quotes._fetch_payload", side_effect=[{"feed": 1}, {"feed": 2}]) as fetch: assert fo_quotes._cached_payload(reference, "jugaad") == {"feed": 1} assert fo_quotes._cached_payload(other, source) == {"feed": 2} assert fo_quotes._cached_payload(reference, "jugaad") == {"feed": 1} assert fetch.call_count == 2 def test_snapshot_download_reuses_pending_work(): reference = fo.validate_contract(contract(), "OPTION") started, release, second_started = Event(), Event(), Event() def fetch(*args): started.set() assert release.wait(2) return {"data": []} def second(): second_started.set() return fo_quotes._cached_payload(reference, "jugaad") with patch("fo_quotes._fetch_payload", side_effect=fetch) as download, ThreadPoolExecutor(max_workers=2) as workers: first = workers.submit(fo_quotes._cached_payload, reference, "jugaad") try: assert started.wait(2) pending = workers.submit(second) assert second_started.wait(2) finally: release.set() assert first.result(timeout=2) == pending.result(timeout=2) == {"data": []} download.assert_called_once() def test_snapshot_download_caches_failures_and_retries_after_ttl(): reference = fo.validate_contract(contract(), "OPTION") with patch("fo_quotes.time.monotonic", return_value=1) as clock, patch("fo_quotes._fetch_payload", side_effect=fo_quotes.requests.Timeout()) as download: for attempt in range(2): with pytest.raises(fo.FoUnavailable): fo_quotes._cached_payload(reference, "jugaad") download.assert_called_once() clock.return_value = 32 download.side_effect = None download.return_value = {"retry": True} assert fo_quotes._cached_payload(reference, "jugaad") == {"retry": True} assert download.call_count == 2 def test_failed_snapshot_is_retried_within_seconds_but_good_ones_are_reused_for_30s(): reference = fo.validate_contract(contract(), "OPTION") with patch("fo_quotes.time.monotonic", return_value=1) as clock, patch("fo_quotes._fetch_payload", side_effect=fo_quotes.requests.Timeout()) as download: with pytest.raises(fo.FoUnavailable): fo_quotes._cached_payload(reference, "jugaad") clock.return_value = 4 with pytest.raises(fo.FoUnavailable): fo_quotes._cached_payload(reference, "jugaad") assert download.call_count == 1 # still inside the short failure window clock.return_value = 7 download.side_effect = None download.return_value = {"ok": True} assert fo_quotes._cached_payload(reference, "jugaad") == {"ok": True} clock.return_value = 30 # 23s after a success: reused assert fo_quotes._cached_payload(reference, "jugaad") == {"ok": True} assert download.call_count == 2 def test_snapshot_download_limits_workers_without_leaving_pending_work(): reference = fo.validate_contract(contract(), "OPTION") with patch("fo_quotes._request_slots") as slots, patch("fo_quotes._fetch_payload") as download: slots.acquire.return_value = False for attempt in range(2): with pytest.raises(fo.FoUnavailable): fo_quotes._cached_payload(reference, "jugaad") slots.acquire.assert_called_once_with(timeout=5) slots.release.assert_not_called() download.assert_not_called() assert next(iter(fo_quotes._payloads.values()))[1].done() @pytest.fixture def contract_chart(): timestamp = datetime(2026, 10, 16, 9, 30, tzinfo=timezone.utc).timestamp() return {"identifier": "OPTIDXNIFTY29-10-2099PE25000.00", "name": "NIFTY", "grapthData": [[timestamp * 1000, 100], [(timestamp + 60) * 1000, 108.2]]} @pytest.mark.parametrize("chart", [False, True]) def test_direct_nse_requests_initialize_session(option_snapshot, contract_chart, chart): reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 16, 9, 32, tzinfo=fo.IST).timestamp() with patch("fo_quotes._SnapshotSession") as sessions, patch("fo_quotes.time.time", return_value=now): session = sessions.return_value.__enter__.return_value session.get.return_value.json.return_value = contract_chart if chart else option_snapshot if chart: fo_quotes._fetch_chart_payload(reference) else: fo_quotes._fetch_payload(reference, "nse_snapshot") assert session.get.call_args_list[0].args == ("https://www.nseindia.com/option-chain",) assert session.get.call_count == 2 def test_empty_nse_chart_payload_is_retried_before_falling_back(contract_chart): reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 16, 9, 32, tzinfo=fo.IST).timestamp() empty = {"closePrice": 0, "grapthData": 0, "identifier": None, "name": None} with patch("fo_quotes._SnapshotSession") as sessions, patch("fo_quotes.time.time", return_value=now), \ patch("fo_quotes.time.sleep"): session = sessions.return_value.__enter__.return_value session.get.return_value.json.side_effect = [empty, empty, contract_chart] assert fo_quotes._fetch_chart_payload(reference)["candles"] session.get.return_value.json.side_effect = [empty] * 3 with pytest.raises(ValueError, match="empty contract chart"): fo_quotes._fetch_chart_payload(reference) def test_contract_chart_preserves_exact_premium_observations(contract_chart, monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 16, 9, 32, tzinfo=fo.IST).timestamp() with patch("fo_quotes._SnapshotSession") as sessions, patch("fo_quotes.time.time", return_value=now): session = sessions.return_value.__enter__.return_value session.get.return_value.json.return_value = contract_chart result = fo_quotes.fetch_contract_chart(reference) assert fo_quotes.fetch_contract_chart(reference) == result assert session.get.call_count == 2 assert session.get.call_args.kwargs["params"] == { "index": "OPTIDXNIFTY29-10-2099PE25000.00", "kind": "fo"} assert result["contract_id"] == reference["contract_id"] assert result["chart_type"] == "line" and result["interval"] == "session" assert result["source"] == "nse_snapshot" assert result["as_of"] == "2026-10-16T09:31:00+05:30" assert result["candles"] == [{"time": int(now - 120), "close": 100}, {"time": int(now - 60), "close": 108.2}] assert not result["stale"] assert all("open" not in row for row in result["candles"]) @pytest.mark.parametrize("updates", [ {"identifier": "OPTIDXNIFTY29-10-2099CE25000.00"}, {"identifier": "OPTIDXNIFTY29-10-2099PE25050.00"}, {"identifier": "OPTIDXNIFTY28-10-2099PE25000.00"}, {"identifier": "NIFTY"}, {"grapthData": []}, {"grapthData": None}, {"grapthData": [[1, 100], [9999999999999, 100]]}, {"grapthData": [[1792123200000, "nan"]]}, ]) def test_contract_chart_rejects_wrong_contract_or_unusable_history(contract_chart, updates, monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") contract_chart.update(updates) reference = fo.validate_contract(contract(), "OPTION") with patch("fo_quotes._SnapshotSession") as sessions, patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 9, 32, tzinfo=fo.IST).timestamp()): sessions.return_value.__enter__.return_value.get.return_value.json.return_value = contract_chart with pytest.raises(fo.FoUnavailable): fo_quotes.fetch_contract_chart(reference) @pytest.mark.parametrize("underlying,underlying_type,kind,identifier", [ ("NIFTY", "INDEX", "FUTURE", "FUTIDXNIFTY29-10-2099XX0.00"), ("RELIANCE", "STOCK", "FUTURE", "FUTSTKRELIANCE29-10-2099XX0.00"), ("BANKNIFTY", "INDEX", "OPTION", "OPTIDXBANKNIFTY29-10-2099PE25000.00"), ("SBIN", "STOCK", "OPTION", "OPTSTKSBIN29-10-2099PE25000.00"), ]) def test_contract_charts_cover_stock_and_index_options_and_futures(contract_chart, underlying, underlying_type, kind, identifier, monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") reference = fo.validate_contract(contract(underlying=underlying, underlying_type=underlying_type), kind) contract_chart["identifier"] = identifier with patch("fo_quotes._SnapshotSession") as sessions, patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 9, 32, tzinfo=fo.IST).timestamp()): sessions.return_value.__enter__.return_value.get.return_value.json.return_value = contract_chart result = fo.FoService().chart(reference) assert result["contract_id"] == reference["contract_id"] assert len(result["candles"]) == 2 def test_contract_chart_cache_isolates_strikes_sides_and_expiries_and_refresh(monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") references = [fo.validate_contract(raw, kind) for raw, kind in [ (contract(strike=22800), "OPTION"), (contract(strike=22850), "OPTION"), (contract(strike=22800, option_type="CE"), "OPTION"), (contract(expiry="2099-11-26"), "OPTION"), (contract(), "FUTURE"), (contract(expiry="2099-11-26"), "FUTURE")]] with patch("fo_quotes._fetch_chart_payload", side_effect=lambda reference: { "contract_id": reference["contract_id"], "candles": [{"time": 1792123200, "close": 100}]}) as fetch: for reference in references: assert fo_quotes.fetch_contract_chart(reference)["contract_id"] == reference["contract_id"] assert fo_quotes.fetch_contract_chart(reference)["contract_id"] == reference["contract_id"] assert fetch.call_count == len(references) fo_quotes.fetch_contract_chart(references[0], refresh=True) assert fetch.call_count == len(references) + 1 monkeypatch.setenv("FO_NSE_SNAPSHOTS", "0") with pytest.raises(fo.FoUnavailable, match="disabled"): fo_quotes.fetch_contract_chart(references[0]) def test_new_weekly_contract_keeps_real_quote_history_when_nse_chart_fails(monkeypatch, tmp_path): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") monkeypatch.setenv("FO_LAST_QUOTES_PATH", str(tmp_path / "quotes.json")) reference = fo.validate_contract(contract(expiry="2026-11-03", strike=22950), "OPTION") service = fo.FoService() start = datetime(2026, 10, 30, 10, 0, tzinfo=fo.IST).timestamp() with patch.object(service, "_watchlist_quote") as fetch, \ patch("fo_quotes._fetch_chart_payload", side_effect=ValueError("NSE chart unavailable")), \ patch("fo_quotes.time.time") as clock: for offset, price in ((0, 129.6), (60, 130.2)): clock.return_value = start + offset fetch.return_value = {"contract_id": reference["contract_id"], "price": price, "quote_time": start + offset, "source": "nse_snapshot", "executable": False} service.watchlist_quote(reference) chart = service.chart(reference) assert chart["contract_id"] == reference["contract_id"] assert chart["source"] == "observed_contract_quotes" assert chart["candles"] == [{"time": start, "close": 129.6}, {"time": start + 60, "close": 130.2}] assert chart["stale"] is False fo_quotes._payloads.clear() with patch("fo_quotes._fetch_chart_payload", side_effect=ValueError("NSE unavailable")), \ patch("fo_quotes.time.time", return_value=start + 181): recovered = fo.FoService().chart(reference) assert recovered["candles"] == chart["candles"] assert recovered["stale"] is True @pytest.mark.parametrize("session,expiry", [ ("2026-10-30", "2026-11-03"), ("2026-11-06", "2026-11-10"), ("2026-11-13", "2026-11-17"), ]) @pytest.mark.parametrize("option_type", ["CE", "PE"]) def test_new_weekly_contract_merges_saved_quotes_with_sparse_successful_chart(session, expiry, option_type): reference = fo.validate_contract(contract(expiry=expiry, strike=22950, option_type=option_type), "OPTION") now = datetime.fromisoformat(session + "T10:01:00").replace(tzinfo=fo.IST).timestamp() latest = {"time": now, "close": 130.2} with patch("fo_quotes.time.time", return_value=now), \ patch("fo_quotes._fetch_chart_payload", return_value={ "contract_id": reference["contract_id"], "source": "nse_snapshot", "candles": [latest], "as_of": datetime.fromtimestamp(now, fo.IST).isoformat()}): fo_quotes.remember_contract_quote(reference, {"contract_id": reference["contract_id"], "price": 129.6, "quote_time": now - 60, "source": "nse_snapshot"}) chart = fo_quotes.fetch_contract_chart(reference) assert chart["contract_id"] == reference["contract_id"] assert chart["candles"] == [{"time": now - 60, "close": 129.6}, latest] assert chart["stale"] is False @pytest.mark.parametrize("updates", [ {"expiry": "2026-11-10"}, {"strike": 23000}, {"option_type": "CE"}, {"underlying": "BANKNIFTY"}, ]) def test_observed_history_never_substitutes_another_contract(updates): reference = fo.validate_contract(contract(expiry="2026-11-03", strike=22950), "OPTION") other = fo.validate_contract(contract(expiry="2026-11-03", strike=22950) | updates, "OPTION") now = datetime(2026, 10, 30, 10, 0, tzinfo=fo.IST).timestamp() with patch("fo_quotes.time.time", return_value=now), \ patch("fo_quotes._fetch_chart_payload", side_effect=ValueError("NSE unavailable")): fo_quotes.remember_contract_quote(reference, {"contract_id": reference["contract_id"], "price": 129.6, "quote_time": now, "source": "nse_snapshot"}) with pytest.raises(fo.FoUnavailable): fo_quotes.fetch_contract_chart(other) @pytest.mark.parametrize("updates", [ {"source": "manual"}, {"source": "manual_mark"}, {"source": None}, {"contract_id": "another-contract"}, {"quote_time": None}, {"quote_time": True}, {"quote_time": float("inf")}, {"price": float("nan")}, {"price": 0}, ]) def test_observed_history_rejects_unverified_quotes(updates): reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 30, 10, 0, tzinfo=fo.IST).timestamp() quote = {"contract_id": reference["contract_id"], "price": 129.6, "quote_time": now, "source": "nse_snapshot", **updates} with patch("fo_quotes.time.time", return_value=now): fo_quotes.remember_contract_quote(reference, quote) assert fo_quotes._observed_history(reference) == [] def test_fresh_observed_quotes_replace_a_stale_successful_nse_chart(): reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 30, 10, 0, tzinfo=fo.IST).timestamp() with patch("fo_quotes.time.time", return_value=now), \ patch("fo_quotes._fetch_chart_payload", return_value={"candles": [{"time": now - 300, "close": 120}]}): fo_quotes.remember_contract_quote(reference, {"contract_id": reference["contract_id"], "price": 129.6, "quote_time": now, "source": "nse_snapshot"}) chart = fo_quotes.fetch_contract_chart(reference) assert chart["candles"][-1] == {"time": now, "close": 129.6} assert chart["stale"] is False def test_observed_history_does_not_invent_ticks_or_bridge_sessions(): reference = fo.validate_contract(contract(), "OPTION") now = datetime(2026, 10, 30, 9, 15, tzinfo=fo.IST).timestamp() quote = {"contract_id": reference["contract_id"], "price": 129.6, "source": "nse_snapshot"} with patch("fo_quotes.time.time", return_value=now), \ patch("fo_quotes._fetch_chart_payload", side_effect=ValueError("NSE unavailable")): for timestamp in (now - 8 * 86400, now - 86400, now, now, now + 60): fo_quotes.remember_contract_quote(reference, {**quote, "quote_time": timestamp}) assert fo_quotes.fetch_contract_chart(reference)["candles"] == [{"time": now, "close": 129.6}] def test_history_storage_failure_does_not_break_quotes(monkeypatch, tmp_path): import sqlite3 monkeypatch.setenv("FO_LAST_QUOTES_PATH", str(tmp_path / "quotes.json")) reference = fo.validate_contract(contract(), "OPTION") quote = {"contract_id": reference["contract_id"], "price": 129.6, "quote_time": datetime.now(fo.IST).timestamp(), "source": "nse_snapshot"} service = fo.FoService() with patch("database.get_app_result_cache", side_effect=sqlite3.OperationalError("busy")), \ patch.object(service, "_watchlist_quote", return_value=quote): assert service.watchlist_quote(reference) == quote @pytest.mark.parametrize("updates", [ {"underlying": "BANKNIFTY"}, {"expiryDate": "28-10-2099"}, {"expiryDate": None}, {"strikePrice": 24900}, {"identifier": "OPTIDXNIFTY29-10-2099CE25000.00"}, {"identifier": "OPTSTKNIFTY29-10-2099PE25000.00"}, {"lastPrice": 0}, {"lastPrice": True}, {"lastPrice": "nan"}, {"instrumentType": "FUTIDX"}, ]) def test_contract_snapshot_rejects_wrong_contract_and_invalid_prices(option_snapshot, updates): option_snapshot["records"]["data"][0]["PE"].update(updates) with patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp()): with pytest.raises(ValueError): fo_quotes._parse_snapshot(option_snapshot, fo.validate_contract(contract(), "OPTION"), "nse_snapshot") @pytest.mark.parametrize("payload", [None, {}, {"records": []}, {"records": {"data": [], "timestamp": "invalid"}}, {"records": {"data": [], "timestamp": "01-Oct-2026 09:30:00"}}, {"records": {"data": [], "timestamp": "17-Oct-2026 09:30:00"}}]) def test_contract_snapshot_rejects_malformed_and_unbounded_timestamps(payload): with patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp()): with pytest.raises((ValueError, TypeError)): fo_quotes._parse_snapshot(payload, fo.validate_contract(contract(), "OPTION"), "nse_snapshot") def test_contract_snapshot_preserves_stale_last_session_quote(option_snapshot): with patch("fo_quotes.time.time", return_value=datetime(2026, 10, 16, 16, 0, tzinfo=fo.IST).timestamp()): quote = fo_quotes._parse_snapshot(option_snapshot, fo.validate_contract(contract(), "OPTION"), "nse_snapshot") assert quote["price"] == 108.2 and quote["stale"] @pytest.mark.parametrize("underlying_type,kind,method", [ ("INDEX", "OPTION", "index_option_chain"), ("STOCK", "OPTION", "equities_option_chain"), ("INDEX", "FUTURE", "stock_quote_fno"), ("STOCK", "FUTURE", "stock_quote_fno"), ]) def test_snapshot_tries_jugaad_then_direct_nse(option_snapshot, underlying_type, kind, method, monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "1") reference = fo.validate_contract(contract(underlying_type=underlying_type), kind) if kind == "FUTURE": raw = option_snapshot["records"]["data"][0]["PE"] option_snapshot = {"timestamp": "16-Oct-2026 09:30:00", "data": [{**raw, "instrumentType": "FUTIDX" if underlying_type == "INDEX" else "FUTSTK", "identifier": ("FUTIDX" if underlying_type == "INDEX" else "FUTSTK") + "NIFTY29-10-2099"}]} elif underlying_type == "STOCK": option_snapshot["records"]["data"][0]["PE"]["identifier"] = "OPTSTKNIFTY29-10-2099PE25000.00" with patch("fo_quotes._SnapshotSession") as sessions, patch("jugaad_data.nse.NSELive." + method) as jugaad: sessions.return_value.__enter__.return_value.get.return_value.json.return_value = option_snapshot now = datetime(2026, 10, 16, 9, 31, tzinfo=fo.IST).timestamp() with patch("fo_quotes.time.time", return_value=now): jugaad.return_value = option_snapshot assert fo_quotes.fetch_contract_snapshot(reference)["source"] == "jugaad" fo_quotes._payloads.clear() jugaad.side_effect = fo_quotes.requests.Timeout() assert fo_quotes.fetch_contract_snapshot(reference)["source"] == "nse_snapshot" fo_quotes._payloads.clear() sessions.return_value.__enter__.return_value.get.return_value.json.return_value = {} with pytest.raises(fo.FoUnavailable, match="Exact contract"): fo_quotes.fetch_contract_snapshot(reference) @pytest.mark.parametrize("direct_timestamp,expected_source", [ ("16-Oct-2026 09:32:30", "nse_snapshot"), ("16-Oct-2026 09:29:00", "jugaad"), (None, "jugaad"), ]) def test_stale_snapshot_checks_direct_source_and_retains_newest_verified_quote(option_snapshot, direct_timestamp, expected_source): direct = json.loads(json.dumps(option_snapshot)) direct["records"]["timestamp"] = direct_timestamp now = datetime(2026, 10, 16, 9, 33, tzinfo=fo.IST).timestamp() with patch("fo_quotes.time.time", return_value=now), \ patch("fo_quotes._cached_payload", side_effect=[option_snapshot, direct]) as fetch: quote = fo_quotes.fetch_contract_snapshot(fo.validate_contract(contract(), "OPTION")) assert quote["source"] == expected_source assert quote["stale"] is (expected_source == "jugaad") assert fetch.call_count == 2 def test_snapshot_opt_out_and_http_timeout(monkeypatch): monkeypatch.setenv("FO_NSE_SNAPSHOTS", "0") with patch("fo_quotes._SnapshotSession") as sessions: with pytest.raises(fo.FoUnavailable, match="disabled"): fo_quotes.fetch_contract_snapshot(fo.validate_contract(contract(), "OPTION")) sessions.assert_not_called() with patch("requests.Session.request") as request: with fo_quotes._SnapshotSession() as session: session.get("https://www.nseindia.com/api/option-chain-v3", timeout=999) assert request.call_args.kwargs["timeout"] == (2, 3) request.return_value.raise_for_status.assert_called_once() def test_watchlist_snapshot_failure_is_rechecked_after_a_few_seconds(): service = fo.FoService() reference = fo.validate_contract(contract(), "OPTION") with patch("fo.fetch_contract_snapshot", side_effect=fo.FoUnavailable("Unavailable")) as fetch, patch("fo.time.monotonic") as clock: clock.return_value = 1 with pytest.raises(fo.FoUnavailable): service.watchlist_quote(reference) clock.return_value = 4 with pytest.raises(fo.FoUnavailable): service.watchlist_quote(reference) assert fetch.call_count == 1 clock.return_value = 7 fetch.side_effect = None fetch.return_value = {"price": 100, "quote_time": 1000} assert service.watchlist_quote(reference)["price"] == 100 assert fetch.call_count == 2 def test_watchlist_snapshot_cache_throttles_failures_and_rechecks_staleness(): service = fo.FoService() reference = fo.validate_contract(contract(), "OPTION") with patch("fo.fetch_contract_snapshot", return_value={"price": 100, "quote_time": 1000}), patch("fo.time.monotonic", return_value=1), patch("fo.time.time", return_value=1200): service.watchlist_quote(reference) assert service.watchlist_quote(reference)["stale"] service._snapshots.clear() with patch("fo.fetch_contract_snapshot", side_effect=fo.FoUnavailable("Unavailable")) as fetch: for attempt in range(2): with pytest.raises(fo.FoUnavailable): service.watchlist_quote(reference) assert fetch.call_count == 1 def test_reference_csv_is_provider_independent_and_filters_bad_rows(): text = "underlying,underlying_type,instrument_type,expiry,strike,option_type,lot_size,tick_size\n" text += "NIFTY,INDEX,OPTION,2099-10-29,25000,CE,25,0.05\n" text += "RELIANCE,STOCK,FUTURE,2099-10-29,,,250,0.05\n" text += "BAD,STOCK,OPTION,2020-01-01,100,CE,1,0.05\n" rows = fo.parse_reference_csv(text) assert len(rows) == 2 assert rows[0]["provider_ids"] == {} assert rows[1]["instrument_type"] == "FUTURE" @pytest.fixture def public_master(): return ("EXCH_ID,SEGMENT,SECURITY_ID,INSTRUMENT,UNDERLYING_SYMBOL,SM_EXPIRY_DATE," "STRIKE_PRICE,OPTION_TYPE,LOT_SIZE,TICK_SIZE\n" "NSE,D,47161,OPTIDX,NIFTY,2099-10-19,23000,CE,65.0,5.0000\n" "NSE,D,47162,OPTIDX,NIFTY,2099-10-19,23000,PE,65.0,5.0000\n" "NSE,D,47163,FUTIDX,NIFTY,2099-10-27,,XX,65.0,10.0000\n" "NSE,D,47164,OPTSTK,RELIANCE,2099-10-27,2500,CE,250.0,5.0000\n" "NSE,D,47165,FUTSTK,RELIANCE,2099-10-27,,XX,250.0,10.0000\n" "BSE,D,47166,OPTIDX,SENSEX,2099-10-19,80000,CE,20.0,5.0000\n" "NSE,E,2885,EQUITY,RELIANCE,,,,1.0,5.0000\n" "NSE,D,47167,OPTIDX,NIFTY,2020-10-19,23000,CE,65.0,5.0000\n") def test_public_master_validates_all_nse_contract_types(public_master): rows = fo.parse_public_reference_csv(public_master.splitlines()) assert len(rows) == 5 assert {row["instrument_type"] for row in rows} == {"OPTION", "FUTURE"} assert {row["underlying_type"] for row in rows} == {"INDEX", "STOCK"} assert rows[0]["lot_size"] == 65 assert rows[0]["tick_size"] == 0.05 assert rows[2]["tick_size"] == 0.1 assert rows[0]["provider_ids"] == {"dhan": {"security_id": "47161"}} assert fo.parse_public_reference_csv(public_master.replace("65.0", "65.5").splitlines()) == rows[3:] def test_public_discovery_starts_once_without_waiting_for_network(monkeypatch): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") monkeypatch.delenv("FO_REFERENCE_CSV", raising=False) service = fo.FoService() with patch("database.get_app_result_cache", return_value=None), patch("fo.threading.Thread") as worker: assert service.contracts() == [] assert service.status()["reference_state"] == "loading" assert service.status()["reference_source"] == "dhan_public" worker.return_value.start.assert_called_once() def test_public_discovery_restores_fresh_sqlite_cache_without_network(monkeypatch): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") monkeypatch.delenv("FO_REFERENCE_CSV", raising=False) valid = {**fo.validate_contract(contract(), "OPTION"), "provider_ids": {}} cached = {"result": {"contracts": [valid]}, "saved_at": 1000} with patch("database.get_app_result_cache", return_value=cached), patch("fo.time.time", return_value=1001), patch("fo.threading.Thread") as worker: service = fo.FoService() assert service.resolve(valid["contract_id"]) == valid assert service.status()["reference_state"] == "available" worker.assert_not_called() def test_public_discovery_fetches_and_persists_verified_rows(monkeypatch, public_master): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") response = Mock() response.__enter__ = Mock(return_value=response) response.__exit__ = Mock(return_value=False) response.headers = {"Content-Length": "1000"} response.iter_lines.return_value = public_master.splitlines() with patch("fo.requests.get", return_value=response) as fetch, patch("database.save_app_result_cache") as save: service = fo.FoService() service._refresh_public_reference() assert len(service._catalog) == 5 assert service._reference_state == "available" assert service._reference_loading is False assert save.call_args.args[1]["contracts"] == service._catalog assert fetch.call_args.args[0] == fo.PUBLIC_REFERENCE_URL assert "headers" not in fetch.call_args.kwargs def test_public_discovery_outage_is_bounded_and_does_not_fabricate_contracts(monkeypatch): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") monkeypatch.delenv("FO_REFERENCE_CSV", raising=False) with patch("fo.requests.get", side_effect=OSError), patch("fo.time.time", return_value=1000), patch("database.get_app_result_cache", return_value=None), patch("fo.threading.Thread") as worker: service = fo.FoService() service._refresh_public_reference() assert service.contracts() == [] assert service.status()["reference_state"] == "unavailable" worker.assert_not_called() @pytest.mark.parametrize("saved_at,rows", [(1000, [{"expiry": "2099-10-19"}]), (2000, []), (-200000, [])]) def test_public_discovery_discards_corrupt_future_and_expired_cache(monkeypatch, saved_at, rows): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") monkeypatch.delenv("FO_REFERENCE_CSV", raising=False) cached = {"result": {"contracts": rows}, "saved_at": saved_at} with patch("database.get_app_result_cache", return_value=cached), patch("fo.time.time", return_value=1001), patch("fo.threading.Thread") as worker: service = fo.FoService() assert service.contracts() == [] assert service.status()["reference_state"] == "loading" worker.return_value.start.assert_called_once() def test_public_discovery_uses_only_bounded_stale_cache_during_refresh(monkeypatch): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") monkeypatch.delenv("FO_REFERENCE_CSV", raising=False) valid = {**fo.validate_contract(contract(), "OPTION"), "provider_ids": {}} cached = {"result": {"contracts": [valid]}, "saved_at": 1000} with patch("database.get_app_result_cache", return_value=cached), patch("fo.time.time", return_value=90000), patch("fo.threading.Thread") as worker: service = fo.FoService() assert service.contracts() == [valid] assert service.status()["reference_state"] == "stale" worker.return_value.start.assert_called_once() with patch("fo.time.time", return_value=200000): assert service.contracts() == [] def test_public_discovery_rejects_oversized_and_empty_responses(monkeypatch): monkeypatch.setenv("FO_AUTO_REFERENCE", "1") response = Mock() response.__enter__ = Mock(return_value=response) response.__exit__ = Mock(return_value=False) response.iter_lines.return_value = [] with patch("fo.requests.get", return_value=response), patch("database.save_app_result_cache") as save: for size in ("65000000", "0"): response.headers = {"Content-Length": size} service = fo.FoService() service._refresh_public_reference() assert service._reference_state == "unavailable" assert service._reference_loading is False save.assert_not_called() def test_contract_catalog_removes_expiry_day_contracts_at_market_close(): raw = fo.validate_contract(contract(expiry="2026-10-19"), "OPTION", today=date(2026, 10, 15)) service = fo.FoService() with patch("fo.datetime") as clock: clock.now.return_value = datetime(2026, 10, 19, 15, 29, tzinfo=fo.IST) assert service._filter_contracts([raw], "", "", "") == [raw] clock.now.return_value = datetime(2026, 10, 19, 15, 30, tzinfo=fo.IST) assert service._filter_contracts([raw], "", "", "") == [] def test_quote_freshness_rejects_invalid_old_future_and_crossed_quotes(): raw = {"price": 100, "bid": 99, "ask": 101, "observed_at": 1000, "trade_time": 999, "source": "fake"} assert fo.normalize_quote(raw, now=1001)["stale"] is False for updates in ({"price": float("nan")}, {"observed_at": 0}, {"trade_time": 1200}, {"bid": 102}, {"stale": True}): assert fo.normalize_quote({**raw, **updates}, now=1001)["stale"] is True def test_provider_quote_cache_deduplicates_calls_and_keeps_timestamp(): provider = Mock() provider.capabilities.return_value = {"quotes": True, "option_chain": False, "margin": False} provider.quote.return_value = {"price": 100, "bid": 99, "ask": 101, "observed_at": 1000, "trade_time": 999, "source": "fake"} service = fo.FoService(provider=provider) valid = fo.validate_contract(contract(), "OPTION") with patch("fo.time.time", return_value=1001): assert service.quote(valid)["price"] == 100 assert service.quote(valid)["observed_at"] == 1000 provider.quote.assert_called_once() def test_optional_dhan_adapter_never_enables_without_browser_permission(): from fo_dhan import DhanFoProvider client = Mock(enabled=True, configured=True, yahoo_fallback_active=False) adapter = DhanFoProvider(client) with patch.dict("os.environ", {"DHAN_ALLOW_BROWSER_DATA": "0"}): assert not adapter.capabilities()["quotes"] with pytest.raises(fo.FoUnavailable): adapter.quote(contract()) client._request.assert_not_called() def test_optional_dhan_adapter_quotes_only_the_contract_and_hides_balance(): from fo_dhan import DhanFoProvider client = Mock(enabled=True, configured=True, yahoo_fallback_active=False) adapter = DhanFoProvider(client) raw = fo.validate_contract(contract(), "OPTION") raw["provider_ids"] = {"dhan": {"security_id": "123", "underlying_security_id": "13", "underlying_segment": "IDX_I"}} client._request.return_value = {"data": {"NSE_FNO": {"123": { "last_price": 100, "last_trade_time": "14/10/2026 10:00:00", "depth": {"buy": [{"price": 99, "quantity": 100}], "sell": [{"price": 101, "quantity": 100}]}}}}} with patch.dict("os.environ", {"DHAN_ALLOW_BROWSER_DATA": "1"}): quote = adapter.quote(raw) assert quote["price"] == 100 assert quote["bid"] == 99 client._request.assert_called_once_with("POST", "/marketfeed/quote", {"NSE_FNO": [123]}, timeout=8) client._request.return_value = {"totalMargin": 50000, "availableBalance": 123456} assert adapter.margin(raw, "SHORT", 50, 100) == 50000 def _snapshot_trade(**updates): reference = fo.validate_contract(contract(), "OPTION") return {"instrument_type": "OPTION", "status": "OPEN", "contract_data": json.dumps(reference), "price_source": "manual", **updates} @pytest.mark.parametrize("quote_age,status,quote_extra,reason", [ (30, "CLOSED", {}, "market is closed"), (900, "OPEN", {}, "too old"), (30, "OPEN", {"last_known": True}, "exact contract"), (30, "OPEN", {"contract_id": "NSE:OPTION:OTHER"}, "exact contract"), ]) def test_snapshot_exit_price_rejects_closed_market_old_or_wrong_quotes(quote_age, status, quote_extra, reason): trade = _snapshot_trade() quote = {"price": 101.2, "source": "jugaad", "quote_time": time.time() - quote_age, **quote_extra} with patch("fo.get_service") as service, patch("market_calendar.market_status", return_value={"status": status}): service.return_value.watchlist_quote.return_value = quote with pytest.raises(fo.FoUnavailable, match=reason): fo.snapshot_exit_price(trade) def test_snapshot_exit_price_returns_a_tick_aligned_last_traded_price(): trade = _snapshot_trade() quote = {"price": 101.23, "source": "jugaad", "quote_time": time.time() - 40} with patch("fo.get_service") as service, patch("market_calendar.market_status", return_value={"status": "OPEN"}): service.return_value.watchlist_quote.return_value = quote assert fo.snapshot_exit_price(trade) == 101.25 trade["contract_data"] = json.dumps({**json.loads(trade["contract_data"]), "expiry": "2020-01-01"}) with pytest.raises(fo.FoUnavailable): fo.snapshot_exit_price(trade) def test_expired_positions_are_unresolved_not_synthetically_settled(): from datetime import datetime trade = {"instrument_type": "OPTION", "status": "OPEN", "contract_data": json.dumps(contract(expiry="2026-10-14")), "price_source": "manual"} assert fo.expiry_state(trade, datetime(2026, 10, 14, 15, 20)) == "pre_expiry_exit_due" assert fo.expiry_state(trade, datetime(2026, 10, 14, 15, 30)) == "expired_unresolved" with pytest.raises(fo.FoUnavailable): fo.automatic_price(trade) def test_reference_file_loading_caching_filtering_and_failure_are_isolated(): service = fo.FoService() text = "underlying,underlying_type,instrument_type,expiry,strike,option_type,lot_size,tick_size\nNIFTY,INDEX,OPTION,2099-10-29,25000,PE,25,0.05\n" info = Mock(st_mtime_ns=100, st_mtime=1000, st_size=100) reader = mock_open(read_data=text) with patch.dict("os.environ", {"FO_REFERENCE_CSV": "/isolated/reference.csv"}), patch("fo.os.stat", return_value=info), patch("fo.time.time", return_value=1001), patch("builtins.open", reader): rows = service.contracts("NIFTY.NS", "OPTION", "2099-10-29") assert len(rows) == 1 assert service.resolve(rows[0]["contract_id"]) == rows[0] assert service.contracts("RELIANCE") == [] reader.assert_called_once() info.st_mtime = 0 with patch("fo.time.time", return_value=10 * 86400): assert service.contracts() == [] with patch.dict("os.environ", {"FO_REFERENCE_CSV": "/missing"}), patch("fo.os.stat", side_effect=OSError): assert service.status()["reference_state"] == "unavailable" def test_ambiguous_reference_rows_and_invalid_provider_maps_are_ignored(): text = "underlying,underlying_type,instrument_type,expiry,strike,option_type,lot_size,tick_size,provider_ids\n" prefix = "NIFTY,INDEX,OPTION,2099-10-29,25000,PE," assert fo.parse_reference_csv(text + prefix + "25,0.05,{}\n" + prefix + "50,0.05,{}\n") == [] assert fo.parse_reference_csv(text + prefix + "25,0.05,[]\n") == [] def test_quote_failure_returns_only_explicitly_stale_cached_data(): provider = Mock() provider.capabilities.return_value = {"quotes": True} service = fo.FoService(provider) valid = fo.validate_contract(contract(), "OPTION") raw = {"price": 100, "bid": 99, "ask": 101, "observed_at": 1000, "trade_time": 999} provider.quote.return_value = raw with patch("fo.time.time", return_value=1001): service.quote(valid) provider.quote.side_effect = OSError with patch("fo.time.time", return_value=1010): assert service.quote(valid)["stale"] service._quotes.clear() with pytest.raises(fo.FoUnavailable): service.quote(valid) with pytest.raises(fo.FoUnavailable): service.quote({}) def test_chain_caching_outage_and_margin_capabilities(): provider = Mock() provider.capabilities.return_value = {"option_chain": True, "margin": True} provider.chain.return_value = {"source": "fake", "contracts": [{"price": 100}]} provider.margin.return_value = 50000 service = fo.FoService(provider) raw = fo.validate_contract(contract(), "OPTION") with patch.object(service, "contracts", return_value=[raw]), patch("fo.time.time", return_value=1000): assert not service.chain("NIFTY", "2099-10-29")["stale"] service.chain("NIFTY", "2099-10-29") provider.chain.assert_called_once() provider.chain.side_effect = ValueError with patch.object(service, "contracts", return_value=[raw]), patch("fo.time.time", return_value=1010): assert service.chain("NIFTY", "2099-10-29")["stale"] service._chains.clear() with pytest.raises(fo.FoUnavailable): service.chain("NIFTY", "2099-10-29") assert service.margin(raw, "SHORT", 2, 100) == 50000 with pytest.raises(ValueError): service.margin(raw, "OTHER", 2, 100) with pytest.raises(fo.FoUnavailable): fo.FoService().margin(raw, "SHORT", 1, 100) with pytest.raises(fo.FoUnavailable): fo.FoService().chain("NIFTY", "2099-10-29") def test_execution_checks_depth_and_freshness_and_uses_correct_side(): quote = {"price": 100, "bid": 99, "ask": 101, "bid_quantity": 50, "ask_quantity": 25, "observed_at": 1000, "trade_time": 1000} with patch("fo.time.time", return_value=1001): assert fo.execution_price(quote, "LONG", 25) == 101 assert fo.execution_price(quote, "SHORT", 50) == 99 with pytest.raises(fo.FoUnavailable): fo.execution_price(quote, "LONG", 50) def test_live_entry_requires_reference_and_records_executable_quote(): raw = fo.validate_contract(contract(), "OPTION") service = Mock() service.resolve.return_value = raw service.status.return_value = {"capabilities": {"margin": True}} service.margin.return_value = 50000 service.quote.return_value = {"price": 100, "bid": 99, "ask": 101, "ask_quantity": 100, "bid_quantity": 100, "observed_at": 1000, "trade_time": 1000} with patch("fo.get_service", return_value=service), patch("market_calendar.market_status", return_value={"status": "OPEN"}), patch("fo.time.time", return_value=1001): fields = fo.prepare_entry(payload(contract_id=raw["contract_id"], price_source="market")) assert fields["entry_price"] == 101 assert json.loads(fields["contract_data"])["entry_quote"]["ask"] == 101 sold = fo.prepare_entry(payload(contract_id=raw["contract_id"], direction="SHORT", price_source="market")) assert sold["margin_estimate"] == 50000 assert sold["entry_price"] == 99 with pytest.raises(fo.FoUnavailable): fo.prepare_entry(payload(price_source="market")) with pytest.raises(ValueError): fo.prepare_entry(payload(order_type="BAD")) def test_registered_provider_and_manual_service_selection(monkeypatch): monkeypatch.setattr(fo, "_service", None) monkeypatch.setattr(fo, "_service_name", None) monkeypatch.setattr(fo, "_provider_factories", {}) monkeypatch.setenv("FO_PROVIDER", "fake") provider = Mock() fo.register_provider("fake", lambda: provider) assert fo.get_service().provider is provider assert fo.get_service() is fo.get_service() monkeypatch.setenv("FO_PROVIDER", "manual") assert fo.get_service().provider is None def test_optional_adapter_chain_checks_mapping_and_normalizes_snapshot(): from fo_dhan import DhanFoProvider client = Mock(enabled=True, configured=True, yahoo_fallback_active=False) adapter = DhanFoProvider(client) raw = fo.validate_contract(contract(), "OPTION") raw["provider_ids"] = {"dhan": {"security_id": "123", "underlying_security_id": "13", "underlying_segment": "IDX_I"}} option = {"security_id": 123, "last_price": 100, "top_bid_price": 99, "top_ask_price": 101, "oi": 100, "volume": 100, "implied_volatility": 15, "greeks": {"delta": -0.4, "theta": -1, "untrusted": "ignored"}} with patch.dict("os.environ", {"DHAN_ALLOW_BROWSER_DATA": "1"}): client._request.return_value = {"data": {"oc": {"25000.000000": {"pe": option}}}} result = adapter.chain([raw]) assert result["contracts"][0]["greeks"] == {"delta": -0.4, "theta": -1} assert result["contracts"][0]["iv"] == 15 client._request.return_value = {"data": {"oc": {}}} with pytest.raises(fo.FoUnavailable): adapter.chain([raw]) raw["provider_ids"]["dhan"]["underlying_segment"] = "NSE_EQ" with pytest.raises(fo.FoUnavailable): adapter.chain([raw]) with pytest.raises(fo.FoUnavailable): adapter.quote(contract()) def test_optional_chain_requests_use_the_shared_read_only_rate_bucket(): from dhan_client import DhanDataClient session = Mock() session.request.return_value.status_code = 200 session.request.return_value.json.return_value = {"status": "success", "data": {}} client = DhanDataClient("test-client", "test-token", enabled=True, session=session) with patch.object(client, "_cache_get", return_value=None), patch.object(client, "_cache_put"), patch("dhan_client.time.monotonic", return_value=1000): client._request("POST", "/optionchain", {"UnderlyingScrip": 13}, timeout=8) assert client._last_request["optionchain"] == 1000 assert "data" not in client._last_request def test_optional_adapter_rejects_malformed_quote_payloads(): from fo_dhan import DhanFoProvider client = Mock(enabled=True, configured=True, yahoo_fallback_active=False) adapter = DhanFoProvider(client) raw = fo.validate_contract(contract(), "OPTION") raw["provider_ids"] = {"dhan": {"security_id": "123"}} with patch.dict("os.environ", {"DHAN_ALLOW_BROWSER_DATA": "1"}): for response in ({"data": []}, {"data": {"NSE_FNO": []}}, {"data": {"NSE_FNO": {"123": {"depth": []}}}}): client._request.return_value = response with pytest.raises(fo.FoUnavailable): adapter.quote(raw)
import json
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime, timezone
from threading import Event
from unittest.mock import Mock, patch, mock_open
import pytest
import fo
import fo_quotes
@pytest.fixture(autouse=True)
def isolate_snapshot_downloads(monkeypatch):
import database
histories = {}
get_cached = database.get_app_result_cache
save_cached = database.save_app_result_cache
def get_history(key):
return histories.get(key) if key.startswith("fo_chart:") else get_cached(key)
def save_history(key, result, saved_at=None):
if key.startswith("fo_chart:"):
histories[key] = {"result": result, "saved_at": saved_at}
else:
save_cached(key, result, saved_at)
monkeypatch.setattr(database, "get_app_result_cache", get_history)
monkeypatch.setattr(database, "save_app_result_cache", save_history)
fo_quotes._payloads.clear()
yield
fo_quotes._payloads.clear()
def contract(**updates):
return {"exchange": "NSE", "underlying": "NIFTY", "underlying_type": "INDEX",
"expiry": "2099-10-29", "strike": 25000, "option_type": "PE",
"lot_size": 25, "tick_size": 0.05, **updates}
def payload(**updates):
return {"instrument_type": "OPTION", "contract": contract(), "lots": 2,
"direction": "LONG", "entry_price": 100, "price_source": "manual", **updates}
def test_put_buy_is_long_premium_and_uses_lots_not_client_shares():
result = fo.validate_trade(payload(shares=9999))
assert result["direction"] == "LONG"
assert result["shares"] == 50
assert json.loads(result["contract_data"])["option_type"] == "PE"
@pytest.mark.parametrize("updates", [
{"lots": 0}, {"lots": 1.5}, {"lots": True}, {"entry_price": "nan"},
{"entry_price": "inf"}, {"entry_price": -1}, {"entry_price": 100.01},
{"direction": "BEARISH"}, {"stop_loss": 101}, {"target": 99},
{"margin_estimate": "nan"}, {"contract": None},
])
def test_manual_trade_rejects_invalid_inputs(updates):
with pytest.raises(ValueError):
fo.validate_trade(payload(**updates))
@pytest.mark.parametrize("updates", [
{"underlying": "<script>"}, {"underlying_type": "OTHER"}, {"exchange": "BSE"},
{"expiry": "2020-01-01"}, {"expiry": "2099-02-30"}, {"lot_size": 0},
{"tick_size": 0}, {"option_type": "CALL"}, {"strike": 0},
])
def test_contract_validation(updates):
with pytest.raises(ValueError):
fo.validate_contract(contract(**updates), "OPTION", today=date(2026, 10, 14))
def test_contract_identity_separates_strikes_expiries_and_instruments():
contracts = [contract(), contract(strike=25100), contract(expiry="2099-11-26")]
identities = {fo.validate_contract(raw, "OPTION")["contract_id"] for raw in contracts}
identities.add(fo.validate_contract(contract(), "FUTURE")["contract_id"])
assert len(identities) == 4
@pytest.mark.parametrize("now,expiry,today_status,one_day_status,target", [
("2026-10-16T10:00:00+05:30", "2026-10-19", "not_trained", "not_trained", "2026-10-19"),
("2026-10-19T10:00:00+05:30", "2026-10-19", "not_trained", "after_expiry", "2026-10-20"),
("2026-10-16T15:00:00+05:30", "2026-10-19", "session_closed", "not_trained", "2026-10-19"),
("2026-10-17T10:00:00+05:30", "2026-10-19", "session_closed", "not_trained", "2026-10-19"),
("2026-10-19T15:30:00+05:30", "2026-10-19", "expired", "expired", "2026-10-20"),
("2026-10-01T10:00:00+05:30", "2026-10-05", "not_trained", "not_trained", "2026-10-05"),
])
def test_derivative_forecast_windows_stop_at_expiry(now, expiry, today_status, one_day_status, target):
windows = fo.forecast_windows(contract(expiry=expiry), now=datetime.fromisoformat(now))
assert windows["INTRADAY"]["status"] == today_status
assert windows["1D"]["status"] == one_day_status
assert windows["1D"]["end_at"] == target + "T15:30:00+05:30"
assert windows["INTRADAY"]["eligible"] == (today_status == "not_trained")
assert windows["1D"]["eligible"] == (one_day_status == "not_trained")
def test_margin_is_required_for_futures_and_sold_options():
for updates in ({"instrument_type": "FUTURE"}, {"direction": "SHORT"}):