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,92 @@
|
|
|
1
|
+
"""Abstract broker interface.
|
|
2
|
+
|
|
3
|
+
Callers talk to brokers exclusively through ``BrokerInterface``, which
|
|
4
|
+
keeps different broker backends (this NSE/BSE paper broker, an
|
|
5
|
+
Alpaca-style US adapter, a live Zerodha/IBKR adapter, ...) swappable
|
|
6
|
+
without touching caller code.
|
|
7
|
+
|
|
8
|
+
Notes on the contract:
|
|
9
|
+
|
|
10
|
+
- All methods are synchronous. Order placement returns immediately with
|
|
11
|
+
the resulting ``Order``. For paper market orders, the returned order is
|
|
12
|
+
already ``FILLED``. For limit orders, status is ``PENDING`` until the
|
|
13
|
+
market crosses the limit price.
|
|
14
|
+
|
|
15
|
+
- Failure modes are exceptions (not return codes): ``InsufficientFundsError``,
|
|
16
|
+
``InsufficientSharesError``, ``MarketClosedError``, ``InvalidOrderError``,
|
|
17
|
+
``PriceUnavailableError``. Callers should expect these and handle them.
|
|
18
|
+
|
|
19
|
+
- ``cancel_order`` returns ``True`` when the order moved from ``PENDING``
|
|
20
|
+
to ``CANCELLED``, ``False`` otherwise (already filled, already cancelled,
|
|
21
|
+
or unknown ID).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from abc import ABC, abstractmethod
|
|
27
|
+
|
|
28
|
+
from .domain.models import Account, Order, OrderStatus, OrderType, Position
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class BrokerInterface(ABC):
|
|
32
|
+
"""Common interface for all broker backends (paper, live, adapters)."""
|
|
33
|
+
|
|
34
|
+
# ── Order placement ────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
def buy(
|
|
38
|
+
self,
|
|
39
|
+
symbol: str,
|
|
40
|
+
qty: float,
|
|
41
|
+
order_type: OrderType = OrderType.MARKET,
|
|
42
|
+
limit_price: float | None = None,
|
|
43
|
+
time_in_force: str = "DAY",
|
|
44
|
+
) -> Order:
|
|
45
|
+
"""Submit a buy order."""
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def sell(
|
|
49
|
+
self,
|
|
50
|
+
symbol: str,
|
|
51
|
+
qty: float,
|
|
52
|
+
order_type: OrderType = OrderType.MARKET,
|
|
53
|
+
limit_price: float | None = None,
|
|
54
|
+
time_in_force: str = "DAY",
|
|
55
|
+
) -> Order:
|
|
56
|
+
"""Submit a sell order."""
|
|
57
|
+
|
|
58
|
+
# ── Read API ───────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
@abstractmethod
|
|
61
|
+
def get_positions(self) -> list[Position]:
|
|
62
|
+
"""All open positions with current price and P&L."""
|
|
63
|
+
|
|
64
|
+
@abstractmethod
|
|
65
|
+
def get_position(self, symbol: str) -> Position | None:
|
|
66
|
+
"""Single position lookup by symbol, or ``None`` if not held."""
|
|
67
|
+
|
|
68
|
+
@abstractmethod
|
|
69
|
+
def get_account(self) -> Account:
|
|
70
|
+
"""Account summary: cash, equity, buying power."""
|
|
71
|
+
|
|
72
|
+
@abstractmethod
|
|
73
|
+
def get_orders(
|
|
74
|
+
self,
|
|
75
|
+
status: OrderStatus | None = None,
|
|
76
|
+
limit: int = 100,
|
|
77
|
+
) -> list[Order]:
|
|
78
|
+
"""Order history, optionally filtered by status. Most recent first."""
|
|
79
|
+
|
|
80
|
+
@abstractmethod
|
|
81
|
+
def get_order(self, order_id: str) -> Order | None:
|
|
82
|
+
"""Single order lookup by ID, or ``None`` if not found."""
|
|
83
|
+
|
|
84
|
+
# ── Order management ───────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
@abstractmethod
|
|
87
|
+
def cancel_order(self, order_id: str) -> bool:
|
|
88
|
+
"""Cancel a pending order. Returns ``True`` if the cancel succeeded."""
|
|
89
|
+
|
|
90
|
+
@abstractmethod
|
|
91
|
+
def cancel_all_orders(self) -> int:
|
|
92
|
+
"""Cancel all pending orders. Returns the count cancelled."""
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.ledger`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.ledger is deprecated; "
|
|
14
|
+
"import from papertrade_india.infrastructure.ledger instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.infrastructure.ledger as _src # noqa: E402
|
|
20
|
+
from papertrade_india.infrastructure.ledger import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.workers.limit_orders`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.limit_orders is deprecated; "
|
|
14
|
+
"import from papertrade_india.workers.limit_orders instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.workers.limit_orders as _src # noqa: E402
|
|
20
|
+
from papertrade_india.workers.limit_orders import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.market_hours`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.market_hours is deprecated; "
|
|
14
|
+
"import from papertrade_india.infrastructure.market_hours instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.infrastructure.market_hours as _src # noqa: E402
|
|
20
|
+
from papertrade_india.infrastructure.market_hours import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module split during the architecture refactor.
|
|
2
|
+
|
|
3
|
+
The original ``microstructure`` module mixed two responsibilities:
|
|
4
|
+
|
|
5
|
+
- pure validation rules (tick / lot / band) → :mod:`papertrade_india.domain.rules.tick_lot_band`
|
|
6
|
+
- the synthetic order-book simulator → :mod:`papertrade_india.execution.book`
|
|
7
|
+
|
|
8
|
+
This shim keeps the legacy import path working but emits a
|
|
9
|
+
:class:`DeprecationWarning`. Update imports to the new locations; this
|
|
10
|
+
shim will be removed in v0.3.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import warnings as _warnings
|
|
16
|
+
|
|
17
|
+
_warnings.warn(
|
|
18
|
+
"papertrade_india.microstructure is deprecated; "
|
|
19
|
+
"import validation rules from papertrade_india.domain.rules.tick_lot_band "
|
|
20
|
+
"and the order-book simulator from papertrade_india.execution.book.",
|
|
21
|
+
DeprecationWarning,
|
|
22
|
+
stacklevel=2,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
from papertrade_india.domain.rules.tick_lot_band import ( # noqa: E402, F401
|
|
26
|
+
MicrostructureConfig,
|
|
27
|
+
is_aligned_to_tick,
|
|
28
|
+
round_to_tick,
|
|
29
|
+
validate_band,
|
|
30
|
+
validate_lot,
|
|
31
|
+
validate_tick,
|
|
32
|
+
)
|
|
33
|
+
from papertrade_india.execution.book import ( # noqa: E402, F401
|
|
34
|
+
BookLevel,
|
|
35
|
+
FillSlice,
|
|
36
|
+
MarketFill,
|
|
37
|
+
OrderBook,
|
|
38
|
+
OrderBookConfig,
|
|
39
|
+
OrderBookSimulator,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
del _warnings
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"MicrostructureConfig",
|
|
46
|
+
"round_to_tick",
|
|
47
|
+
"is_aligned_to_tick",
|
|
48
|
+
"validate_tick",
|
|
49
|
+
"validate_lot",
|
|
50
|
+
"validate_band",
|
|
51
|
+
"OrderBookConfig",
|
|
52
|
+
"BookLevel",
|
|
53
|
+
"OrderBook",
|
|
54
|
+
"FillSlice",
|
|
55
|
+
"MarketFill",
|
|
56
|
+
"OrderBookSimulator",
|
|
57
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.migrations`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.migrations is deprecated; "
|
|
14
|
+
"import from papertrade_india.infrastructure.migrations instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.infrastructure.migrations as _src # noqa: E402
|
|
20
|
+
from papertrade_india.infrastructure.migrations import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.domain.models`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.models is deprecated; "
|
|
14
|
+
"import from papertrade_india.domain.models instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.domain.models as _src # noqa: E402
|
|
20
|
+
from papertrade_india.domain.models import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.observability`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.observability is deprecated; "
|
|
14
|
+
"import from papertrade_india.infrastructure.observability instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.infrastructure.observability as _src # noqa: E402
|
|
20
|
+
from papertrade_india.infrastructure.observability import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""After-Market Order (AMO) queueing and firing.
|
|
2
|
+
|
|
3
|
+
AMO market orders are persisted as PENDING with ``time_in_force='AMO'``
|
|
4
|
+
and fired at the next session open by :func:`fire_pending`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import uuid
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from ..domain.models import Order, OrderSide, OrderStatus, OrderType, ProductType
|
|
14
|
+
from . import state as _state
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
17
|
+
from .._context import BrokerContext
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def queue(
|
|
23
|
+
ctx: BrokerContext,
|
|
24
|
+
symbol: str,
|
|
25
|
+
qty: float,
|
|
26
|
+
side: OrderSide,
|
|
27
|
+
time_in_force: str,
|
|
28
|
+
product_type: ProductType,
|
|
29
|
+
) -> Order:
|
|
30
|
+
"""Queue an AMO market order. Fires at next session open via
|
|
31
|
+
:func:`fire_pending` (the watcher calls this automatically).
|
|
32
|
+
|
|
33
|
+
Persisted as PENDING with ``order_type=MARKET``,
|
|
34
|
+
``time_in_force='AMO'``. Distinguishing from a regular pending
|
|
35
|
+
market order is via the TIF — regular markets never persist as
|
|
36
|
+
PENDING, only AMOs do.
|
|
37
|
+
"""
|
|
38
|
+
order_id = uuid.uuid4().hex[:12]
|
|
39
|
+
now = ctx.now_iso()
|
|
40
|
+
with ctx.persistence.transaction() as conn:
|
|
41
|
+
_state.record(
|
|
42
|
+
ctx, conn,
|
|
43
|
+
order_id=order_id, symbol=symbol, side=side, qty=qty,
|
|
44
|
+
order_type=OrderType.MARKET, status=OrderStatus.PENDING,
|
|
45
|
+
filled_qty=0.0, filled_avg_price=None, limit_price=None,
|
|
46
|
+
fees_paid=0.0, realized_pl=0.0, time_in_force=time_in_force,
|
|
47
|
+
created_at=now, filled_at=None, product_type=product_type,
|
|
48
|
+
)
|
|
49
|
+
ctx.emit(conn, event_type="order_submitted", order_id=order_id,
|
|
50
|
+
payload={"symbol": symbol, "side": side.value, "qty": qty,
|
|
51
|
+
"order_type": OrderType.MARKET.value,
|
|
52
|
+
"time_in_force": "AMO",
|
|
53
|
+
"product_type": product_type.value})
|
|
54
|
+
ctx.drain_pending_events()
|
|
55
|
+
logger.info("QUEUE AMO MARKET %s %s %s (fires at next open)",
|
|
56
|
+
side.value.upper(), qty, symbol)
|
|
57
|
+
|
|
58
|
+
with ctx.persistence.read() as conn:
|
|
59
|
+
row = conn.execute(
|
|
60
|
+
"SELECT * FROM orders WHERE id = ? AND account_id = ?",
|
|
61
|
+
(order_id, ctx.account_id),
|
|
62
|
+
).fetchone()
|
|
63
|
+
assert row is not None
|
|
64
|
+
return _state.row_to_order(row)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def fire_pending(ctx: BrokerContext) -> int:
|
|
68
|
+
"""Fill every pending AMO market order at the current price.
|
|
69
|
+
|
|
70
|
+
Idempotent within a session: orders flip from PENDING to FILLED
|
|
71
|
+
atomically, so a second call after the first fires nothing.
|
|
72
|
+
Intended to be called once at REGULAR-phase open by the watcher.
|
|
73
|
+
|
|
74
|
+
Returns the count of AMO orders fired.
|
|
75
|
+
"""
|
|
76
|
+
from .market import fill_pending_market # noqa: PLC0415
|
|
77
|
+
|
|
78
|
+
with ctx.persistence.read() as conn:
|
|
79
|
+
rows = conn.execute(
|
|
80
|
+
"SELECT id FROM orders "
|
|
81
|
+
"WHERE account_id = ? AND status = ? "
|
|
82
|
+
"AND order_type = ? AND time_in_force = 'AMO'",
|
|
83
|
+
(ctx.account_id, OrderStatus.PENDING.value, OrderType.MARKET.value),
|
|
84
|
+
).fetchall()
|
|
85
|
+
ids = [r["id"] for r in rows]
|
|
86
|
+
n = 0
|
|
87
|
+
for oid in ids:
|
|
88
|
+
try:
|
|
89
|
+
fill_pending_market(ctx, oid)
|
|
90
|
+
n += 1
|
|
91
|
+
except Exception as e: # noqa: BLE001
|
|
92
|
+
logger.warning("AMO fire failed for %s: %s", oid, e)
|
|
93
|
+
if n:
|
|
94
|
+
logger.info("Fired %d AMO market order(s)", n)
|
|
95
|
+
return n
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
__all__ = ["queue", "fire_pending"]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Order-book interaction helpers shared across order modules.
|
|
2
|
+
|
|
3
|
+
Thin wrappers over :class:`OrderBookSimulator` that handle the
|
|
4
|
+
best-effort semantics: any failure (no rich quote, book empty) falls
|
|
5
|
+
back to the slippage-only price so the legacy behavior stays stable.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from ..domain.models import OrderSide
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
16
|
+
from .._context import BrokerContext
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def symbol_microstructure(
|
|
22
|
+
ctx: BrokerContext,
|
|
23
|
+
symbol: str,
|
|
24
|
+
) -> tuple[float, int, float | None]:
|
|
25
|
+
"""Resolve (tick_size, lot_size, daily_band_pct) for ``symbol``.
|
|
26
|
+
|
|
27
|
+
Falls back to :class:`MicrostructureConfig` defaults when the
|
|
28
|
+
symbol master has no override.
|
|
29
|
+
"""
|
|
30
|
+
cfg = ctx.microstructure_config
|
|
31
|
+
with ctx.persistence.read() as conn:
|
|
32
|
+
entry = ctx.symbol_master.get(conn, symbol, ctx.default_exchange)
|
|
33
|
+
if entry is None:
|
|
34
|
+
return (cfg.default_tick_size, cfg.default_lot_size, cfg.default_band_pct)
|
|
35
|
+
tick = entry.tick_size if entry.tick_size is not None else cfg.default_tick_size
|
|
36
|
+
lot = entry.lot_size if entry.lot_size > 0 else cfg.default_lot_size
|
|
37
|
+
band = (
|
|
38
|
+
entry.daily_band_pct
|
|
39
|
+
if entry.daily_band_pct is not None
|
|
40
|
+
else cfg.default_band_pct
|
|
41
|
+
)
|
|
42
|
+
return (tick, lot, band)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def maybe_apply_book_impact(
|
|
46
|
+
ctx: BrokerContext,
|
|
47
|
+
symbol: str,
|
|
48
|
+
qty: float,
|
|
49
|
+
side: OrderSide,
|
|
50
|
+
last_price: float,
|
|
51
|
+
) -> float:
|
|
52
|
+
"""Walk the synthetic book; return VWAP fill price.
|
|
53
|
+
|
|
54
|
+
Only kicks in when the provider supplies a real bid/ask. Without
|
|
55
|
+
bid/ask there's no honest book to synthesize — falls back to the
|
|
56
|
+
slippage-only path so legacy semantics remain stable.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
mq = ctx.price_feed.get_market_quote(symbol)
|
|
60
|
+
except Exception: # noqa: BLE001
|
|
61
|
+
return last_price
|
|
62
|
+
if mq is None or mq.bid is None or mq.ask is None:
|
|
63
|
+
return last_price
|
|
64
|
+
tick, _, _ = symbol_microstructure(ctx, symbol)
|
|
65
|
+
if mq.has_depth:
|
|
66
|
+
# Real provider depth (e.g. Upstox 5-level) — walk the true book.
|
|
67
|
+
book = ctx.book_sim.book_from_levels(
|
|
68
|
+
symbol=symbol, last=last_price,
|
|
69
|
+
bids=mq.bids, asks=mq.asks, tick_size=tick,
|
|
70
|
+
)
|
|
71
|
+
else:
|
|
72
|
+
book = ctx.book_sim.synthesize(
|
|
73
|
+
symbol=symbol, last=last_price, bid=mq.bid, ask=mq.ask,
|
|
74
|
+
adv=float(mq.volume) if mq.volume else None, tick_size=tick,
|
|
75
|
+
)
|
|
76
|
+
fill = ctx.book_sim.walk_book(book, side, int(round(qty)))
|
|
77
|
+
if fill.filled_qty == 0:
|
|
78
|
+
return last_price
|
|
79
|
+
return fill.avg_price
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def maybe_join_book_queue(
|
|
83
|
+
ctx: BrokerContext,
|
|
84
|
+
symbol: str,
|
|
85
|
+
side: OrderSide,
|
|
86
|
+
limit_price: float,
|
|
87
|
+
) -> None:
|
|
88
|
+
"""Record a queue position so ``get_queue_position`` works.
|
|
89
|
+
|
|
90
|
+
Soft-fails on any error; queue tracking is observability, not
|
|
91
|
+
correctness-critical.
|
|
92
|
+
"""
|
|
93
|
+
try:
|
|
94
|
+
mq = ctx.price_feed.get_market_quote(symbol)
|
|
95
|
+
except Exception: # noqa: BLE001
|
|
96
|
+
return
|
|
97
|
+
tick, _, _ = symbol_microstructure(ctx, symbol)
|
|
98
|
+
if mq.has_depth:
|
|
99
|
+
book = ctx.book_sim.book_from_levels(
|
|
100
|
+
symbol=symbol, last=mq.last,
|
|
101
|
+
bids=mq.bids, asks=mq.asks, tick_size=tick,
|
|
102
|
+
)
|
|
103
|
+
else:
|
|
104
|
+
book = ctx.book_sim.synthesize(
|
|
105
|
+
symbol=symbol, last=mq.last, bid=mq.bid, ask=mq.ask,
|
|
106
|
+
adv=float(mq.volume) if mq.volume else None, tick_size=tick,
|
|
107
|
+
)
|
|
108
|
+
ctx.book_sim.join_queue(symbol, side, limit_price, book)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
__all__ = ["symbol_microstructure", "maybe_apply_book_impact", "maybe_join_book_queue"]
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Bracket order: parent entry + stop-loss child + target child.
|
|
2
|
+
|
|
3
|
+
- :func:`queue` — create the three-order bracket atomically.
|
|
4
|
+
- The OCO and sibling-rebalancing logic lives in :mod:`orders.state`
|
|
5
|
+
(``cancel_bracket_siblings``, ``rebalance_bracket_sibling_qty``) so
|
|
6
|
+
it can be called from both the limit and market fill paths.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from ..domain.models import Order, OrderSide, OrderStatus, OrderType, ProductType
|
|
16
|
+
from . import state as _state
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
19
|
+
from .._context import BrokerContext
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def queue(
|
|
25
|
+
ctx: BrokerContext,
|
|
26
|
+
symbol: str,
|
|
27
|
+
qty: float,
|
|
28
|
+
side: OrderSide,
|
|
29
|
+
limit_price: float | None,
|
|
30
|
+
stop_price: float,
|
|
31
|
+
target_price: float,
|
|
32
|
+
time_in_force: str,
|
|
33
|
+
product_type: ProductType = ProductType.DELIVERY,
|
|
34
|
+
) -> Order:
|
|
35
|
+
"""Queue a bracket: parent entry + child SL + child target.
|
|
36
|
+
|
|
37
|
+
Semantics
|
|
38
|
+
---------
|
|
39
|
+
- Parent: MARKET (when ``limit_price is None``) or LIMIT.
|
|
40
|
+
- Children are queued in PENDING but won't trigger until the parent
|
|
41
|
+
fills. The watcher gates them on parent status.
|
|
42
|
+
- On either child filling, the other is auto-cancelled (OCO).
|
|
43
|
+
- On the parent being cancelled while still PENDING, both children
|
|
44
|
+
are auto-cancelled too.
|
|
45
|
+
|
|
46
|
+
Children are the *opposite side* of the parent: a BUY parent spawns
|
|
47
|
+
SELL-stop and SELL-limit children at ``stop_price`` and
|
|
48
|
+
``target_price`` respectively.
|
|
49
|
+
"""
|
|
50
|
+
from .market import fill_pending_market # noqa: PLC0415
|
|
51
|
+
|
|
52
|
+
opposite = OrderSide.SELL if side == OrderSide.BUY else OrderSide.BUY
|
|
53
|
+
parent_id = uuid.uuid4().hex[:12]
|
|
54
|
+
now = ctx.now_iso()
|
|
55
|
+
|
|
56
|
+
with ctx.persistence.transaction() as conn:
|
|
57
|
+
parent_type = OrderType.LIMIT if limit_price is not None else OrderType.MARKET
|
|
58
|
+
_state.record(
|
|
59
|
+
ctx, conn,
|
|
60
|
+
order_id=parent_id, symbol=symbol, side=side, qty=qty,
|
|
61
|
+
order_type=parent_type, status=OrderStatus.PENDING,
|
|
62
|
+
filled_qty=0.0, filled_avg_price=None, limit_price=limit_price,
|
|
63
|
+
fees_paid=0.0, realized_pl=0.0, time_in_force=time_in_force,
|
|
64
|
+
created_at=now, filled_at=None, stop_price=stop_price,
|
|
65
|
+
target_price=target_price, product_type=product_type,
|
|
66
|
+
)
|
|
67
|
+
sl_id = uuid.uuid4().hex[:12]
|
|
68
|
+
_state.record(
|
|
69
|
+
ctx, conn,
|
|
70
|
+
order_id=sl_id, symbol=symbol, side=opposite, qty=qty,
|
|
71
|
+
order_type=OrderType.STOP_MARKET, status=OrderStatus.PENDING,
|
|
72
|
+
filled_qty=0.0, filled_avg_price=None, limit_price=None,
|
|
73
|
+
fees_paid=0.0, realized_pl=0.0, time_in_force=time_in_force,
|
|
74
|
+
created_at=now, filled_at=None, stop_price=stop_price,
|
|
75
|
+
parent_order_id=parent_id, product_type=product_type,
|
|
76
|
+
)
|
|
77
|
+
tgt_id = uuid.uuid4().hex[:12]
|
|
78
|
+
_state.record(
|
|
79
|
+
ctx, conn,
|
|
80
|
+
order_id=tgt_id, symbol=symbol, side=opposite, qty=qty,
|
|
81
|
+
order_type=OrderType.LIMIT, status=OrderStatus.PENDING,
|
|
82
|
+
filled_qty=0.0, filled_avg_price=None, limit_price=target_price,
|
|
83
|
+
fees_paid=0.0, realized_pl=0.0, time_in_force=time_in_force,
|
|
84
|
+
created_at=now, filled_at=None, parent_order_id=parent_id,
|
|
85
|
+
product_type=product_type,
|
|
86
|
+
)
|
|
87
|
+
ctx.emit(conn, event_type="order_submitted", order_id=parent_id,
|
|
88
|
+
payload={"symbol": symbol, "side": side.value, "qty": qty,
|
|
89
|
+
"order_type": "bracket", "limit_price": limit_price,
|
|
90
|
+
"stop_price": stop_price, "target_price": target_price,
|
|
91
|
+
"child_sl_id": sl_id, "child_target_id": tgt_id,
|
|
92
|
+
"product_type": product_type.value})
|
|
93
|
+
ctx.drain_pending_events()
|
|
94
|
+
logger.info("QUEUE BRACKET %s %s %s entry=%s SL=₹%.2f TGT=₹%.2f",
|
|
95
|
+
side.value.upper(), qty, symbol,
|
|
96
|
+
f"₹{limit_price:.2f}" if limit_price else "MARKET",
|
|
97
|
+
stop_price, target_price)
|
|
98
|
+
|
|
99
|
+
if parent_type == OrderType.MARKET:
|
|
100
|
+
try:
|
|
101
|
+
fill_pending_market(ctx, parent_id)
|
|
102
|
+
except Exception as e: # noqa: BLE001
|
|
103
|
+
logger.warning("Parent bracket %s could not fill immediately: %s",
|
|
104
|
+
parent_id, e)
|
|
105
|
+
|
|
106
|
+
with ctx.persistence.read() as conn:
|
|
107
|
+
row = conn.execute(
|
|
108
|
+
"SELECT * FROM orders WHERE id = ? AND account_id = ?",
|
|
109
|
+
(parent_id, ctx.account_id),
|
|
110
|
+
).fetchone()
|
|
111
|
+
assert row is not None
|
|
112
|
+
return _state.row_to_order(row)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
__all__ = ["queue"]
|