PaperTrade-India 0.1.0.dev0__tar.gz

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 (171) hide show
  1. papertrade_india-0.1.0.dev0/.gitignore +41 -0
  2. papertrade_india-0.1.0.dev0/CHANGELOG.md +466 -0
  3. papertrade_india-0.1.0.dev0/LICENSE +21 -0
  4. papertrade_india-0.1.0.dev0/PKG-INFO +261 -0
  5. papertrade_india-0.1.0.dev0/README.md +192 -0
  6. papertrade_india-0.1.0.dev0/docs/ARCHITECTURE.md +224 -0
  7. papertrade_india-0.1.0.dev0/docs/COOKBOOK.md +452 -0
  8. papertrade_india-0.1.0.dev0/docs/FEES.md +156 -0
  9. papertrade_india-0.1.0.dev0/examples/01_basic_usage.py +55 -0
  10. papertrade_india-0.1.0.dev0/examples/02_with_ai_agent.py +55 -0
  11. papertrade_india-0.1.0.dev0/examples/03_backtest_example.py +68 -0
  12. papertrade_india-0.1.0.dev0/examples/04_multi_account.py +45 -0
  13. papertrade_india-0.1.0.dev0/examples/05_mcp_server.py +180 -0
  14. papertrade_india-0.1.0.dev0/examples/06_tier3_observability.py +147 -0
  15. papertrade_india-0.1.0.dev0/examples/07_backtest_replay.py +136 -0
  16. papertrade_india-0.1.0.dev0/examples/08_data_providers.py +123 -0
  17. papertrade_india-0.1.0.dev0/examples/09_realism_features.py +305 -0
  18. papertrade_india-0.1.0.dev0/pyproject.toml +164 -0
  19. papertrade_india-0.1.0.dev0/src/papertrade_india/__init__.py +250 -0
  20. papertrade_india-0.1.0.dev0/src/papertrade_india/_context.py +144 -0
  21. papertrade_india-0.1.0.dev0/src/papertrade_india/broker.py +546 -0
  22. papertrade_india-0.1.0.dev0/src/papertrade_india/cli.py +474 -0
  23. papertrade_india-0.1.0.dev0/src/papertrade_india/clock.py +29 -0
  24. papertrade_india-0.1.0.dev0/src/papertrade_india/corporate_actions/__init__.py +10 -0
  25. papertrade_india-0.1.0.dev0/src/papertrade_india/corporate_actions/bonus.py +105 -0
  26. papertrade_india-0.1.0.dev0/src/papertrade_india/corporate_actions/dividends.py +99 -0
  27. papertrade_india-0.1.0.dev0/src/papertrade_india/corporate_actions/rights.py +189 -0
  28. papertrade_india-0.1.0.dev0/src/papertrade_india/corporate_actions/splits.py +111 -0
  29. papertrade_india-0.1.0.dev0/src/papertrade_india/corporate_actions/store.py +247 -0
  30. papertrade_india-0.1.0.dev0/src/papertrade_india/data/nse_holidays_2026.json +22 -0
  31. papertrade_india-0.1.0.dev0/src/papertrade_india/data/nse_holidays_2027.json +9 -0
  32. papertrade_india-0.1.0.dev0/src/papertrade_india/data/nse_universe_sample.csv +31 -0
  33. papertrade_india-0.1.0.dev0/src/papertrade_india/domain/__init__.py +6 -0
  34. papertrade_india-0.1.0.dev0/src/papertrade_india/domain/exceptions.py +183 -0
  35. papertrade_india-0.1.0.dev0/src/papertrade_india/domain/models.py +213 -0
  36. papertrade_india-0.1.0.dev0/src/papertrade_india/domain/rules/__init__.py +5 -0
  37. papertrade_india-0.1.0.dev0/src/papertrade_india/domain/rules/risk.py +165 -0
  38. papertrade_india-0.1.0.dev0/src/papertrade_india/domain/rules/tick_lot_band.py +139 -0
  39. papertrade_india-0.1.0.dev0/src/papertrade_india/events.py +29 -0
  40. papertrade_india-0.1.0.dev0/src/papertrade_india/exceptions.py +29 -0
  41. papertrade_india-0.1.0.dev0/src/papertrade_india/execution/__init__.py +5 -0
  42. papertrade_india-0.1.0.dev0/src/papertrade_india/execution/book.py +385 -0
  43. papertrade_india-0.1.0.dev0/src/papertrade_india/execution/fees.py +213 -0
  44. papertrade_india-0.1.0.dev0/src/papertrade_india/execution/settlement.py +360 -0
  45. papertrade_india-0.1.0.dev0/src/papertrade_india/execution/simulation.py +176 -0
  46. papertrade_india-0.1.0.dev0/src/papertrade_india/execution/slippage.py +120 -0
  47. papertrade_india-0.1.0.dev0/src/papertrade_india/fees.py +29 -0
  48. papertrade_india-0.1.0.dev0/src/papertrade_india/idempotency.py +29 -0
  49. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/__init__.py +6 -0
  50. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/clock.py +123 -0
  51. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/events.py +137 -0
  52. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/holidays.py +138 -0
  53. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/idempotency.py +133 -0
  54. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/ledger.py +141 -0
  55. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/market_hours.py +200 -0
  56. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/migrations.py +622 -0
  57. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/observability.py +195 -0
  58. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/persistence.py +130 -0
  59. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/symbols.py +279 -0
  60. papertrade_india-0.1.0.dev0/src/papertrade_india/infrastructure/watchlist.py +78 -0
  61. papertrade_india-0.1.0.dev0/src/papertrade_india/interface.py +92 -0
  62. papertrade_india-0.1.0.dev0/src/papertrade_india/ledger.py +29 -0
  63. papertrade_india-0.1.0.dev0/src/papertrade_india/limit_orders.py +29 -0
  64. papertrade_india-0.1.0.dev0/src/papertrade_india/market_hours.py +29 -0
  65. papertrade_india-0.1.0.dev0/src/papertrade_india/microstructure.py +57 -0
  66. papertrade_india-0.1.0.dev0/src/papertrade_india/migrations.py +29 -0
  67. papertrade_india-0.1.0.dev0/src/papertrade_india/models.py +29 -0
  68. papertrade_india-0.1.0.dev0/src/papertrade_india/observability.py +29 -0
  69. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/__init__.py +5 -0
  70. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/amo.py +98 -0
  71. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/book_helpers.py +111 -0
  72. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/bracket.py +115 -0
  73. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/limit.py +210 -0
  74. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/market.py +264 -0
  75. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/partial_fills.py +92 -0
  76. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/preopen.py +274 -0
  77. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/state.py +640 -0
  78. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/stop.py +122 -0
  79. papertrade_india-0.1.0.dev0/src/papertrade_india/orders/submit.py +385 -0
  80. papertrade_india-0.1.0.dev0/src/papertrade_india/partial_fills.py +29 -0
  81. papertrade_india-0.1.0.dev0/src/papertrade_india/persistence.py +29 -0
  82. papertrade_india-0.1.0.dev0/src/papertrade_india/preopen.py +29 -0
  83. papertrade_india-0.1.0.dev0/src/papertrade_india/presets.py +120 -0
  84. papertrade_india-0.1.0.dev0/src/papertrade_india/price_feed.py +316 -0
  85. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/__init__.py +123 -0
  86. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/alphavantage.py +180 -0
  87. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/base.py +256 -0
  88. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/cache.py +147 -0
  89. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/composite.py +244 -0
  90. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/dhan.py +266 -0
  91. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/finnhub.py +122 -0
  92. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/health.py +233 -0
  93. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/jugaad.py +142 -0
  94. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/kite.py +222 -0
  95. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/nse_bhavcopy.py +210 -0
  96. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/nsepython.py +98 -0
  97. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/registry.py +226 -0
  98. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/stooq.py +173 -0
  99. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/twelvedata.py +198 -0
  100. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/upstox.py +318 -0
  101. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/upstox_instruments.py +171 -0
  102. papertrade_india-0.1.0.dev0/src/papertrade_india/providers/yfinance.py +205 -0
  103. papertrade_india-0.1.0.dev0/src/papertrade_india/quickstart.py +111 -0
  104. papertrade_india-0.1.0.dev0/src/papertrade_india/reads/__init__.py +6 -0
  105. papertrade_india-0.1.0.dev0/src/papertrade_india/reads/account.py +140 -0
  106. papertrade_india-0.1.0.dev0/src/papertrade_india/reads/orders.py +54 -0
  107. papertrade_india-0.1.0.dev0/src/papertrade_india/reads/positions.py +188 -0
  108. papertrade_india-0.1.0.dev0/src/papertrade_india/risk.py +29 -0
  109. papertrade_india-0.1.0.dev0/src/papertrade_india/settlement.py +29 -0
  110. papertrade_india-0.1.0.dev0/src/papertrade_india/simulation.py +29 -0
  111. papertrade_india-0.1.0.dev0/src/papertrade_india/slippage.py +29 -0
  112. papertrade_india-0.1.0.dev0/src/papertrade_india/symbols.py +29 -0
  113. papertrade_india-0.1.0.dev0/src/papertrade_india/workers/__init__.py +6 -0
  114. papertrade_india-0.1.0.dev0/src/papertrade_india/workers/limit_orders.py +390 -0
  115. papertrade_india-0.1.0.dev0/tests/__init__.py +0 -0
  116. papertrade_india-0.1.0.dev0/tests/conftest.py +122 -0
  117. papertrade_india-0.1.0.dev0/tests/e2e/__init__.py +0 -0
  118. papertrade_india-0.1.0.dev0/tests/e2e/test_real_yfinance.py +75 -0
  119. papertrade_india-0.1.0.dev0/tests/integration/__init__.py +0 -0
  120. papertrade_india-0.1.0.dev0/tests/integration/test_alpaca_contract.py +161 -0
  121. papertrade_india-0.1.0.dev0/tests/integration/test_broker_invariants.py +214 -0
  122. papertrade_india-0.1.0.dev0/tests/integration/test_cli_tier3.py +138 -0
  123. papertrade_india-0.1.0.dev0/tests/integration/test_concurrent_access.py +120 -0
  124. papertrade_india-0.1.0.dev0/tests/integration/test_corporate_actions.py +158 -0
  125. papertrade_india-0.1.0.dev0/tests/integration/test_events_and_observability.py +344 -0
  126. papertrade_india-0.1.0.dev0/tests/integration/test_full_lifecycle.py +608 -0
  127. papertrade_india-0.1.0.dev0/tests/integration/test_idempotency.py +141 -0
  128. papertrade_india-0.1.0.dev0/tests/integration/test_ledger.py +220 -0
  129. papertrade_india-0.1.0.dev0/tests/integration/test_migrations.py +295 -0
  130. papertrade_india-0.1.0.dev0/tests/integration/test_partial_fills_integration.py +160 -0
  131. papertrade_india-0.1.0.dev0/tests/integration/test_quickstart_and_breakdown.py +305 -0
  132. papertrade_india-0.1.0.dev0/tests/integration/test_real_depth_fill.py +79 -0
  133. papertrade_india-0.1.0.dev0/tests/integration/test_realism_amo_gtt_preopen.py +213 -0
  134. papertrade_india-0.1.0.dev0/tests/integration/test_realism_bonus_rights.py +159 -0
  135. papertrade_india-0.1.0.dev0/tests/integration/test_realism_microstructure.py +160 -0
  136. papertrade_india-0.1.0.dev0/tests/integration/test_realism_misc.py +256 -0
  137. papertrade_india-0.1.0.dev0/tests/integration/test_realism_settlement.py +150 -0
  138. papertrade_india-0.1.0.dev0/tests/integration/test_realism_stops_and_brackets.py +178 -0
  139. papertrade_india-0.1.0.dev0/tests/integration/test_replay_clock.py +184 -0
  140. papertrade_india-0.1.0.dev0/tests/integration/test_stale_price_reject.py +130 -0
  141. papertrade_india-0.1.0.dev0/tests/integration/test_symbols.py +188 -0
  142. papertrade_india-0.1.0.dev0/tests/unit/__init__.py +0 -0
  143. papertrade_india-0.1.0.dev0/tests/unit/test_book_real_depth.py +68 -0
  144. papertrade_india-0.1.0.dev0/tests/unit/test_clock.py +70 -0
  145. papertrade_india-0.1.0.dev0/tests/unit/test_fee_schedule.py +148 -0
  146. papertrade_india-0.1.0.dev0/tests/unit/test_fees.py +124 -0
  147. papertrade_india-0.1.0.dev0/tests/unit/test_fees_properties.py +141 -0
  148. papertrade_india-0.1.0.dev0/tests/unit/test_holidays.py +71 -0
  149. papertrade_india-0.1.0.dev0/tests/unit/test_layering.py +202 -0
  150. papertrade_india-0.1.0.dev0/tests/unit/test_market_hours.py +159 -0
  151. papertrade_india-0.1.0.dev0/tests/unit/test_microstructure.py +242 -0
  152. papertrade_india-0.1.0.dev0/tests/unit/test_partial_fills.py +71 -0
  153. papertrade_india-0.1.0.dev0/tests/unit/test_preopen.py +114 -0
  154. papertrade_india-0.1.0.dev0/tests/unit/test_presets.py +91 -0
  155. papertrade_india-0.1.0.dev0/tests/unit/test_price_feed.py +102 -0
  156. papertrade_india-0.1.0.dev0/tests/unit/test_price_feed_new_provider_compat.py +162 -0
  157. papertrade_india-0.1.0.dev0/tests/unit/test_providers_base.py +127 -0
  158. papertrade_india-0.1.0.dev0/tests/unit/test_providers_broker_feed.py +496 -0
  159. papertrade_india-0.1.0.dev0/tests/unit/test_providers_composite.py +149 -0
  160. papertrade_india-0.1.0.dev0/tests/unit/test_providers_health.py +126 -0
  161. papertrade_india-0.1.0.dev0/tests/unit/test_providers_registry.py +86 -0
  162. papertrade_india-0.1.0.dev0/tests/unit/test_providers_rest.py +295 -0
  163. papertrade_india-0.1.0.dev0/tests/unit/test_reads_positions.py +98 -0
  164. papertrade_india-0.1.0.dev0/tests/unit/test_resilient_feed.py +144 -0
  165. papertrade_india-0.1.0.dev0/tests/unit/test_risk.py +207 -0
  166. papertrade_india-0.1.0.dev0/tests/unit/test_session_phase.py +147 -0
  167. papertrade_india-0.1.0.dev0/tests/unit/test_settlement.py +129 -0
  168. papertrade_india-0.1.0.dev0/tests/unit/test_simulation.py +94 -0
  169. papertrade_india-0.1.0.dev0/tests/unit/test_slippage.py +222 -0
  170. papertrade_india-0.1.0.dev0/tests/unit/test_upstox_instruments.py +95 -0
  171. papertrade_india-0.1.0.dev0/tests/unit/test_watchlist_store.py +66 -0
