PaperTrade-India 0.1.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. papertrade_india/__init__.py +250 -0
  2. papertrade_india/_context.py +144 -0
  3. papertrade_india/broker.py +546 -0
  4. papertrade_india/cli.py +474 -0
  5. papertrade_india/clock.py +29 -0
  6. papertrade_india/corporate_actions/__init__.py +10 -0
  7. papertrade_india/corporate_actions/bonus.py +105 -0
  8. papertrade_india/corporate_actions/dividends.py +99 -0
  9. papertrade_india/corporate_actions/rights.py +189 -0
  10. papertrade_india/corporate_actions/splits.py +111 -0
  11. papertrade_india/corporate_actions/store.py +247 -0
  12. papertrade_india/data/nse_holidays_2026.json +22 -0
  13. papertrade_india/data/nse_holidays_2027.json +9 -0
  14. papertrade_india/data/nse_universe_sample.csv +31 -0
  15. papertrade_india/domain/__init__.py +6 -0
  16. papertrade_india/domain/exceptions.py +183 -0
  17. papertrade_india/domain/models.py +213 -0
  18. papertrade_india/domain/rules/__init__.py +5 -0
  19. papertrade_india/domain/rules/risk.py +165 -0
  20. papertrade_india/domain/rules/tick_lot_band.py +139 -0
  21. papertrade_india/events.py +29 -0
  22. papertrade_india/exceptions.py +29 -0
  23. papertrade_india/execution/__init__.py +5 -0
  24. papertrade_india/execution/book.py +385 -0
  25. papertrade_india/execution/fees.py +213 -0
  26. papertrade_india/execution/settlement.py +360 -0
  27. papertrade_india/execution/simulation.py +176 -0
  28. papertrade_india/execution/slippage.py +120 -0
  29. papertrade_india/fees.py +29 -0
  30. papertrade_india/idempotency.py +29 -0
  31. papertrade_india/infrastructure/__init__.py +6 -0
  32. papertrade_india/infrastructure/clock.py +123 -0
  33. papertrade_india/infrastructure/events.py +137 -0
  34. papertrade_india/infrastructure/holidays.py +138 -0
  35. papertrade_india/infrastructure/idempotency.py +133 -0
  36. papertrade_india/infrastructure/ledger.py +141 -0
  37. papertrade_india/infrastructure/market_hours.py +200 -0
  38. papertrade_india/infrastructure/migrations.py +622 -0
  39. papertrade_india/infrastructure/observability.py +195 -0
  40. papertrade_india/infrastructure/persistence.py +130 -0
  41. papertrade_india/infrastructure/symbols.py +279 -0
  42. papertrade_india/infrastructure/watchlist.py +78 -0
  43. papertrade_india/interface.py +92 -0
  44. papertrade_india/ledger.py +29 -0
  45. papertrade_india/limit_orders.py +29 -0
  46. papertrade_india/market_hours.py +29 -0
  47. papertrade_india/microstructure.py +57 -0
  48. papertrade_india/migrations.py +29 -0
  49. papertrade_india/models.py +29 -0
  50. papertrade_india/observability.py +29 -0
  51. papertrade_india/orders/__init__.py +5 -0
  52. papertrade_india/orders/amo.py +98 -0
  53. papertrade_india/orders/book_helpers.py +111 -0
  54. papertrade_india/orders/bracket.py +115 -0
  55. papertrade_india/orders/limit.py +210 -0
  56. papertrade_india/orders/market.py +264 -0
  57. papertrade_india/orders/partial_fills.py +92 -0
  58. papertrade_india/orders/preopen.py +274 -0
  59. papertrade_india/orders/state.py +640 -0
  60. papertrade_india/orders/stop.py +122 -0
  61. papertrade_india/orders/submit.py +385 -0
  62. papertrade_india/partial_fills.py +29 -0
  63. papertrade_india/persistence.py +29 -0
  64. papertrade_india/preopen.py +29 -0
  65. papertrade_india/presets.py +120 -0
  66. papertrade_india/price_feed.py +316 -0
  67. papertrade_india/providers/__init__.py +123 -0
  68. papertrade_india/providers/alphavantage.py +180 -0
  69. papertrade_india/providers/base.py +256 -0
  70. papertrade_india/providers/cache.py +147 -0
  71. papertrade_india/providers/composite.py +244 -0
  72. papertrade_india/providers/dhan.py +266 -0
  73. papertrade_india/providers/finnhub.py +122 -0
  74. papertrade_india/providers/health.py +233 -0
  75. papertrade_india/providers/jugaad.py +142 -0
  76. papertrade_india/providers/kite.py +222 -0
  77. papertrade_india/providers/nse_bhavcopy.py +210 -0
  78. papertrade_india/providers/nsepython.py +98 -0
  79. papertrade_india/providers/registry.py +226 -0
  80. papertrade_india/providers/stooq.py +173 -0
  81. papertrade_india/providers/twelvedata.py +198 -0
  82. papertrade_india/providers/upstox.py +318 -0
  83. papertrade_india/providers/upstox_instruments.py +171 -0
  84. papertrade_india/providers/yfinance.py +205 -0
  85. papertrade_india/quickstart.py +111 -0
  86. papertrade_india/reads/__init__.py +6 -0
  87. papertrade_india/reads/account.py +140 -0
  88. papertrade_india/reads/orders.py +54 -0
  89. papertrade_india/reads/positions.py +188 -0
  90. papertrade_india/risk.py +29 -0
  91. papertrade_india/settlement.py +29 -0
  92. papertrade_india/simulation.py +29 -0
  93. papertrade_india/slippage.py +29 -0
  94. papertrade_india/symbols.py +29 -0
  95. papertrade_india/workers/__init__.py +6 -0
  96. papertrade_india/workers/limit_orders.py +390 -0
  97. papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
  98. papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
  99. papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
  100. papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  101. papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,195 @@
