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.
- papertrade_india/__init__.py +250 -0
- papertrade_india/_context.py +144 -0
- papertrade_india/broker.py +546 -0
- papertrade_india/cli.py +474 -0
- papertrade_india/clock.py +29 -0
- papertrade_india/corporate_actions/__init__.py +10 -0
- papertrade_india/corporate_actions/bonus.py +105 -0
- papertrade_india/corporate_actions/dividends.py +99 -0
- papertrade_india/corporate_actions/rights.py +189 -0
- papertrade_india/corporate_actions/splits.py +111 -0
- papertrade_india/corporate_actions/store.py +247 -0
- papertrade_india/data/nse_holidays_2026.json +22 -0
- papertrade_india/data/nse_holidays_2027.json +9 -0
- papertrade_india/data/nse_universe_sample.csv +31 -0
- papertrade_india/domain/__init__.py +6 -0
- papertrade_india/domain/exceptions.py +183 -0
- papertrade_india/domain/models.py +213 -0
- papertrade_india/domain/rules/__init__.py +5 -0
- papertrade_india/domain/rules/risk.py +165 -0
- papertrade_india/domain/rules/tick_lot_band.py +139 -0
- papertrade_india/events.py +29 -0
- papertrade_india/exceptions.py +29 -0
- papertrade_india/execution/__init__.py +5 -0
- papertrade_india/execution/book.py +385 -0
- papertrade_india/execution/fees.py +213 -0
- papertrade_india/execution/settlement.py +360 -0
- papertrade_india/execution/simulation.py +176 -0
- papertrade_india/execution/slippage.py +120 -0
- papertrade_india/fees.py +29 -0
- papertrade_india/idempotency.py +29 -0
- papertrade_india/infrastructure/__init__.py +6 -0
- papertrade_india/infrastructure/clock.py +123 -0
- papertrade_india/infrastructure/events.py +137 -0
- papertrade_india/infrastructure/holidays.py +138 -0
- papertrade_india/infrastructure/idempotency.py +133 -0
- papertrade_india/infrastructure/ledger.py +141 -0
- papertrade_india/infrastructure/market_hours.py +200 -0
- papertrade_india/infrastructure/migrations.py +622 -0
- papertrade_india/infrastructure/observability.py +195 -0
- papertrade_india/infrastructure/persistence.py +130 -0
- papertrade_india/infrastructure/symbols.py +279 -0
- papertrade_india/infrastructure/watchlist.py +78 -0
- papertrade_india/interface.py +92 -0
- papertrade_india/ledger.py +29 -0
- papertrade_india/limit_orders.py +29 -0
- papertrade_india/market_hours.py +29 -0
- papertrade_india/microstructure.py +57 -0
- papertrade_india/migrations.py +29 -0
- papertrade_india/models.py +29 -0
- papertrade_india/observability.py +29 -0
- papertrade_india/orders/__init__.py +5 -0
- papertrade_india/orders/amo.py +98 -0
- papertrade_india/orders/book_helpers.py +111 -0
- papertrade_india/orders/bracket.py +115 -0
- papertrade_india/orders/limit.py +210 -0
- papertrade_india/orders/market.py +264 -0
- papertrade_india/orders/partial_fills.py +92 -0
- papertrade_india/orders/preopen.py +274 -0
- papertrade_india/orders/state.py +640 -0
- papertrade_india/orders/stop.py +122 -0
- papertrade_india/orders/submit.py +385 -0
- papertrade_india/partial_fills.py +29 -0
- papertrade_india/persistence.py +29 -0
- papertrade_india/preopen.py +29 -0
- papertrade_india/presets.py +120 -0
- papertrade_india/price_feed.py +316 -0
- papertrade_india/providers/__init__.py +123 -0
- papertrade_india/providers/alphavantage.py +180 -0
- papertrade_india/providers/base.py +256 -0
- papertrade_india/providers/cache.py +147 -0
- papertrade_india/providers/composite.py +244 -0
- papertrade_india/providers/dhan.py +266 -0
- papertrade_india/providers/finnhub.py +122 -0
- papertrade_india/providers/health.py +233 -0
- papertrade_india/providers/jugaad.py +142 -0
- papertrade_india/providers/kite.py +222 -0
- papertrade_india/providers/nse_bhavcopy.py +210 -0
- papertrade_india/providers/nsepython.py +98 -0
- papertrade_india/providers/registry.py +226 -0
- papertrade_india/providers/stooq.py +173 -0
- papertrade_india/providers/twelvedata.py +198 -0
- papertrade_india/providers/upstox.py +318 -0
- papertrade_india/providers/upstox_instruments.py +171 -0
- papertrade_india/providers/yfinance.py +205 -0
- papertrade_india/quickstart.py +111 -0
- papertrade_india/reads/__init__.py +6 -0
- papertrade_india/reads/account.py +140 -0
- papertrade_india/reads/orders.py +54 -0
- papertrade_india/reads/positions.py +188 -0
- papertrade_india/risk.py +29 -0
- papertrade_india/settlement.py +29 -0
- papertrade_india/simulation.py +29 -0
- papertrade_india/slippage.py +29 -0
- papertrade_india/symbols.py +29 -0
- papertrade_india/workers/__init__.py +6 -0
- papertrade_india/workers/limit_orders.py +390 -0
- papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
- papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
- papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
- papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
"""Schema migrations.
|
|
2
|
+
|
|
3
|
+
Why this module exists
|
|
4
|
+
----------------------
|
|
5
|
+
Pre-1.0, the package's first persistence layer ran ``executescript(SCHEMA)``
|
|
6
|
+
with ``CREATE TABLE IF NOT EXISTS`` on every connect. That's fine for
|
|
7
|
+
brand-new DBs but breaks the moment the schema *changes*: a 0.1.0 user
|
|
8
|
+
who upgrades to 0.2.0 won't get the new columns or indexes, because
|
|
9
|
+
``IF NOT EXISTS`` is a no-op when the table already exists. Versioned
|
|
10
|
+
migrations fix this.
|
|
11
|
+
|
|
12
|
+
Design
|
|
13
|
+
------
|
|
14
|
+
- Each migration is a function decorated with ``@migration(N)``. ``N`` is
|
|
15
|
+
a positive integer; migrations apply in numeric order.
|
|
16
|
+
- A single ``schema_version`` table tracks the highest applied version.
|
|
17
|
+
Brand-new DBs see no table; we create it and start from version 0.
|
|
18
|
+
- ``run_migrations(conn)`` applies all migrations strictly greater than
|
|
19
|
+
the recorded version, in a transaction per migration.
|
|
20
|
+
- A migration that raises rolls back its own transaction; the package
|
|
21
|
+
refuses to continue at a half-applied version.
|
|
22
|
+
- Forward-only: there is no downgrade path. Reverting deployments rarely
|
|
23
|
+
needs DB rollback in practice, and offering it is a footgun.
|
|
24
|
+
|
|
25
|
+
Detecting legacy DBs (pre-versioning)
|
|
26
|
+
-------------------------------------
|
|
27
|
+
A 0.1.x DB has all the v1 tables (``account``, ``positions``, ``orders``,
|
|
28
|
+
etc.) but no ``schema_version`` row. We detect this and stamp it as
|
|
29
|
+
version 1 without re-running migration 001 — its DDL is ``IF NOT EXISTS``
|
|
30
|
+
so re-running would be safe, but the stamp is faster and tells future
|
|
31
|
+
maintainers what shape the DB started from.
|
|
32
|
+
|
|
33
|
+
Adding a new migration
|
|
34
|
+
----------------------
|
|
35
|
+
1. Add a ``@migration(N+1)`` function below the latest one.
|
|
36
|
+
2. Use ``ALTER TABLE`` / ``CREATE INDEX`` / DML, not ``CREATE TABLE``.
|
|
37
|
+
3. Add a test in ``tests/integration/test_migrations.py`` that
|
|
38
|
+
synthesizes a v(N) DB and verifies the upgrade.
|
|
39
|
+
4. Update ``CHANGELOG.md`` with the migration's purpose.
|
|
40
|
+
|
|
41
|
+
The runner can be invoked from the CLI: ``papertrade-india migrate``.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
import logging
|
|
47
|
+
import sqlite3
|
|
48
|
+
from collections.abc import Callable
|
|
49
|
+
from typing import TypeVar
|
|
50
|
+
|
|
51
|
+
logger = logging.getLogger(__name__)
|
|
52
|
+
|
|
53
|
+
# Registry: version → migration function. Populated by the @migration decorator.
|
|
54
|
+
MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
F = TypeVar("F", bound=Callable[[sqlite3.Connection], None])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def migration(version: int) -> Callable[[F], F]:
|
|
61
|
+
"""Register ``fn`` as the migration for ``version``.
|
|
62
|
+
|
|
63
|
+
Versions are positive integers; gaps are not allowed (1, 2, 3, …).
|
|
64
|
+
Re-registering an existing version raises ``ValueError`` immediately
|
|
65
|
+
— duplicate migration numbers in two PRs would silently overwrite,
|
|
66
|
+
which is exactly the kind of bug versioning exists to catch.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def decorator(fn: F) -> F:
|
|
70
|
+
if version <= 0:
|
|
71
|
+
raise ValueError(f"migration version must be positive, got {version}")
|
|
72
|
+
if version in MIGRATIONS:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
f"migration {version} is already registered "
|
|
75
|
+
f"(by {MIGRATIONS[version].__qualname__})"
|
|
76
|
+
)
|
|
77
|
+
MIGRATIONS[version] = fn
|
|
78
|
+
return fn
|
|
79
|
+
|
|
80
|
+
return decorator
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ── Migration 001: initial schema ──────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@migration(1)
|
|
87
|
+
def _v1_initial_schema(conn: sqlite3.Connection) -> None:
|
|
88
|
+
"""The package's day-one schema: account, positions, orders, trades,
|
|
89
|
+
cash_movements, events, idempotency_keys, symbols, corporate_actions.
|
|
90
|
+
|
|
91
|
+
Brand-new DBs run this in full. Legacy 0.1.x DBs already have these
|
|
92
|
+
tables (the legacy detector stamps them at v1 without re-running),
|
|
93
|
+
but the DDL is ``IF NOT EXISTS`` everywhere so re-running would be
|
|
94
|
+
safe.
|
|
95
|
+
|
|
96
|
+
We execute statements one at a time rather than ``executescript``
|
|
97
|
+
because executescript silently issues COMMIT, which fights with
|
|
98
|
+
our own transaction wrapping in ``run_migrations``.
|
|
99
|
+
"""
|
|
100
|
+
for stmt in _split_statements(_INITIAL_SCHEMA_SQL):
|
|
101
|
+
conn.execute(stmt)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# ── Migration 002: microstructure + settlement + new order columns ──
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@migration(2)
|
|
108
|
+
def _v2_realism_extensions(conn: sqlite3.Connection) -> None:
|
|
109
|
+
"""Add the columns and tables needed for tick/lot/band rules,
|
|
110
|
+
T+1 settlement, and the new order types (STOP, BRACKET, INTRADAY).
|
|
111
|
+
|
|
112
|
+
Strategy
|
|
113
|
+
--------
|
|
114
|
+
Every change is additive at the data level — no rows lose meaning:
|
|
115
|
+
|
|
116
|
+
- ``symbols.tick_size`` / ``daily_band_pct``: NULL means "use
|
|
117
|
+
MicrostructureConfig defaults". Existing rows stay valid.
|
|
118
|
+
- ``orders``: rebuilt to widen the ``order_type`` CHECK and add
|
|
119
|
+
``stop_price`` / ``target_price`` / ``parent_order_id`` /
|
|
120
|
+
``triggered_at`` / ``product_type``. Rebuild is necessary because
|
|
121
|
+
SQLite can't ``ALTER TABLE ... DROP/REPLACE CONSTRAINT``. We use
|
|
122
|
+
the canonical 12-step rebuild: create new, copy, drop, rename.
|
|
123
|
+
- ``pending_settlements``: brand-new table, empty initially.
|
|
124
|
+
|
|
125
|
+
Rebuild safety
|
|
126
|
+
--------------
|
|
127
|
+
Foreign keys are deferred during the rebuild via
|
|
128
|
+
``PRAGMA defer_foreign_keys=1`` so the in-flight rename doesn't
|
|
129
|
+
blow up cross-table FK references (``trades.order_id``,
|
|
130
|
+
``cash_movements.order_id``, etc.). FK enforcement is restored at
|
|
131
|
+
the end. The whole thing runs inside the migration transaction so
|
|
132
|
+
a crash mid-rebuild rolls back cleanly.
|
|
133
|
+
"""
|
|
134
|
+
# --- symbols: tick + band (additive) -------------------------------------
|
|
135
|
+
conn.execute("ALTER TABLE symbols ADD COLUMN tick_size REAL")
|
|
136
|
+
conn.execute("ALTER TABLE symbols ADD COLUMN daily_band_pct REAL")
|
|
137
|
+
|
|
138
|
+
# --- orders: rebuild with widened CHECK + new columns -------------------
|
|
139
|
+
conn.execute("PRAGMA defer_foreign_keys=ON")
|
|
140
|
+
|
|
141
|
+
conn.execute(
|
|
142
|
+
"""
|
|
143
|
+
CREATE TABLE orders_new (
|
|
144
|
+
id TEXT PRIMARY KEY,
|
|
145
|
+
account_id TEXT NOT NULL,
|
|
146
|
+
symbol TEXT NOT NULL,
|
|
147
|
+
exchange TEXT NOT NULL,
|
|
148
|
+
side TEXT NOT NULL CHECK(side IN ('buy','sell')),
|
|
149
|
+
qty REAL NOT NULL CHECK(qty > 0),
|
|
150
|
+
order_type TEXT NOT NULL CHECK(order_type IN (
|
|
151
|
+
'market','limit','stop_market','stop_limit','bracket'
|
|
152
|
+
)),
|
|
153
|
+
status TEXT NOT NULL CHECK(status IN (
|
|
154
|
+
'pending','filled','partially_filled',
|
|
155
|
+
'cancelled','rejected','expired'
|
|
156
|
+
)),
|
|
157
|
+
filled_qty REAL NOT NULL DEFAULT 0,
|
|
158
|
+
filled_avg_price REAL,
|
|
159
|
+
limit_price REAL,
|
|
160
|
+
fees_paid REAL NOT NULL DEFAULT 0,
|
|
161
|
+
realized_pl REAL NOT NULL DEFAULT 0,
|
|
162
|
+
time_in_force TEXT NOT NULL DEFAULT 'DAY',
|
|
163
|
+
created_at TEXT NOT NULL,
|
|
164
|
+
filled_at TEXT,
|
|
165
|
+
cancelled_at TEXT,
|
|
166
|
+
expired_at TEXT,
|
|
167
|
+
rejection_reason TEXT,
|
|
168
|
+
stop_price REAL,
|
|
169
|
+
target_price REAL,
|
|
170
|
+
parent_order_id TEXT,
|
|
171
|
+
triggered_at TEXT,
|
|
172
|
+
product_type TEXT NOT NULL DEFAULT 'delivery'
|
|
173
|
+
CHECK(product_type IN ('delivery','intraday')),
|
|
174
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id)
|
|
175
|
+
ON DELETE CASCADE
|
|
176
|
+
)
|
|
177
|
+
""",
|
|
178
|
+
)
|
|
179
|
+
conn.execute(
|
|
180
|
+
"""
|
|
181
|
+
INSERT INTO orders_new (
|
|
182
|
+
id, account_id, symbol, exchange, side, qty, order_type, status,
|
|
183
|
+
filled_qty, filled_avg_price, limit_price, fees_paid, realized_pl,
|
|
184
|
+
time_in_force, created_at, filled_at, cancelled_at, expired_at,
|
|
185
|
+
rejection_reason
|
|
186
|
+
)
|
|
187
|
+
SELECT
|
|
188
|
+
id, account_id, symbol, exchange, side, qty, order_type, status,
|
|
189
|
+
filled_qty, filled_avg_price, limit_price, fees_paid, realized_pl,
|
|
190
|
+
time_in_force, created_at, filled_at, cancelled_at, expired_at,
|
|
191
|
+
rejection_reason
|
|
192
|
+
FROM orders
|
|
193
|
+
""",
|
|
194
|
+
)
|
|
195
|
+
conn.execute("DROP TABLE orders")
|
|
196
|
+
conn.execute("ALTER TABLE orders_new RENAME TO orders")
|
|
197
|
+
|
|
198
|
+
# Recreate the v1 indexes (rebuild dropped them with the table).
|
|
199
|
+
conn.execute(
|
|
200
|
+
"CREATE INDEX IF NOT EXISTS idx_orders_account_status "
|
|
201
|
+
"ON orders(account_id, status)",
|
|
202
|
+
)
|
|
203
|
+
conn.execute(
|
|
204
|
+
"CREATE INDEX IF NOT EXISTS idx_orders_account_created "
|
|
205
|
+
"ON orders(account_id, created_at DESC)",
|
|
206
|
+
)
|
|
207
|
+
conn.execute(
|
|
208
|
+
"CREATE INDEX IF NOT EXISTS idx_orders_parent "
|
|
209
|
+
"ON orders(parent_order_id)",
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
# --- pending settlements (new table) -------------------------------------
|
|
213
|
+
for stmt in _split_statements(_SETTLEMENT_SCHEMA_SQL):
|
|
214
|
+
conn.execute(stmt)
|
|
215
|
+
|
|
216
|
+
# FK enforcement restored automatically at COMMIT.
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# ── Migration 003: bonus / rights as first-class corporate-action types ──
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@migration(3)
|
|
223
|
+
def _v3_bonus_and_rights(conn: sqlite3.Connection) -> None:
|
|
224
|
+
"""Widen ``corporate_actions.action_type`` to include 'bonus' and
|
|
225
|
+
'rights' (and 'merger', 'spinoff' for forward compat).
|
|
226
|
+
|
|
227
|
+
Why a rebuild rather than ALTER + new check
|
|
228
|
+
-------------------------------------------
|
|
229
|
+
SQLite can't drop or relax a CHECK constraint on an existing column
|
|
230
|
+
via ALTER. We rebuild the table with the wider domain and copy the
|
|
231
|
+
data, same as v2 did for ``orders``.
|
|
232
|
+
|
|
233
|
+
Existing rows with ``action_type='split'`` or ``'dividend'`` keep
|
|
234
|
+
their meaning. Bonus issues that were previously routed through
|
|
235
|
+
``apply_split`` are *not* retroactively reclassified — that would
|
|
236
|
+
rewrite history. Going forward, callers should use
|
|
237
|
+
:meth:`IndiaPaperBroker.apply_bonus` and
|
|
238
|
+
:meth:`IndiaPaperBroker.apply_rights` to record the proper type.
|
|
239
|
+
"""
|
|
240
|
+
conn.execute("PRAGMA defer_foreign_keys=ON")
|
|
241
|
+
conn.execute(
|
|
242
|
+
"""
|
|
243
|
+
CREATE TABLE corporate_actions_new (
|
|
244
|
+
id TEXT PRIMARY KEY,
|
|
245
|
+
symbol TEXT NOT NULL,
|
|
246
|
+
exchange TEXT NOT NULL,
|
|
247
|
+
action_type TEXT NOT NULL CHECK(action_type IN (
|
|
248
|
+
'split', 'dividend', 'bonus', 'rights', 'merger', 'spinoff'
|
|
249
|
+
)),
|
|
250
|
+
ratio_num INTEGER,
|
|
251
|
+
ratio_den INTEGER,
|
|
252
|
+
amount_per_share REAL,
|
|
253
|
+
ex_date TEXT NOT NULL,
|
|
254
|
+
notes TEXT,
|
|
255
|
+
applied_at TEXT NOT NULL
|
|
256
|
+
)
|
|
257
|
+
""",
|
|
258
|
+
)
|
|
259
|
+
conn.execute(
|
|
260
|
+
"""
|
|
261
|
+
INSERT INTO corporate_actions_new
|
|
262
|
+
SELECT id, symbol, exchange, action_type, ratio_num, ratio_den,
|
|
263
|
+
amount_per_share, ex_date, notes, applied_at
|
|
264
|
+
FROM corporate_actions
|
|
265
|
+
""",
|
|
266
|
+
)
|
|
267
|
+
conn.execute("DROP TABLE corporate_actions")
|
|
268
|
+
conn.execute("ALTER TABLE corporate_actions_new RENAME TO corporate_actions")
|
|
269
|
+
conn.execute(
|
|
270
|
+
"CREATE INDEX IF NOT EXISTS idx_corporate_actions_symbol_date "
|
|
271
|
+
"ON corporate_actions(symbol, ex_date)",
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# ── Migration 004: UI watchlist ────────────────────────────────────────
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@migration(4)
|
|
279
|
+
def _v4_watchlist(conn: sqlite3.Connection) -> None:
|
|
280
|
+
"""A simple, ordered favorites list for the UI.
|
|
281
|
+
|
|
282
|
+
Global (not per-account) — it's a display convenience, not trading
|
|
283
|
+
state, matching the tool's single-user design. ``position`` keeps the
|
|
284
|
+
user's ordering; ``symbol`` is the primary key so re-adding is a
|
|
285
|
+
no-op/upsert.
|
|
286
|
+
"""
|
|
287
|
+
conn.execute(
|
|
288
|
+
"""
|
|
289
|
+
CREATE TABLE IF NOT EXISTS watchlist (
|
|
290
|
+
symbol TEXT PRIMARY KEY,
|
|
291
|
+
position INTEGER NOT NULL DEFAULT 0,
|
|
292
|
+
added_at TEXT NOT NULL
|
|
293
|
+
)
|
|
294
|
+
""",
|
|
295
|
+
)
|
|
296
|
+
conn.execute(
|
|
297
|
+
"CREATE INDEX IF NOT EXISTS idx_watchlist_position "
|
|
298
|
+
"ON watchlist(position)",
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# ── Public API ─────────────────────────────────────────────────────────
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def current_version() -> int:
|
|
306
|
+
"""The highest registered migration number. Brand-new DBs target this."""
|
|
307
|
+
return max(MIGRATIONS) if MIGRATIONS else 0
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def applied_version(conn: sqlite3.Connection) -> int:
|
|
311
|
+
"""The highest migration recorded in ``schema_version``.
|
|
312
|
+
|
|
313
|
+
Returns 0 if the table doesn't exist (or is empty).
|
|
314
|
+
"""
|
|
315
|
+
try:
|
|
316
|
+
row = conn.execute(
|
|
317
|
+
"SELECT COALESCE(MAX(version), 0) AS v FROM schema_version"
|
|
318
|
+
).fetchone()
|
|
319
|
+
except sqlite3.OperationalError:
|
|
320
|
+
# Table doesn't exist — pre-versioning DB.
|
|
321
|
+
return 0
|
|
322
|
+
return int(row["v"]) if row else 0
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def run_migrations(conn: sqlite3.Connection) -> list[int]:
|
|
326
|
+
"""Apply all pending migrations to ``conn``.
|
|
327
|
+
|
|
328
|
+
Returns the list of versions that were applied (empty if up-to-date).
|
|
329
|
+
Raises ``RuntimeError`` if the DB reports a version higher than the
|
|
330
|
+
package knows about — that means a newer client wrote to it and an
|
|
331
|
+
older one is reading. Refusing to operate is safer than corrupting
|
|
332
|
+
the data.
|
|
333
|
+
"""
|
|
334
|
+
_ensure_version_table(conn)
|
|
335
|
+
|
|
336
|
+
# Legacy detection: tables exist but no version row. Stamp at v1.
|
|
337
|
+
# If the legacy DB happens to be missing tables that v1 introduced
|
|
338
|
+
# (truly old fragments, or the ``_synthesize_legacy_v1`` test
|
|
339
|
+
# fixture which only seeds the detector keys), run v1's idempotent
|
|
340
|
+
# body to fill the gaps before stamping. v1's DDL is all
|
|
341
|
+
# ``CREATE TABLE IF NOT EXISTS``, so re-running is safe.
|
|
342
|
+
if applied_version(conn) == 0 and _looks_like_legacy_v1(conn):
|
|
343
|
+
logger.info(
|
|
344
|
+
"Detected legacy v0.1.x database (tables present, no schema_version "
|
|
345
|
+
"row). Backfilling missing v1 tables and stamping as schema_version=1.",
|
|
346
|
+
)
|
|
347
|
+
for stmt in _split_statements(_INITIAL_SCHEMA_SQL):
|
|
348
|
+
conn.execute(stmt)
|
|
349
|
+
_stamp_version(conn, 1)
|
|
350
|
+
|
|
351
|
+
applied = applied_version(conn)
|
|
352
|
+
target = current_version()
|
|
353
|
+
|
|
354
|
+
if applied > target:
|
|
355
|
+
raise RuntimeError(
|
|
356
|
+
f"Database is at schema version {applied} but this client only "
|
|
357
|
+
f"knows up to version {target}. Refusing to operate — "
|
|
358
|
+
f"upgrade the papertrade-india package."
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
pending = sorted(v for v in MIGRATIONS if v > applied)
|
|
362
|
+
if not pending:
|
|
363
|
+
return []
|
|
364
|
+
|
|
365
|
+
for v in pending:
|
|
366
|
+
logger.info("Applying migration %d → %s", v, MIGRATIONS[v].__qualname__)
|
|
367
|
+
# Each migration runs in its own IMMEDIATE transaction so a
|
|
368
|
+
# failure leaves the previous state intact.
|
|
369
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
370
|
+
try:
|
|
371
|
+
MIGRATIONS[v](conn)
|
|
372
|
+
_stamp_version(conn, v)
|
|
373
|
+
except Exception:
|
|
374
|
+
conn.execute("ROLLBACK")
|
|
375
|
+
raise
|
|
376
|
+
conn.execute("COMMIT")
|
|
377
|
+
|
|
378
|
+
return pending
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
# ── Internals ──────────────────────────────────────────────────────────
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _ensure_version_table(conn: sqlite3.Connection) -> None:
|
|
385
|
+
conn.execute("""
|
|
386
|
+
CREATE TABLE IF NOT EXISTS schema_version (
|
|
387
|
+
version INTEGER PRIMARY KEY,
|
|
388
|
+
applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
389
|
+
)
|
|
390
|
+
""")
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _split_statements(sql: str) -> list[str]:
|
|
394
|
+
"""Split a multi-statement SQL string into individual statements.
|
|
395
|
+
|
|
396
|
+
SQLite's ``executescript`` runs them but auto-commits, which we
|
|
397
|
+
can't tolerate inside our own transaction wrapping. ``execute``
|
|
398
|
+
only accepts one statement at a time, so we split on ``;`` and
|
|
399
|
+
skip blanks/comments.
|
|
400
|
+
|
|
401
|
+
We deliberately don't try to handle SQL strings that contain
|
|
402
|
+
semicolons inside string literals — none of our DDL has that.
|
|
403
|
+
"""
|
|
404
|
+
out: list[str] = []
|
|
405
|
+
for raw in sql.split(";"):
|
|
406
|
+
s = raw.strip()
|
|
407
|
+
if not s:
|
|
408
|
+
continue
|
|
409
|
+
# Drop SQL line comments. We never embed them inside multi-line
|
|
410
|
+
# statements, so this is safe.
|
|
411
|
+
cleaned = "\n".join(
|
|
412
|
+
line for line in s.splitlines()
|
|
413
|
+
if not line.lstrip().startswith("--")
|
|
414
|
+
).strip()
|
|
415
|
+
if cleaned:
|
|
416
|
+
out.append(cleaned)
|
|
417
|
+
return out
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _stamp_version(conn: sqlite3.Connection, version: int) -> None:
|
|
421
|
+
conn.execute(
|
|
422
|
+
"INSERT OR IGNORE INTO schema_version (version) VALUES (?)",
|
|
423
|
+
(version,),
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _looks_like_legacy_v1(conn: sqlite3.Connection) -> bool:
|
|
428
|
+
"""Return True if the DB has v1's tables but no recorded version.
|
|
429
|
+
|
|
430
|
+
Heuristic: the presence of ``account`` and ``positions`` is enough.
|
|
431
|
+
A pristine new DB has neither; a v1 DB has both. This avoids
|
|
432
|
+
false-positive stamps on totally empty files.
|
|
433
|
+
"""
|
|
434
|
+
rows = conn.execute(
|
|
435
|
+
"SELECT name FROM sqlite_master "
|
|
436
|
+
"WHERE type='table' AND name IN ('account', 'positions')"
|
|
437
|
+
).fetchall()
|
|
438
|
+
return len(rows) == 2
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
# ── v1 schema body ─────────────────────────────────────────────────────
|
|
442
|
+
#
|
|
443
|
+
# Kept in one big string so future-archaeologists can read the day-one
|
|
444
|
+
# schema in one place. Subsequent migrations should NOT modify this
|
|
445
|
+
# string — they should be ALTER statements in their own functions.
|
|
446
|
+
|
|
447
|
+
_INITIAL_SCHEMA_SQL = """
|
|
448
|
+
CREATE TABLE IF NOT EXISTS account (
|
|
449
|
+
account_id TEXT PRIMARY KEY,
|
|
450
|
+
cash REAL NOT NULL CHECK(cash >= 0),
|
|
451
|
+
realized_pl_total REAL NOT NULL DEFAULT 0,
|
|
452
|
+
created_at TEXT NOT NULL
|
|
453
|
+
);
|
|
454
|
+
|
|
455
|
+
CREATE TABLE IF NOT EXISTS positions (
|
|
456
|
+
account_id TEXT NOT NULL,
|
|
457
|
+
symbol TEXT NOT NULL,
|
|
458
|
+
exchange TEXT NOT NULL,
|
|
459
|
+
qty REAL NOT NULL CHECK(qty >= 0),
|
|
460
|
+
avg_cost REAL NOT NULL CHECK(avg_cost > 0),
|
|
461
|
+
entry_date TEXT NOT NULL,
|
|
462
|
+
PRIMARY KEY (account_id, symbol),
|
|
463
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
464
|
+
);
|
|
465
|
+
|
|
466
|
+
CREATE TABLE IF NOT EXISTS orders (
|
|
467
|
+
id TEXT PRIMARY KEY,
|
|
468
|
+
account_id TEXT NOT NULL,
|
|
469
|
+
symbol TEXT NOT NULL,
|
|
470
|
+
exchange TEXT NOT NULL,
|
|
471
|
+
side TEXT NOT NULL CHECK(side IN ('buy','sell')),
|
|
472
|
+
qty REAL NOT NULL CHECK(qty > 0),
|
|
473
|
+
order_type TEXT NOT NULL CHECK(order_type IN ('market','limit')),
|
|
474
|
+
status TEXT NOT NULL CHECK(status IN (
|
|
475
|
+
'pending','filled','partially_filled',
|
|
476
|
+
'cancelled','rejected','expired'
|
|
477
|
+
)),
|
|
478
|
+
filled_qty REAL NOT NULL DEFAULT 0,
|
|
479
|
+
filled_avg_price REAL,
|
|
480
|
+
limit_price REAL,
|
|
481
|
+
fees_paid REAL NOT NULL DEFAULT 0,
|
|
482
|
+
realized_pl REAL NOT NULL DEFAULT 0,
|
|
483
|
+
time_in_force TEXT NOT NULL DEFAULT 'DAY',
|
|
484
|
+
created_at TEXT NOT NULL,
|
|
485
|
+
filled_at TEXT,
|
|
486
|
+
cancelled_at TEXT,
|
|
487
|
+
expired_at TEXT,
|
|
488
|
+
rejection_reason TEXT,
|
|
489
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
490
|
+
);
|
|
491
|
+
|
|
492
|
+
CREATE INDEX IF NOT EXISTS idx_orders_account_status
|
|
493
|
+
ON orders(account_id, status);
|
|
494
|
+
CREATE INDEX IF NOT EXISTS idx_orders_account_created
|
|
495
|
+
ON orders(account_id, created_at DESC);
|
|
496
|
+
|
|
497
|
+
CREATE TABLE IF NOT EXISTS trades (
|
|
498
|
+
id TEXT PRIMARY KEY,
|
|
499
|
+
order_id TEXT NOT NULL,
|
|
500
|
+
account_id TEXT NOT NULL,
|
|
501
|
+
symbol TEXT NOT NULL,
|
|
502
|
+
side TEXT NOT NULL,
|
|
503
|
+
qty REAL NOT NULL,
|
|
504
|
+
price REAL NOT NULL,
|
|
505
|
+
fees REAL NOT NULL DEFAULT 0,
|
|
506
|
+
realized_pl REAL NOT NULL DEFAULT 0,
|
|
507
|
+
executed_at TEXT NOT NULL,
|
|
508
|
+
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
|
|
509
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
510
|
+
);
|
|
511
|
+
|
|
512
|
+
CREATE INDEX IF NOT EXISTS idx_trades_account_executed
|
|
513
|
+
ON trades(account_id, executed_at DESC);
|
|
514
|
+
|
|
515
|
+
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
|
516
|
+
account_id TEXT NOT NULL,
|
|
517
|
+
key TEXT NOT NULL,
|
|
518
|
+
request_hash TEXT NOT NULL,
|
|
519
|
+
order_id TEXT NOT NULL,
|
|
520
|
+
created_at TEXT NOT NULL,
|
|
521
|
+
PRIMARY KEY (account_id, key),
|
|
522
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE,
|
|
523
|
+
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
|
|
524
|
+
);
|
|
525
|
+
|
|
526
|
+
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
|
527
|
+
ON idempotency_keys(created_at);
|
|
528
|
+
|
|
529
|
+
CREATE TABLE IF NOT EXISTS symbols (
|
|
530
|
+
symbol TEXT NOT NULL,
|
|
531
|
+
exchange TEXT NOT NULL CHECK(exchange IN ('NSE','BSE')),
|
|
532
|
+
name TEXT,
|
|
533
|
+
isin TEXT,
|
|
534
|
+
lot_size INTEGER NOT NULL DEFAULT 1 CHECK(lot_size >= 1),
|
|
535
|
+
delisted_at TEXT,
|
|
536
|
+
added_at TEXT NOT NULL,
|
|
537
|
+
PRIMARY KEY (symbol, exchange)
|
|
538
|
+
);
|
|
539
|
+
|
|
540
|
+
CREATE INDEX IF NOT EXISTS idx_symbols_delisted
|
|
541
|
+
ON symbols(delisted_at);
|
|
542
|
+
|
|
543
|
+
CREATE TABLE IF NOT EXISTS cash_movements (
|
|
544
|
+
id TEXT PRIMARY KEY,
|
|
545
|
+
account_id TEXT NOT NULL,
|
|
546
|
+
amount REAL NOT NULL,
|
|
547
|
+
reason TEXT NOT NULL CHECK(reason IN (
|
|
548
|
+
'buy_principal', 'buy_fees',
|
|
549
|
+
'sell_principal', 'sell_fees',
|
|
550
|
+
'dividend', 'adjustment', 'initial_capital'
|
|
551
|
+
)),
|
|
552
|
+
order_id TEXT,
|
|
553
|
+
symbol TEXT,
|
|
554
|
+
notes TEXT,
|
|
555
|
+
recorded_at TEXT NOT NULL,
|
|
556
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
557
|
+
);
|
|
558
|
+
|
|
559
|
+
CREATE INDEX IF NOT EXISTS idx_cash_movements_account_recorded
|
|
560
|
+
ON cash_movements(account_id, recorded_at DESC);
|
|
561
|
+
|
|
562
|
+
CREATE INDEX IF NOT EXISTS idx_cash_movements_order
|
|
563
|
+
ON cash_movements(order_id);
|
|
564
|
+
|
|
565
|
+
CREATE TABLE IF NOT EXISTS corporate_actions (
|
|
566
|
+
id TEXT PRIMARY KEY,
|
|
567
|
+
symbol TEXT NOT NULL,
|
|
568
|
+
exchange TEXT NOT NULL,
|
|
569
|
+
action_type TEXT NOT NULL CHECK(action_type IN ('split', 'dividend')),
|
|
570
|
+
ratio_num INTEGER,
|
|
571
|
+
ratio_den INTEGER,
|
|
572
|
+
amount_per_share REAL,
|
|
573
|
+
ex_date TEXT NOT NULL,
|
|
574
|
+
notes TEXT,
|
|
575
|
+
applied_at TEXT NOT NULL
|
|
576
|
+
);
|
|
577
|
+
|
|
578
|
+
CREATE INDEX IF NOT EXISTS idx_corporate_actions_symbol_date
|
|
579
|
+
ON corporate_actions(symbol, ex_date);
|
|
580
|
+
|
|
581
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
582
|
+
id TEXT PRIMARY KEY,
|
|
583
|
+
account_id TEXT,
|
|
584
|
+
event_type TEXT NOT NULL,
|
|
585
|
+
order_id TEXT,
|
|
586
|
+
payload TEXT NOT NULL DEFAULT '{}',
|
|
587
|
+
recorded_at TEXT NOT NULL
|
|
588
|
+
);
|
|
589
|
+
|
|
590
|
+
CREATE INDEX IF NOT EXISTS idx_events_account_recorded
|
|
591
|
+
ON events(account_id, recorded_at DESC);
|
|
592
|
+
|
|
593
|
+
CREATE INDEX IF NOT EXISTS idx_events_type_recorded
|
|
594
|
+
ON events(event_type, recorded_at DESC);
|
|
595
|
+
|
|
596
|
+
CREATE INDEX IF NOT EXISTS idx_events_order
|
|
597
|
+
ON events(order_id);
|
|
598
|
+
"""
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
# ── v2 schema additions ──────────────────────────────────────────────
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
_SETTLEMENT_SCHEMA_SQL = """
|
|
605
|
+
CREATE TABLE IF NOT EXISTS pending_settlements (
|
|
606
|
+
id TEXT PRIMARY KEY,
|
|
607
|
+
account_id TEXT NOT NULL,
|
|
608
|
+
symbol TEXT NOT NULL,
|
|
609
|
+
side TEXT NOT NULL CHECK(side IN ('buy','sell')),
|
|
610
|
+
qty REAL NOT NULL,
|
|
611
|
+
cash_delta REAL NOT NULL DEFAULT 0,
|
|
612
|
+
trade_date TEXT NOT NULL,
|
|
613
|
+
settle_on TEXT NOT NULL,
|
|
614
|
+
status TEXT NOT NULL DEFAULT 'pending'
|
|
615
|
+
CHECK(status IN ('pending','settled','cancelled')),
|
|
616
|
+
created_at TEXT NOT NULL,
|
|
617
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
618
|
+
);
|
|
619
|
+
|
|
620
|
+
CREATE INDEX IF NOT EXISTS idx_pending_settlements_due
|
|
621
|
+
ON pending_settlements(account_id, status, settle_on);
|
|
622
|
+
"""
|