@@ -0,0 +1,41 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.so
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .eggs/
8
+ .tox/
9
+ .coverage
10
+ .coverage.*
11
+ htmlcov/
12
+ .pytest_cache/
13
+ .ruff_cache/
14
+ .mypy_cache/
15
+ .hypothesis/
16
+
17
+ # Local virtualenvs
18
+ .venv/
19
+ venv/
20
+ env/
21
+
22
+ # IDE
23
+ .vscode/
24
+ .idea/
25
+ *.swp
26
+
27
+ # OS
28
+ .DS_Store
29
+ Thumbs.db
30
+
31
+ # Secrets
32
+ .env
33
+
34
+ # Local data and DBs created by examples/tests
35
+ *.db
36
+ *.db-journal
37
+ *.db-wal
38
+ *.db-shm
39
+ /data/
40
+ /docs/local/
41
+ examples/_local/
@@ -0,0 +1,466 @@
1
+ # Changelog
2
+
3
+ All notable changes to **papertrade-india** are documented here. The format
4
+ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the
5
+ project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ Pre-1.0 releases may include breaking changes in MINOR bumps; each one will
8
+ be called out here.
9
+
10
+ ## [Unreleased]
11
+
12
+ ### Architecture refactor (internal, no public API changes)
13
+
14
+ The 3,363-line ``broker.py`` god-class has been broken up into cohesive
15
+ subsystems. Phases 1, 2, 3, 4a, and 5 of the
16
+ [architecture refactor plan](docs/architecture_refactor.md) have landed.
17
+
18
+ #### New package layout
19
+
20
+ - ``domain/`` — pure value types and stateless rules
21
+ - ``domain/models.py`` (← ``models.py``)
22
+ - ``domain/exceptions.py`` (← ``exceptions.py``)
23
+ - ``domain/rules/risk.py`` (← ``risk.py``)
24
+ - ``domain/rules/tick_lot_band.py`` (the validation half of
25
+ ``microstructure.py``)
26
+ - ``execution/`` — fill mechanics
27
+ - ``execution/slippage.py``, ``execution/fees.py``,
28
+ ``execution/settlement.py``, ``execution/simulation.py``
29
+ (← root ``slippage.py`` etc.)
30
+ - ``execution/book.py`` (the order-book half of ``microstructure.py``)
31
+ - ``orders/`` — order lifecycle
32
+ - ``orders/partial_fills.py`` (← ``partial_fills.py``)
33
+ - ``orders/preopen.py`` (← ``preopen.py``)
34
+ - ``orders/state.py`` (NEW — ``_record_order``, ``_record_trade``,
35
+ ``_row_to_order`` extracted from ``IndiaPaperBroker``)
36
+ - ``reads/`` — read-only views over broker state (NEW)
37
+ - ``reads/positions.py``, ``reads/account.py``, ``reads/orders.py``
38
+ - ``corporate_actions/`` — splits, bonuses, rights, dividends (NEW
39
+ package replacing ``corporate_actions.py``)
40
+ - ``infrastructure/`` — persistence, observability, clock, market hours,
41
+ symbols, ledger, events, idempotency (← root modules of the same
42
+ names)
43
+ - ``workers/limit_orders.py`` (← ``limit_orders.py``)
44
+ - ``_context.py`` — ``BrokerContext`` dataclass that carries shared
45
+ collaborators to subsystem functions
46
+
47
+ #### Behavior
48
+
49
+ - All 490 tests pass without modification.
50
+ - ``IndiaPaperBroker``'s public surface is unchanged: ``buy``, ``sell``,
51
+ ``get_positions``, ``get_account``, ``apply_split`` and friends keep
52
+ the same signatures and return shapes.
53
+ - ``broker.py`` line count: 3,363 → 2,717 (-19%). Order flow
54
+ (``_submit_order``, ``_execute_market_order``, bracket/stop/limit
55
+ bookkeeping, ~2,300 lines) is the Phase 4b/4c/4d work that remains.
56
+
57
+ #### Deprecated import paths
58
+
59
+ The old ``papertrade_india.<module>`` paths still work for now but emit
60
+ a ``DeprecationWarning`` pointing at the new home. Update imports to
61
+ the new locations; the shim modules will be removed in v0.3.
62
+
63
+ | Old path | New path |
64
+ |:---|:---|
65
+ | ``papertrade_india.models`` | ``papertrade_india.domain.models`` |
66
+ | ``papertrade_india.exceptions`` | ``papertrade_india.domain.exceptions`` |
67
+ | ``papertrade_india.risk`` | ``papertrade_india.domain.rules.risk`` |
68
+ | ``papertrade_india.microstructure`` (validators) | ``papertrade_india.domain.rules.tick_lot_band`` |
69
+ | ``papertrade_india.microstructure`` (book sim) | ``papertrade_india.execution.book`` |
70
+ | ``papertrade_india.slippage`` | ``papertrade_india.execution.slippage`` |
71
+ | ``papertrade_india.fees`` | ``papertrade_india.execution.fees`` |
72
+ | ``papertrade_india.settlement`` | ``papertrade_india.execution.settlement`` |
73
+ | ``papertrade_india.simulation`` | ``papertrade_india.execution.simulation`` |
74
+ | ``papertrade_india.partial_fills`` | ``papertrade_india.orders.partial_fills`` |
75
+ | ``papertrade_india.preopen`` | ``papertrade_india.orders.preopen`` |
76
+ | ``papertrade_india.limit_orders`` | ``papertrade_india.workers.limit_orders`` |
77
+ | ``papertrade_india.persistence`` | ``papertrade_india.infrastructure.persistence`` |
78
+ | ``papertrade_india.migrations`` | ``papertrade_india.infrastructure.migrations`` |
79
+ | ``papertrade_india.idempotency`` | ``papertrade_india.infrastructure.idempotency`` |
80
+ | ``papertrade_india.ledger`` | ``papertrade_india.infrastructure.ledger`` |
81
+ | ``papertrade_india.events`` | ``papertrade_india.infrastructure.events`` |
82
+ | ``papertrade_india.observability`` | ``papertrade_india.infrastructure.observability`` |
83
+ | ``papertrade_india.clock`` | ``papertrade_india.infrastructure.clock`` |
84
+ | ``papertrade_india.market_hours`` | ``papertrade_india.infrastructure.market_hours`` |
85
+ | ``papertrade_india.symbols`` | ``papertrade_india.infrastructure.symbols`` |
86
+
87
+ The umbrella ``papertrade_india`` re-exports stay unchanged: ``from
88
+ papertrade_india import IndiaPaperBroker, Position, Order, ...``
89
+ continues to work.
90
+
91
+ ### Added (Tier-B/C: 1.0 readiness)
92
+
93
+ #### Versioned schema migrations (Tier-C, 1.0 blocker)
94
+ - New `migrations.py` module with a `@migration(N)` decorator,
95
+ `MIGRATIONS` registry, and `run_migrations(conn)` runner.
96
+ - A single `schema_version` table tracks the applied version per DB.
97
+ Brand-new DBs see no row and start at v0; legacy 0.1.x DBs (tables
98
+ present, no row) are detected and stamped at v1 without re-running.
99
+ - Each migration runs in its own `BEGIN IMMEDIATE` transaction so a
100
+ failure leaves the previous state intact.
101
+ - Forward-incompatibility guard: if a DB reports a higher version than
102
+ the package knows, `run_migrations` raises `RuntimeError` rather than
103
+ risking corruption.
104
+ - `papertrade-india migrate --db PATH` CLI command for pre-deploy /
105
+ recovery use.
106
+ - Decorator validates positive versions and rejects duplicates loudly
107
+ so a future double-PR collision can't silently overwrite.
108
+ - The pre-existing `Persistence.SCHEMA` and `EXTENSION_SCHEMAS`
109
+ symbols are now thin re-exports that point at the migrations module
110
+ for backwards compatibility.
111
+
112
+ This is the 1.0 blocker called out in the suggestion review: any future
113
+ schema change can now ship as a v2/v3/... migration and existing 0.1
114
+ users get the new columns automatically on first connect after upgrade.
115
+
116
+ #### Cookbook (Tier-B)
117
+ - New `docs/COOKBOOK.md` with 15 task-oriented recipes covering
118
+ contract-note reconciliation, replay backtests, Jupyter usage,
119
+ mid-year fee changes, autonomous-agent safety, OTel/Prometheus
120
+ wiring, multi-account, and migrations.
121
+
122
+ ### Tests
123
+ - 12 new tests covering fresh DB at head, legacy detection,
124
+ forward-incompatibility, decorator validation, and the migrate CLI.
125
+ - Total: **317 passing**, 3 opt-in E2E skipped.
126
+
127
+ ### Pushed back on (with reasons)
128
+ - **Tier-C `account.cash` integer paise** — the cash-invariant fuzz
129
+ test (200 random ops, exact match within ₹0.01) has held since Tier 2
130
+ with float math. No evidence of drift biting in practice. Switching
131
+ to integer paise touches ~15 files and forces re-validation of every
132
+ fee calculation, for a problem nobody has yet. Document as "if/when"
133
+ in the limitations section.
134
+ - **Tier-C `PriceFeed.subscribe()` for streaming** — speculative.
135
+ No streaming data source to test against. The `PriceProvider`
136
+ Protocol already accepts any `get_price` impl; a future streaming
137
+ provider can wrap a stream into pull-based polling without breaking
138
+ the API.
139
+
140
+ ### Added (Tier-A: completing the package)
141
+
142
+ #### Backtest replay mode
143
+ - New `clock.py` module with `Clock` Protocol, `WallClock` (default),
144
+ and `ReplayClock(start_at)` for deterministic backtests.
145
+ - `IndiaPaperBroker(clock=...)` accepts any `Clock`. Every `datetime.now(IST)`
146
+ call inside the broker now routes through the clock, including order
147
+ timestamps, ledger `recorded_at`, event `recorded_at`, market-hour
148
+ checks, session-phase checks, and DAY-tif expiry timestamps.
149
+ - `broker.clock` property exposes the clock; the limit-order watcher
150
+ uses it for its own market-hour checks.
151
+ - `ReplayClock.advance(timedelta)` and `.set(datetime)` move time
152
+ forward; backwards moves raise `ValueError` so the simulator's
153
+ audit log stays monotonic.
154
+ - New example `examples/07_backtest_replay.py` runs a 10-day momentum
155
+ backtest with no wall-clock waiting.
156
+
157
+ #### Quickstart factory
158
+ - New `quickstart()` factory returns a safe-by-default broker
159
+ pre-configured with the Zerodha-delivery preset, 5 bp slippage,
160
+ strict symbol master with the bundled NSE-30 sample loaded, and
161
+ stale-price hard-reject ON. Saves first-time users from the
162
+ multi-parameter cliff.
163
+
164
+ #### Position basis breakdown
165
+ - New `broker.get_position_basis_breakdown(symbol)` returns
166
+ `{qty, principal, fees_in_basis, total_basis, ledger_buy_principal,
167
+ ledger_buy_fees, ledger_sell_principal, ledger_sell_fees}`. Lets
168
+ users reconcile a position's `avg_cost` against a real broker's
169
+ contract note.
170
+
171
+ #### Status CLI command
172
+ - New `papertrade-india status` consolidates account + positions +
173
+ ledger tail + events tail + invariant check into one Rich panel.
174
+ Same exit-3-on-drift contract as `verify-invariant` so it can also
175
+ serve as a cron health check.
176
+
177
+ #### Watcher idempotency cleanup
178
+ - `LimitOrderWatcher(idempotency_cleanup_every=N, idempotency_ttl_hours=H)`
179
+ runs `broker.cleanup_idempotency_keys(hours=H)` every Nth tick.
180
+ Off by default; opt-in for users who don't want to wire their own
181
+ cron.
182
+
183
+ #### Invariant logging on drift
184
+ - `verify_cash_invariant()` now emits a structured WARN with the drift
185
+ amount, the account id, and the most recent 5 ledger rows when it
186
+ returns False. Triage-friendly out of the box.
187
+
188
+ #### Alpaca contract test
189
+ - New `tests/integration/test_alpaca_contract.py` pins the "drop-in
190
+ replacement for Alpaca's TradingService" claim with structural
191
+ signature checks. Method names, required params, optional params,
192
+ and Order/Account/Position field shapes are all verified.
193
+
194
+ ### Tests
195
+ - 32 new tests across clock, replay-broker, quickstart, basis
196
+ breakdown, status CLI, watcher cleanup, and Alpaca contract.
197
+ - Total: **305 passing**, 3 opt-in E2E skipped.
198
+
199
+ ### Added (Tier-3 polish — closing the loop)
200
+ - `EventBus.subscribe(fn, event_types=...)`: per-subscription filter so
201
+ callbacks only fire for matching event types. Empty set = drop all
202
+ (useful as a deliberate no-op for testing).
203
+ - `EventBus.replay_from_broker(broker, since=..., event_types=...)`:
204
+ re-dispatches persisted events to current subscribers in chronological
205
+ order. Catches up subscribers added mid-run.
206
+ - `BrokerEvent.recorded_at`: timestamp on every delivered event so
207
+ subscribers can do their own time-based logic without re-querying.
208
+ - New CLI commands: `ledger`, `events` (with `--type` filter),
209
+ `verify-invariant` (exit 3 on drift), `phase`.
210
+ - `MarketClosedError` now names the current `SessionPhase` so an agent
211
+ can distinguish "wait 7 minutes for REGULAR" from "wait until tomorrow".
212
+ - MCP server example exposes Tier-3 surfaces:
213
+ `get_session_phase`, `get_cash_ledger`, `get_recent_events`,
214
+ `verify_cash_invariant`.
215
+ - New example `examples/06_tier3_observability.py` demonstrates the
216
+ bus + filter + replay end-to-end.
217
+
218
+ ### Tests
219
+ - 14 new tests covering filter sets, replay, recorded_at on delivered
220
+ events, phase-aware errors, and CLI smoke tests for all new commands.
221
+ - Total: **246 passing**, 3 opt-in E2E skipped.
222
+
223
+ ### Added (Tier-3 realism)
224
+
225
+ #### Configurable partial fills
226
+ - New `PartialFillConfig` (`max_per_tick`, `max_pct_per_tick`,
227
+ `min_fill_qty`, `enabled`). The watcher now slices limit fills per
228
+ tick instead of all-or-nothing.
229
+ - New `OrderStatus.PARTIALLY_FILLED` is now actually used (was reserved).
230
+ - `Order.filled_avg_price` becomes volume-weighted across slices.
231
+ - `cancel_order()` works on PARTIALLY_FILLED orders too — already-filled
232
+ qty stays in the position; the rest is dropped.
233
+ - Honest framing: this is a configurable per-tick fill cap, not real
234
+ bid/ask depth. We have no order book.
235
+
236
+ #### Session phases
237
+ - New `SessionPhase` enum: `CLOSED`, `PRE_OPEN`, `REGULAR`, `POST_CLOSE`.
238
+ - New `NSECalendar.current_phase(dt=None)` returns the active phase.
239
+ - `is_market_open()` now means "is the REGULAR continuous session
240
+ active" — kept the same semantics as before so legacy code still works.
241
+ - New `IndiaPaperBroker.current_session_phase()` exposes the phase.
242
+
243
+ #### Persisted event log
244
+ - New `events` table: append-only, with typed `event_type`, optional
245
+ `account_id`, `order_id`, JSON `payload`, and `recorded_at`.
246
+ - Events emitted: `order_submitted`, `order_filled`,
247
+ `order_partially_filled`, `order_cancelled`, `order_expired`,
248
+ `order_rejected`, `position_opened`, `position_closed`,
249
+ `corporate_action`, `account_reset`.
250
+ - Events are persisted in the same transaction as the state change,
251
+ so the log can never disagree with what was committed.
252
+ - New `IndiaPaperBroker.get_events(limit, event_types)` for queries.
253
+ - Honest framing: this is a parallel audit stream, NOT event-sourcing.
254
+ Account/positions/orders are still authoritative.
255
+
256
+ #### Observability callback bus
257
+ - New `EventBus` for in-process pub/sub of `BrokerEvent` callbacks.
258
+ Wire to OpenTelemetry, Prometheus, structured logs, or anything else.
259
+ - Subscribers fire AFTER the SQL transaction commits (so they never
260
+ see uncommitted state).
261
+ - One bad subscriber doesn't poison the bus — failures are logged
262
+ per-subscriber and the next one still runs.
263
+ - New `IndiaPaperBroker(event_bus=...)` parameter; `broker.events.subscribe(fn)`.
264
+ - New `stdlib_log_subscriber` convenience for development.
265
+
266
+ #### Per-symbol slippage
267
+ - `SlippageConfig` gains a `per_symbol_bps: dict[str, float]` field.
268
+ Use to model illiquid micro-caps with higher slippage than mid-caps.
269
+ - Default `bps` still applies to symbols not in the override map.
270
+
271
+ ### Schema additions
272
+ - `events` table (account-CASCADE; partially scoped — some events have no account_id).
273
+
274
+ ### Tests
275
+ - 42 new tests covering session phases, partial-fill slicing,
276
+ partial-fill cash invariant, event-log persistence, callback bus
277
+ isolation, and per-symbol slippage on the broker.
278
+ - Total: **232 passing**, 3 opt-in E2E skipped.
279
+
280
+ ### Added (Tier-2 realism)
281
+
282
+ #### Immutable cash ledger
283
+ - New `cash_movements` table: append-only row per cash mutation, with
284
+ signed `amount`, typed `reason`, optional `order_id`/`symbol`/`notes`,
285
+ and `recorded_at` timestamp.
286
+ - Reasons: `buy_principal`, `buy_fees`, `sell_principal`, `sell_fees`,
287
+ `dividend`, `adjustment`, `initial_capital`.
288
+ - New `IndiaPaperBroker.get_cash_movements(limit=200)` returns recent
289
+ rows for an account.
290
+ - New `IndiaPaperBroker.verify_cash_invariant()` asserts
291
+ `account.cash == sum(cash_movements.amount)` within ₹0.01. Run from
292
+ audits / health checks.
293
+ - Account creation seeds the ledger with an `initial_capital` row;
294
+ `reset()` re-seeds so the invariant holds across resets.
295
+
296
+ #### Corporate actions
297
+ - New `IndiaPaperBroker.apply_split(symbol, ratio_num, ratio_den, ...)`
298
+ multiplies qty and divides avg_cost by the ratio. Total cost basis
299
+ preserved, no cash impact. Bonus issues are a degenerate split
300
+ (1:1 bonus = 2:1 split).
301
+ - New `IndiaPaperBroker.apply_dividend(symbol, amount_per_share, ...)`
302
+ credits `amount_per_share * qty_held` to cash, recorded in the ledger
303
+ as a `dividend` row. Tax-aware behavior is not modeled.
304
+ - New `corporate_actions` table (audit log of every action applied).
305
+
306
+ #### Date-versioned fee schedule
307
+ - New `FeeSchedule(default, effective_from={date: FeeConfig})`. Broker
308
+ picks the right config based on the order's trade date — useful when
309
+ STT/GST/stamp duty change in budget.
310
+ - Bare `FeeConfig` still works (auto-wrapped in a single-entry schedule).
311
+
312
+ #### Stale-price hard-reject
313
+ - New `IndiaPaperBroker(enforce_fresh_prices=True)` rejects fills whose
314
+ underlying price came from the long-lived stale-price cache.
315
+ - New `Quote` dataclass with `price`, `source`, `fetched_at`, `is_stale`.
316
+ - New `PriceFeed.get_quote(symbol)` returns a `Quote` (existing
317
+ `get_price()` returns float, kept for backwards compatibility).
318
+ - Limit watcher pre-checks staleness so stale orders skip cleanly
319
+ (stay PENDING for the next live tick) without unnecessary log noise.
320
+ - New `StalePriceRejected` exception.
321
+
322
+ ### Schema additions
323
+ - `cash_movements` table (account-CASCADE, no order FK by design — see
324
+ `ledger.py` docstring for the rationale).
325
+ - `corporate_actions` table (audit log).
326
+
327
+ ### Tests
328
+ - 38 new tests covering ledger invariant under random ops, splits +
329
+ dividends + cost-basis preservation, fee schedules with effective
330
+ dates, and stale-price reject paths for both market and limit fills.
331
+ - Total: **190 passing**, 3 opt-in E2E skipped.
332
+
333
+ ### Added (Tier-1 realism)
334
+ - **Slippage model** (`slippage.py`): configurable basis-point slippage
335
+ on market fills. Default 0 bps (legacy behavior); pass
336
+ `SlippageConfig(bps=5)` for realistic 5-bp impact. Limit fills are
337
+ unaffected by default; opt-in with `apply_to_limits=True` (capped by
338
+ the limit price).
339
+ - **Risk controls** (`risk.py`): pre-trade kill switch (config flag or
340
+ `PAPERTRADE_INDIA_KILL_SWITCH=1` env var), symbol whitelist, per-order
341
+ notional cap, per-position notional cap, per-position equity-fraction
342
+ cap. Violations raise `RiskViolation` (or `KillSwitchActive`) with
343
+ zero state mutation.
344
+ - **Idempotency keys** (`idempotency.py`): `buy()` / `sell()` accept
345
+ an `idempotency_key`. Replays with same params return the prior
346
+ order; mismatched params raise `IdempotencyConflict`. Keys scoped
347
+ per-account, TTL-pruned via `cleanup_idempotency_keys()`.
348
+ - **Broker presets** (`presets.py`): named `FeeConfig` instances for
349
+ Zerodha, Upstox, Groww, Angel One, and ICICIdirect (delivery + intraday
350
+ variants where applicable). `get_preset(name)` for case-insensitive
351
+ lookup.
352
+ - **Symbol master** (`symbols.py`): track tradeable NSE/BSE symbols
353
+ with optional metadata (name, ISIN, lot size). Always rejects orders
354
+ for delisted symbols; rejects unknown symbols in `strict=True` mode.
355
+ Bundled `nse_universe_sample.csv` covers ~30 of the largest NSE
356
+ companies.
357
+ - **Non-goals section** in README — visible at the top of the project
358
+ rather than buried in §7 of the design doc.
359
+ - New exceptions: `RiskViolation`, `KillSwitchActive`,
360
+ `IdempotencyConflict`, `SymbolNotFound`, `SymbolDelisted`.
361
+
362
+ ### Changed
363
+ - `IndiaPaperBroker.__init__` accepts `slippage_config`, `risk_config`,
364
+ and `symbol_master`. All default to "no-op" so existing callers see
365
+ zero behavior change.
366
+ - `IndiaPaperBroker.buy()` / `sell()` accept an optional
367
+ `idempotency_key` parameter.
368
+
369
+ ### Schema additions
370
+ - `idempotency_keys` table (per-account, FK CASCADE on account & order).
371
+ - `symbols` table for the symbol master.
372
+
373
+ ### Tests
374
+ - 67 new tests covering all five new modules. Total: 152 passing,
375
+ 3 opt-in E2E skipped.
376
+
377
+ ### Added (test + tooling completeness)
378
+ - Property-based tests for the fee engine (Hypothesis): all components
379
+ non-negative, total within paise of sum, BSE ≥ NSE per side, capped
380
+ brokerage respects paise-rounded cap, etc.
381
+ - Stateful fuzz: ~1000 random buy/sell ops against a 5-symbol universe
382
+ with prices drifting ±2% per op; asserts the equity invariant
383
+ ``cash + portfolio_value == initial + realized + unrealized`` and
384
+ every order ends in a valid terminal status.
385
+ - Round-trip Hypothesis test: any sequence of N buys followed by a
386
+ matched-quantity sell zeroes the position cleanly.
387
+ - E2E test suite (`tests/e2e/`) opt-in via `RUN_E2E=1` for real-yfinance
388
+ smoke. Default `pytest` runs skip these.
389
+ - Snapshot tests for bundled NSE holiday data (2026 + 2027) plus a
390
+ weekend-detector that fails loudly if a refresh PR adds a Sat/Sun.
391
+ - `scripts/update_nse_holidays.py` — converts a hand-curated CSV into
392
+ the bundled JSON, with validation (year matches, no weekends).
393
+ - GitHub Actions: `test.yml` (lint + pytest on Python 3.10/3.11/3.12)
394
+ and `publish.yml` (PyPI Trusted Publishing on tag push).
395
+ - `docs/ARCHITECTURE.md`, `docs/FEES.md`, `docs/CONTRIBUTING.md`.
396
+
397
+ ### Fixed (caught by the new property tests)
398
+ - Bundled holiday data contained dates that fall on weekends
399
+ (`2026-08-15`, several 2027 placeholders). Removed — weekends are
400
+ already non-trading days, and `scripts/update_nse_holidays.py` now
401
+ rejects them at validation time.
402
+
403
+ ### Fixed (correctness)
404
+ - **Buy-side fees now flow into realized P&L.** `avg_cost` includes prorated
405
+ buy fees (i.e. `qty * avg_cost == total cash spent acquiring the position`).
406
+ Realized P&L on a sell — `(price - avg_cost) * qty - sell_fees` — therefore
407
+ captures *both* sides of fees over a round-trip. Previously the buy-side
408
+ fees affected cash but were absent from `realized_pl`, leading the agent
409
+ to systematically over-state P&L by ~₹6–₹15 per round trip.
410
+ - **Limit-order cancel-vs-fill race.** `_execute_limit_fill` now claims the
411
+ order via `UPDATE ... WHERE status='pending'` before applying cash and
412
+ position changes; if the order moved out of PENDING (e.g. user cancelled),
413
+ `OrderNoLongerPending` is raised and the whole transaction rolls back.
414
+ Previously the watcher could clobber a CANCELLED row back to FILLED and
415
+ open an unwanted position.
416
+ - `cancel_order` is similarly race-safe via `WHERE status='pending'`.
417
+
418
+ ### Added
419
+ - `Position.current_price_stale: bool` — flips to `True` when the price
420
+ feed couldn't produce a fresh quote and the broker fell back to
421
+ `avg_cost`. Lets agents distinguish a real break-even from a stale
422
+ valuation.
423
+ - `IndiaPaperBroker.expire_stale_day_orders()` — sweeps all PENDING DAY-tif
424
+ limit orders to EXPIRED in one transaction. Call from a session-close hook.
425
+ - `IndiaPaperBroker(strict_open=True)` — refuse to auto-create a missing
426
+ account; raise `AccountNotFoundError` instead. Used by CLI inspection
427
+ commands.
428
+ - `papertrade-india expire-day-orders` and `create-account` CLI commands.
429
+ - `Order.expired_at` field and EXPIRED status in the DB schema CHECK list.
430
+ - New exceptions: `AccountNotFoundError`, `OrderNoLongerPending`.
431
+
432
+ ### Changed
433
+ - `IndiaPaperBroker.get_position(symbol)` is now O(1) — direct primary-key
434
+ lookup instead of scanning all positions.
435
+ - `get_account()` reads cash, realized_pl_total, and pending-buy notional
436
+ inside one read context for a tighter snapshot.
437
+ - CLI inspection commands (`account`, `positions`, `orders`, `cancel-all`,
438
+ `reset`, `expire-day-orders`) use `strict_open=True` and exit with code 2
439
+ on a missing account instead of silently creating a fresh ₹1M account.
440
+ - Fill log message no longer prints `realized P&L ₹0.00` for buys.
441
+
442
+ ### Schema
443
+ - `account.cash` gains `CHECK(cash >= 0)`.
444
+ - `orders.status` gains a CHECK constraint matching the `OrderStatus` enum.
445
+ - `orders.expired_at` column added.
446
+ - `trades.order_id` foreign key gains `ON DELETE CASCADE` (simplifies `reset()`).
447
+
448
+ ### Initial implementation
449
+ - Initial implementation extracted from `hedge-fund-agent` per
450
+ `docs/India_Paper_Trading_Design.md` v2.0.
451
+ - `IndiaPaperBroker` — drop-in replacement for Alpaca's `TradingService`
452
+ with the same method shapes.
453
+ - `BrokerInterface` ABC for swappable brokers.
454
+ - Domain models: `Position`, `Order`, `Account`, `Trade`.
455
+ - `IndianFeeEngine` with realistic NSE/BSE fee schedule
456
+ (brokerage, STT, exchange, GST, SEBI, stamp duty, DP charges).
457
+ - `NSECalendar` with bundled holiday data for 2026 and 2027.
458
+ - `PriceFeed` with three-layer fallback chain (yfinance →
459
+ jugaad-data → cached last-known).
460
+ - Thread-safe SQLite persistence with WAL mode and atomic transactions.
461
+ - `LimitOrderWatcher` background loop for limit-order fills.
462
+ - Multi-account support via `account_id`.
463
+ - CLI for inspecting account state.
464
+ - MCP server example for direct LLM-agent integration.
465
+
466
+ [Unreleased]: https://github.com/your-org/papertrade-india/compare/HEAD...HEAD
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 papertrade-india contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.