1
+ """Observability hooks.
2
+
3
+ The broker emits structured events as Python callbacks. The consumer
4
+ wires those into whatever observability stack they use (OpenTelemetry,
5
+ Prometheus, Datadog, plain logs). The broker itself doesn't pull in any
6
+ of those dependencies.
7
+
8
+ Two parallel mechanisms:
9
+
10
+ 1. **Event log** (``events.py``): persisted to SQLite. Survives process
11
+ restarts. Use for audits, replay, post-hoc analysis.
12
+ 2. **Callback bus** (this module): in-process, ephemeral. Use for live
13
+ metrics, real-time alerts, log shipping. Multiple subscribers
14
+ supported; one bad subscriber doesn't poison the others.
15
+
16
+ Callbacks fire AFTER state has been committed. They cannot veto an
17
+ order; for that, you want ``risk.py`` (pre-trade) instead.
18
+
19
+ Failure handling
20
+ ----------------
21
+ A subscriber that raises is logged and skipped. Other subscribers still
22
+ run. This is the right tradeoff: the broker's correctness must not
23
+ depend on whether a metrics shipper is healthy.
24
+
25
+ Per-subscription filtering
26
+ --------------------------
27
+ ``EventBus.subscribe(fn, event_types=("order_filled", "order_cancelled"))``
28
+ delivers only the listed types to ``fn``. Saves subscribers from doing
29
+ their own filter dispatch.
30
+
31
+ Replay from the persisted log
32
+ -----------------------------
33
+ ``EventBus.replay_from_broker(broker, since=..., event_types=...)``
34
+ fetches historical events from the SQLite log and dispatches them to
35
+ all current subscribers. Useful when a long-lived subscriber crashes
36
+ and needs to catch up, or when adding a subscriber to a process that
37
+ has already been running.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import logging
43
+ from collections.abc import Callable, Iterable
44
+ from dataclasses import dataclass, field
45
+ from datetime import datetime
46
+ from typing import TYPE_CHECKING, Any
47
+
48
+ if TYPE_CHECKING: # avoid runtime circular import
49
+ from .broker import IndiaPaperBroker # noqa: F401
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class BrokerEvent:
56
+ """In-memory mirror of a persisted event, delivered to subscribers.
57
+
58
+ Same shape as ``events.Event`` minus the SQLite id (subscribers
59
+ rarely care about it).
60
+ """
61
+
62
+ event_type: str
63
+ account_id: str | None
64
+ order_id: str | None
65
+ payload: dict[str, Any]
66
+ # Wall-clock time the event was recorded. Set automatically by the
67
+ # broker when emitting; replay-from-log preserves the original time.
68
+ recorded_at: datetime | None = None
69
+
70
+
71
+ # A subscriber is any callable that takes a BrokerEvent. We wrap it in
72
+ # a private record so we can attach a name (for failure logs) and an
73
+ # optional filter set.
74
+ Subscriber = Callable[[BrokerEvent], None]
75
+
76
+
77
+ @dataclass
78
+ class _NamedSub:
79
+ name: str
80
+ fn: Subscriber
81
+ # When non-None, only events whose type is in this set are delivered.
82
+ # None means "deliver everything" (the default).
83
+ event_types: frozenset[str] | None = None
84
+
85
+
86
+ @dataclass
87
+ class EventBus:
88
+ """In-process pub/sub for ``BrokerEvent``.
89
+
90
+ Thread-safety: subscriber lists are mutated rarely (subscribe at
91
+ startup) and iterated frequently (publish per order). We don't
92
+ bother with a lock — Python's GIL + append-only list iteration is
93
+ safe enough for the typical "register at boot" usage. If you need
94
+ dynamic subscribe/unsubscribe under load, wrap a lock externally.
95
+ """
96
+
97
+ subscribers: list[_NamedSub] = field(default_factory=list)
98
+
99
+ def subscribe(
100
+ self,
101
+ fn: Subscriber,
102
+ name: str | None = None,
103
+ event_types: Iterable[str] | None = None,
104
+ ) -> None:
105
+ """Register a subscriber.
106
+
107
+ Parameters
108
+ ----------
109
+ fn:
110
+ The callable to invoke for each matching event.
111
+ name:
112
+ Used in failure logs. Defaults to ``fn.__name__``.
113
+ event_types:
114
+ When provided, only events whose ``event_type`` is in the
115
+ set are delivered to this subscriber. ``None`` (default)
116
+ delivers every event.
117
+ """
118
+ n = name or getattr(fn, "__name__", repr(fn))
119
+ et = frozenset(event_types) if event_types is not None else None
120
+ self.subscribers.append(_NamedSub(name=n, fn=fn, event_types=et))
121
+
122
+ def unsubscribe(self, fn: Subscriber) -> bool:
123
+ """Remove the first subscriber whose ``fn`` matches. Returns
124
+ whether one was removed."""
125
+ for i, sub in enumerate(self.subscribers):
126
+ if sub.fn is fn:
127
+ del self.subscribers[i]
128
+ return True
129
+ return False
130
+
131
+ def publish(self, event: BrokerEvent) -> None:
132
+ """Fan out to every matching subscriber. Failures are isolated."""
133
+ if not self.subscribers:
134
+ return
135
+ for sub in self.subscribers:
136
+ if sub.event_types is not None and event.event_type not in sub.event_types:
137
+ continue
138
+ try:
139
+ sub.fn(event)
140
+ except Exception as e: # noqa: BLE001 — defensive
141
+ logger.exception(
142
+ "Subscriber %s failed handling %s: %s",
143
+ sub.name, event.event_type, e,
144
+ )
145
+
146
+ def replay_from_broker(
147
+ self,
148
+ broker: IndiaPaperBroker,
149
+ since: datetime | None = None,
150
+ event_types: Iterable[str] | None = None,
151
+ limit: int = 10_000,
152
+ ) -> int:
153
+ """Re-dispatch persisted events to current subscribers.
154
+
155
+ Useful for:
156
+ - Bootstrapping a new subscriber after the process has been running.
157
+ - Catching a crashed subscriber up after a restart.
158
+
159
+ Returns the count of events replayed (post-filter on subscribers).
160
+ """
161
+ types_tuple = tuple(event_types) if event_types is not None else None
162
+ rows = broker.get_events(limit=limit, event_types=types_tuple)
163
+ # ``get_events`` returns newest-first; replay should be chronological.
164
+ rows = list(reversed(rows))
165
+ if since is not None:
166
+ # Persisted timestamps are tz-aware (IST); coerce a naive
167
+ # ``since`` to the persisted rows' tzinfo so comparison
168
+ # doesn't raise. We don't *change* the wall-clock value —
169
+ # this is a best-effort assumption that callers passing a
170
+ # naive datetime mean it in the broker's local zone.
171
+ if since.tzinfo is None and rows and rows[0].recorded_at.tzinfo is not None:
172
+ since = since.replace(tzinfo=rows[0].recorded_at.tzinfo)
173
+ rows = [r for r in rows if r.recorded_at >= since]
174
+ count = 0
175
+ for row in rows:
176
+ ev = BrokerEvent(
177
+ event_type=row.event_type,
178
+ account_id=row.account_id,
179
+ order_id=row.order_id,
180
+ payload=dict(row.payload),
181
+ recorded_at=row.recorded_at,
182
+ )
183
+ self.publish(ev)
184
+ count += 1
185
+ return count
186
+
187
+
188
+ # Convenience: a logging subscriber for quick smoke tests.
189
+ def stdlib_log_subscriber(event: BrokerEvent) -> None:
190
+ """Log every event at INFO. Useful for ``broker.events.subscribe(...)``
191
+ during development."""
192
+ logger.info(
193
+ "event=%s account=%s order=%s payload=%s",
194
+ event.event_type, event.account_id, event.order_id, event.payload,
195
+ )
@@ -0,0 +1,130 @@
1
+ """Thread-safe SQLite persistence layer.
2
+
3
+ Why this looks the way it does:
4
+
5
+ - **Thread-local connections.** SQLite connections aren't safe to share
6
+ across threads by default. We give each thread its own.
7
+ - **WAL journal mode.** Allows concurrent readers + one writer without
8
+ blocking, which matters for the limit-order watcher running alongside
9
+ the main broker thread.
10
+ - **Manual transactions.** ``isolation_level=None`` disables Python's
11
+ implicit-transaction wrapping. The :meth:`Persistence.transaction`
12
+ context manager wraps multi-statement operations atomically, with
13
+ rollback on any exception.
14
+ - **Foreign keys ON.** Enforced explicitly because SQLite's default is
15
+ off, even on modern versions.
16
+ - **Versioned schema migrations.** ``migrations.run_migrations`` is
17
+ invoked on first-thread connect. Brand-new DBs run from version 0 to
18
+ the current head; legacy 0.1.x DBs are detected, stamped at v1, and
19
+ upgraded forward. See ``migrations.py`` for the full design.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import sqlite3
25
+ import threading
26
+ from collections.abc import Iterator
27
+ from contextlib import contextmanager
28
+ from pathlib import Path
29
+
30
+ from . import migrations as _migrations
31
+
32
+ PathLike = str | Path
33
+
34
+
35
+ class Persistence:
36
+ """Thread-safe SQLite wrapper.
37
+
38
+ One connection per thread (sqlite3 isn't safe to share). WAL mode
39
+ allows concurrent readers + one writer.
40
+
41
+ The :meth:`transaction` context manager wraps multi-statement
42
+ operations so partial failures don't corrupt account state.
43
+ """
44
+
45
+ def __init__(self, db_path: PathLike) -> None:
46
+ self.db_path = str(db_path)
47
+ Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
48
+ self._local = threading.local()
49
+ # Run migrations on first connect. Brand-new DBs apply from v0
50
+ # to head; legacy DBs are stamped + upgraded forward.
51
+ with self._connect() as conn:
52
+ # File-level PRAGMAs that must be set OUTSIDE any transaction
53
+ # (SQLite refuses ``PRAGMA journal_mode`` inside one). These
54
+ # used to live in the v1 schema string but moved out when
55
+ # we adopted versioned migrations.
56
+ conn.execute("PRAGMA journal_mode = WAL")
57
+ conn.execute("PRAGMA synchronous = NORMAL")
58
+ _migrations.run_migrations(conn)
59
+
60
+ def _connect(self) -> sqlite3.Connection:
61
+ """Return the thread-local connection, creating it lazily."""
62
+ conn = getattr(self._local, "conn", None)
63
+ if conn is None:
64
+ conn = sqlite3.connect(
65
+ self.db_path,
66
+ isolation_level=None, # Manual transaction control
67
+ check_same_thread=True,
68
+ )
69
+ conn.row_factory = sqlite3.Row
70
+ # Each thread needs its own foreign-key setting. busy_timeout
71
+ # makes a concurrent writer WAIT for the lock (up to 5s)
72
+ # instead of failing immediately with "database is locked" —
73
+ # important once multiple UI sessions share one broker.
74
+ conn.execute("PRAGMA foreign_keys = ON")
75
+ conn.execute("PRAGMA busy_timeout = 5000")
76
+ self._local.conn = conn
77
+ return conn
78
+
79
+ @contextmanager
80
+ def transaction(self) -> Iterator[sqlite3.Connection]:
81
+ """Atomic multi-statement transaction.
82
+
83
+ Usage::
84
+
85
+ with persistence.transaction() as conn:
86
+ conn.execute("UPDATE account SET cash = cash - ? ...", ...)
87
+ conn.execute("INSERT INTO orders ...", ...)
88
+ # commits on exit; rolls back on exception
89
+ """
90
+ conn = self._connect()
91
+ conn.execute("BEGIN IMMEDIATE")
92
+ try:
93
+ yield conn
94
+ except Exception:
95
+ conn.execute("ROLLBACK")
96
+ raise
97
+ else:
98
+ conn.execute("COMMIT")
99
+
100
+ @contextmanager
101
+ def read(self) -> Iterator[sqlite3.Connection]:
102
+ """Read-only operations don't need explicit transactions."""
103
+ yield self._connect()
104
+
105
+ def close(self) -> None:
106
+ """Close this thread's connection. Subsequent calls re-open it lazily.
107
+
108
+ Note: this only closes the *calling* thread's connection. Other
109
+ thread-local connections remain open until their threads exit.
110
+ For long-lived daemon threads (e.g. ``LimitOrderWatcher``) that's
111
+ the desired behavior; for short-lived workers, call ``close()``
112
+ from inside the worker before it exits.
113
+ """
114
+ conn = getattr(self._local, "conn", None)
115
+ if conn is not None:
116
+ conn.close()
117
+ self._local.conn = None
118
+
119
+
120
+ # ──────────────────────────────────────────────────────────────────────
121
+ # Backwards-compat re-exports.
122
+ #
123
+ # The pre-migrations design exposed a module-level ``SCHEMA`` string
124
+ # and an ``EXTENSION_SCHEMAS`` tuple. Some external tests or scripts
125
+ # may still touch these. They're now thin aliases over the migrations
126
+ # module so behavior is preserved.
127
+ # ──────────────────────────────────────────────────────────────────────
128
+
129
+ SCHEMA = _migrations._INITIAL_SCHEMA_SQL
130
+ EXTENSION_SCHEMAS: tuple[str, ...] = () # everything is in v1 now
@@ -0,0 +1,279 @@
1
+ """Symbol master.
2
+
3
+ Tracks tradeable NSE/BSE symbols with optional metadata: long name,
4
+ exchange, lot size, ISIN, and a delisting timestamp. Two modes:
5
+
6
+ 1. **Lenient (default)**: an unknown symbol is accepted; orders for
7
+ symbols marked delisted are rejected with ``SymbolDelisted``. This is
8
+ the right default for a paper broker — a user typing
9
+ ``broker.buy("RELIANCE", 5)`` shouldn't have to seed a CSV first.
10
+ 2. **Strict** (``strict=True`` on ``SymbolMaster``): unknown symbols
11
+ are rejected with ``SymbolNotFound``. Use this for production-style
12
+ deployments where you want every symbol audited.
13
+
14
+ The master is account-scope-free — symbols are global to a database
15
+ file. A sample seed CSV ships in ``data/nse_universe_sample.csv`` with
16
+ ~30 of the largest Indian companies.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import csv
22
+ import sqlite3
23
+ from dataclasses import dataclass
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+
27
+ from ..domain.exceptions import SymbolDelisted, SymbolNotFound
28
+ from ..domain.models import Exchange
29
+ from .market_hours import IST
30
+
31
+ SCHEMA = """
32
+ CREATE TABLE IF NOT EXISTS symbols (
33
+ symbol TEXT NOT NULL,
34
+ exchange TEXT NOT NULL CHECK(exchange IN ('NSE','BSE')),
35
+ name TEXT,
36
+ isin TEXT,
37
+ lot_size INTEGER NOT NULL DEFAULT 1 CHECK(lot_size >= 1),
38
+ delisted_at TEXT,
39
+ added_at TEXT NOT NULL,
40
+ tick_size REAL,
41
+ daily_band_pct REAL,
42
+ PRIMARY KEY (symbol, exchange)
43
+ );
44
+
45
+ CREATE INDEX IF NOT EXISTS idx_symbols_delisted
46
+ ON symbols(delisted_at);
47
+ """
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class SymbolEntry:
52
+ symbol: str
53
+ exchange: Exchange
54
+ name: str | None
55
+ isin: str | None
56
+ lot_size: int
57
+ delisted_at: datetime | None
58
+ # Microstructure metadata. ``None`` = "use MicrostructureConfig
59
+ # defaults" (broker-wide ₹0.05 tick, ±20% band by default).
60
+ tick_size: float | None = None
61
+ daily_band_pct: float | None = None
62
+
63
+
64
+ class SymbolMaster:
65
+ """Symbol master backed by the broker's SQLite file.
66
+
67
+ Methods are designed to be called inside an open transaction (for
68
+ writes) or a read context (for queries). The broker holds a single
69
+ instance and threads its own connection in.
70
+ """
71
+
72
+ def __init__(self, strict: bool = False) -> None:
73
+ self.strict = strict
74
+
75
+ # ── Reads ──────────────────────────────────────────────────────────
76
+
77
+ def get(
78
+ self,
79
+ conn: sqlite3.Connection,
80
+ symbol: str,
81
+ exchange: Exchange,
82
+ ) -> SymbolEntry | None:
83
+ row = conn.execute(
84
+ "SELECT symbol, exchange, name, isin, lot_size, delisted_at, "
85
+ "tick_size, daily_band_pct "
86
+ "FROM symbols WHERE symbol = ? AND exchange = ?",
87
+ (symbol, exchange.value),
88
+ ).fetchone()
89
+ if row is None:
90
+ return None
91
+ return SymbolEntry(
92
+ symbol=row["symbol"],
93
+ exchange=Exchange(row["exchange"]),
94
+ name=row["name"],
95
+ isin=row["isin"],
96
+ lot_size=row["lot_size"],
97
+ delisted_at=(
98
+ datetime.fromisoformat(row["delisted_at"])
99
+ if row["delisted_at"] else None
100
+ ),
101
+ tick_size=row["tick_size"],
102
+ daily_band_pct=row["daily_band_pct"],
103
+ )
104
+
105
+ def list_all(
106
+ self,
107
+ conn: sqlite3.Connection,
108
+ include_delisted: bool = False,
109
+ ) -> list[SymbolEntry]:
110
+ if include_delisted:
111
+ rows = conn.execute(
112
+ "SELECT symbol, exchange, name, isin, lot_size, delisted_at, "
113
+ "tick_size, daily_band_pct "
114
+ "FROM symbols ORDER BY exchange, symbol"
115
+ ).fetchall()
116
+ else:
117
+ rows = conn.execute(
118
+ "SELECT symbol, exchange, name, isin, lot_size, delisted_at, "
119
+ "tick_size, daily_band_pct "
120
+ "FROM symbols WHERE delisted_at IS NULL "
121
+ "ORDER BY exchange, symbol"
122
+ ).fetchall()
123
+ return [
124
+ SymbolEntry(
125
+ symbol=r["symbol"],
126
+ exchange=Exchange(r["exchange"]),
127
+ name=r["name"],
128
+ isin=r["isin"],
129
+ lot_size=r["lot_size"],
130
+ delisted_at=(
131
+ datetime.fromisoformat(r["delisted_at"])
132
+ if r["delisted_at"] else None
133
+ ),
134
+ tick_size=r["tick_size"],
135
+ daily_band_pct=r["daily_band_pct"],
136
+ )
137
+ for r in rows
138
+ ]
139
+
140
+ # ── Writes ─────────────────────────────────────────────────────────
141
+
142
+ def upsert(
143
+ self,
144
+ conn: sqlite3.Connection,
145
+ symbol: str,
146
+ exchange: Exchange,
147
+ name: str | None = None,
148
+ isin: str | None = None,
149
+ lot_size: int = 1,
150
+ tick_size: float | None = None,
151
+ daily_band_pct: float | None = None,
152
+ ) -> None:
153
+ """Insert or update a symbol. Clears any delisted_at flag.
154
+
155
+ ``tick_size`` and ``daily_band_pct`` may be ``None`` — that's
156
+ the signal to fall back to the broker's
157
+ :class:`MicrostructureConfig` defaults at validate time.
158
+ """
159
+ now = datetime.now(IST).isoformat()
160
+ conn.execute(
161
+ "INSERT INTO symbols (symbol, exchange, name, isin, "
162
+ "lot_size, delisted_at, added_at, tick_size, daily_band_pct) "
163
+ "VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?) "
164
+ "ON CONFLICT(symbol, exchange) DO UPDATE SET "
165
+ "name = excluded.name, isin = excluded.isin, "
166
+ "lot_size = excluded.lot_size, delisted_at = NULL, "
167
+ "tick_size = excluded.tick_size, "
168
+ "daily_band_pct = excluded.daily_band_pct",
169
+ (
170
+ symbol, exchange.value, name, isin, lot_size, now,
171
+ tick_size, daily_band_pct,
172
+ ),
173
+ )
174
+
175
+ def delist(
176
+ self,
177
+ conn: sqlite3.Connection,
178
+ symbol: str,
179
+ exchange: Exchange,
180
+ when: datetime | None = None,
181
+ ) -> bool:
182
+ """Mark a symbol delisted. Returns True if a row was updated."""
183
+ ts = (when or datetime.now(IST)).isoformat()
184
+ cur = conn.execute(
185
+ "UPDATE symbols SET delisted_at = ? "
186
+ "WHERE symbol = ? AND exchange = ? AND delisted_at IS NULL",
187
+ (ts, symbol, exchange.value),
188
+ )
189
+ return cur.rowcount > 0
190
+
191
+ def relist(
192
+ self,
193
+ conn: sqlite3.Connection,
194
+ symbol: str,
195
+ exchange: Exchange,
196
+ ) -> bool:
197
+ """Clear the delisted flag. Returns True if a row was updated."""
198
+ cur = conn.execute(
199
+ "UPDATE symbols SET delisted_at = NULL "
200
+ "WHERE symbol = ? AND exchange = ? AND delisted_at IS NOT NULL",
201
+ (symbol, exchange.value),
202
+ )
203
+ return cur.rowcount > 0
204
+
205
+ def load_csv(
206
+ self,
207
+ conn: sqlite3.Connection,
208
+ csv_path: Path,
209
+ exchange: Exchange,
210
+ ) -> int:
211
+ """Bulk-upsert from a CSV with columns:
212
+ ``symbol[, name, isin, lot_size, tick_size, daily_band_pct]``.
213
+
214
+ Returns the count of rows upserted. Missing columns fall back
215
+ to defaults (lot=1, tick/band=NULL → broker config).
216
+ """
217
+ n = 0
218
+ with open(csv_path, newline="") as f:
219
+ reader = csv.DictReader(f)
220
+ if reader.fieldnames is None or "symbol" not in reader.fieldnames:
221
+ raise ValueError(
222
+ f"CSV must have a 'symbol' column. Got: {reader.fieldnames}"
223
+ )
224
+ for row in reader:
225
+ sym = (row.get("symbol") or "").strip().upper()
226
+ if not sym:
227
+ continue
228
+ self.upsert(
229
+ conn,
230
+ symbol=sym,
231
+ exchange=exchange,
232
+ name=(row.get("name") or "").strip() or None,
233
+ isin=(row.get("isin") or "").strip() or None,
234
+ lot_size=int(row.get("lot_size") or 1),
235
+ tick_size=_parse_optional_float(row.get("tick_size")),
236
+ daily_band_pct=_parse_optional_float(
237
+ row.get("daily_band_pct"),
238
+ ),
239
+ )
240
+ n += 1
241
+ return n
242
+
243
+ # ── Validation hook used by the broker ─────────────────────────────
244
+
245
+ def validate(
246
+ self,
247
+ conn: sqlite3.Connection,
248
+ symbol: str,
249
+ exchange: Exchange,
250
+ ) -> None:
251
+ """Raise ``SymbolDelisted`` (always) or ``SymbolNotFound`` (strict)
252
+ when a symbol can't be traded; return silently otherwise.
253
+ """
254
+ entry = self.get(conn, symbol, exchange)
255
+ if entry is None:
256
+ if self.strict:
257
+ raise SymbolNotFound(
258
+ f"Symbol {symbol!r} on {exchange.value} not in master "
259
+ f"(strict mode). Add via SymbolMaster.upsert."
260
+ )
261
+ return
262
+ if entry.delisted_at is not None:
263
+ raise SymbolDelisted(
264
+ f"Symbol {symbol!r} on {exchange.value} was delisted at "
265
+ f"{entry.delisted_at.isoformat()}"
266
+ )
267
+
268
+
269
+ def _parse_optional_float(s: str | None) -> float | None:
270
+ """Parse an optional float column from a CSV row; treat blanks as None."""
271
+ if s is None:
272
+ return None
273
+ s = s.strip()
274
+ if not s:
275
+ return None
276
+ try:
277
+ return float(s)
278
+ except ValueError:
279
+ return None
@@ -0,0 +1,78 @@
1
+ """SQLite-backed watchlist store.
2
+
3
+ A small, ordered favorites list for the UI, persisted in the broker's
4
+ own SQLite database (table ``watchlist``, migration 004) rather than a
5
+ loose JSON file — so it's atomic, concurrency-safe (via the shared
6
+ connection's ``busy_timeout``), and lives in the one datastore that the
7
+ Docker volume already persists.
8
+
9
+ Global, not per-account: it's a display convenience, matching the
10
+ single-user design.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from datetime import datetime
16
+
17
+ from .persistence import Persistence
18
+
19
+
20
+ class WatchlistStore:
21
+ """CRUD for the ordered symbol watchlist."""
22
+
23
+ def __init__(self, persistence: Persistence) -> None:
24
+ self._db = persistence
25
+
26
+ def list_symbols(self) -> list[str]:
27
+ """Return symbols in user order."""
28
+ with self._db.read() as conn:
29
+ rows = conn.execute(
30
+ "SELECT symbol FROM watchlist ORDER BY position, symbol"
31
+ ).fetchall()
32
+ return [r["symbol"] for r in rows]
33
+
34
+ def set_symbols(self, symbols: list[str]) -> list[str]:
35
+ """Replace the entire watchlist with ``symbols`` (order preserved).
36
+
37
+ Symbols are upper-cased and de-duplicated. Returns the cleaned
38
+ list that was stored.
39
+ """
40
+ clean: list[str] = []
41
+ for s in symbols:
42
+ s = str(s).strip().upper()
43
+ if s and s not in clean:
44
+ clean.append(s)
45
+ now = datetime.now().isoformat()
46
+ with self._db.transaction() as conn:
47
+ conn.execute("DELETE FROM watchlist")
48
+ conn.executemany(
49
+ "INSERT INTO watchlist (symbol, position, added_at) "
50
+ "VALUES (?, ?, ?)",
51
+ [(sym, i, now) for i, sym in enumerate(clean)],
52
+ )
53
+ return clean
54
+
55
+ def add(self, symbol: str) -> None:
56
+ """Append one symbol (no-op if already present)."""
57
+ sym = symbol.strip().upper()
58
+ if not sym:
59
+ return
60
+ now = datetime.now().isoformat()
61
+ with self._db.transaction() as conn:
62
+ row = conn.execute(
63
+ "SELECT COALESCE(MAX(position), -1) AS m FROM watchlist"
64
+ ).fetchone()
65
+ conn.execute(
66
+ "INSERT OR IGNORE INTO watchlist (symbol, position, added_at) "
67
+ "VALUES (?, ?, ?)",
68
+ (sym, int(row["m"]) + 1, now),
69
+ )
70
+
71
+ def remove(self, symbol: str) -> None:
72
+ with self._db.transaction() as conn:
73
+ conn.execute(
74
+ "DELETE FROM watchlist WHERE symbol = ?", (symbol.strip().upper(),)
75
+ )
76
+
77
+
78
+ __all__ = ["WatchlistStore"]