tradingapi 0.5.5__tar.gz → 0.5.6__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.
- {tradingapi-0.5.5 → tradingapi-0.5.6}/PKG-INFO +1 -1
- {tradingapi-0.5.5 → tradingapi-0.5.6}/pyproject.toml +1 -1
- tradingapi-0.5.6/tests/test_fivepaisa_trade_info.py +39 -0
- tradingapi-0.5.6/tests/test_unfilled_eod_pnl.py +125 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/fivepaisa.py +49 -9
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/utils.py +52 -2
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi.egg-info/PKG-INFO +1 -1
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi.egg-info/SOURCES.txt +1 -0
- tradingapi-0.5.5/tests/test_unfilled_eod_pnl.py +0 -53
- {tradingapi-0.5.5 → tradingapi-0.5.6}/README.md +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/setup.cfg +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_broker_side_terminal_order.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_calculate_delta_realtime_quotes.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_calculate_mtm.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_dhan_historical_diagnostics.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_find_option_with_delta.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_fivepaisa_available_capital.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_fivepaisa_historical_recovery.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_fivepaisa_stream_reconnect.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_flattrade_symbology.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_market_hours_config.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_place_combo_order_price_broker.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tests/test_symbol_matches_order.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/__init__.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/allocation.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/attribution.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/broker_base.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/config/commissions_20241216.yaml +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/config/config_sample.yaml +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/config.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/dhan.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/error_handling.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/exceptions.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/flattrade.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/globals.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/ib.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/icicidirect.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/icicidirect_generate_session.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/market_data_exchanges.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/market_hours.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/proxy_utils.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/shoonya.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi/span.py +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi.egg-info/dependency_links.txt +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi.egg-info/entry_points.txt +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi.egg-info/requires.txt +0 -0
- {tradingapi-0.5.5 → tradingapi-0.5.6}/tradingapi.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from types import SimpleNamespace
|
|
2
|
+
from unittest.mock import Mock
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from tradingapi.fivepaisa import FivePaisa
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.mark.parametrize("status, content", [
|
|
11
|
+
(404, "404 page not found"), (200, "not json"),
|
|
12
|
+
(200, '{"body":{"Message":"Invalid session"}}'),
|
|
13
|
+
])
|
|
14
|
+
def test_unavailable_trade_info_returns_none_for_orderbook_fallback(status, content):
|
|
15
|
+
response = httpx.Response(status, text=content, request=httpx.Request("POST", "https://example.test/TradeInformation"))
|
|
16
|
+
api = SimpleNamespace(
|
|
17
|
+
USER_KEY="secret", client_code="client", access_token="token", Jwt_token="",
|
|
18
|
+
APIUID="uid", TRADE_INFO_ROUTE="https://example.test/TradeInformation",
|
|
19
|
+
session=Mock(),
|
|
20
|
+
)
|
|
21
|
+
api.session.post.return_value = response
|
|
22
|
+
broker = SimpleNamespace(api=api)
|
|
23
|
+
assert FivePaisa._fetch_trade_info(broker, []) is None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_trade_info_preserves_partial_execution_details_and_uses_local_payload():
|
|
27
|
+
body = {"TradeDetail": [{"Qty": 65, "Rate": 12.5}], "Status": "Pending"}
|
|
28
|
+
api = SimpleNamespace(
|
|
29
|
+
USER_KEY="secret", client_code="client", access_token="token", Jwt_token="",
|
|
30
|
+
APIUID="uid", TRADE_INFO_ROUTE="https://example.test/TradeInformation",
|
|
31
|
+
session=Mock(), payload={"body": {"unrelated": "preserve"}},
|
|
32
|
+
)
|
|
33
|
+
api.session.post.return_value = httpx.Response(
|
|
34
|
+
200, json={"body": body}, request=httpx.Request("POST", api.TRADE_INFO_ROUTE),
|
|
35
|
+
)
|
|
36
|
+
request = [{"ExchOrderID": "123", "Exch": "N", "ExchType": "D", "ScripCode": 1}]
|
|
37
|
+
assert FivePaisa._fetch_trade_info(SimpleNamespace(api=api), request) == body
|
|
38
|
+
assert api.payload == {"body": {"unrelated": "preserve"}}
|
|
39
|
+
assert api.session.post.call_args.kwargs["json"]["body"]["TradeInformationList"] == request
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
from unittest.mock import MagicMock
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from tradingapi.broker_base import Brokers, OrderInfo, OrderStatus
|
|
6
|
+
from tradingapi.utils import (
|
|
7
|
+
_get_confirmed_open_position_by_order,
|
|
8
|
+
should_prune_terminal_zero_fill_leg,
|
|
9
|
+
update_order_status,
|
|
10
|
+
_process_broker_order_update,
|
|
11
|
+
get_open_position_by_order,
|
|
12
|
+
)
|
|
13
|
+
from tradingapi.broker_base import Order
|
|
14
|
+
from tradingapi.fivepaisa import FivePaisa
|
|
15
|
+
from tradingapi.exceptions import ValidationError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_invalid_broker_id_cannot_overwrite_shared_key():
|
|
19
|
+
broker = MagicMock()
|
|
20
|
+
order = Order(broker_order_id="0", internal_order_id="NEW_1", status="OPEN")
|
|
21
|
+
assert _process_broker_order_update(broker, order, "NIFTY_OPT_20261123_PUT_24900") == ""
|
|
22
|
+
broker.redis_o.hmset.assert_not_called()
|
|
23
|
+
broker.redis_o.hset.assert_not_called()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_broker_remap_rejects_zero_before_redis_mutation():
|
|
27
|
+
broker = MagicMock()
|
|
28
|
+
with pytest.raises(ValidationError):
|
|
29
|
+
FivePaisa._update_broker_order_id(broker, "NEW_1", "12345", "0")
|
|
30
|
+
broker.redis_o.pipeline.assert_not_called()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_positions_ignore_zero_without_expiring():
|
|
34
|
+
broker = MagicMock()
|
|
35
|
+
broker.redis_o.hget.return_value = "0"
|
|
36
|
+
broker.redis_o.hgetall.return_value = {
|
|
37
|
+
"internal_order_id": "OTHER_1", "long_symbol": "NIFTY_OPT_20261123_PUT_24900",
|
|
38
|
+
"quantity": "1170", "order_type": "SHORT", "price": "17.1",
|
|
39
|
+
}
|
|
40
|
+
assert get_open_position_by_order(broker, "OLD_1") == {}
|
|
41
|
+
assert all(call.args[0] != "0" for call in broker.redis_o.hgetall.call_args_list)
|
|
42
|
+
broker.get_quote.assert_not_called()
|
|
43
|
+
broker.redis_o.hmset.assert_not_called()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_cancelled_zero_fill_should_prune():
|
|
47
|
+
fills = OrderInfo(
|
|
48
|
+
order_size=65,
|
|
49
|
+
order_price=25.0,
|
|
50
|
+
fill_size=0,
|
|
51
|
+
fill_price=0,
|
|
52
|
+
status=OrderStatus.CANCELLED,
|
|
53
|
+
broker_order_id="449150478",
|
|
54
|
+
exchange_order_id="1400000189211783",
|
|
55
|
+
broker=Brokers.FIVEPAISA,
|
|
56
|
+
)
|
|
57
|
+
assert should_prune_terminal_zero_fill_leg(fills) is True
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_eod_undefined_zero_fill_zeros_redis_quantity():
|
|
61
|
+
redis = MagicMock()
|
|
62
|
+
redis.hgetall.return_value = {
|
|
63
|
+
"long_symbol": "NIFTY_OPT_20260915_CALL_23300",
|
|
64
|
+
"order_type": "SELL",
|
|
65
|
+
"quantity": "65",
|
|
66
|
+
"price": "25",
|
|
67
|
+
"exchange": "NSE",
|
|
68
|
+
"broker_order_id": "449150478",
|
|
69
|
+
"internal_order_id": "CASOTM01_2",
|
|
70
|
+
"status": "OPEN",
|
|
71
|
+
"broker": "FIVEPAISA",
|
|
72
|
+
"remote_order_id": "2026091515150000",
|
|
73
|
+
"exch_order_id": "1400000189211783",
|
|
74
|
+
}
|
|
75
|
+
broker = MagicMock()
|
|
76
|
+
broker.redis_o = redis
|
|
77
|
+
broker.broker = Brokers.FIVEPAISA
|
|
78
|
+
broker.get_order_info.return_value = OrderInfo(
|
|
79
|
+
order_size=65,
|
|
80
|
+
order_price=25.0,
|
|
81
|
+
fill_size=0,
|
|
82
|
+
fill_price=0,
|
|
83
|
+
status=OrderStatus.UNDEFINED,
|
|
84
|
+
broker_order_id="449150478",
|
|
85
|
+
exchange_order_id="1400000189211783",
|
|
86
|
+
broker=Brokers.FIVEPAISA,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
update_order_status(broker, "CASOTM01_2", "449150478", eod=True)
|
|
90
|
+
|
|
91
|
+
redis.hset.assert_any_call("449150478", "quantity", "0")
|
|
92
|
+
redis.delete.assert_not_called()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_confirmed_positions_exclude_rejected_combo_leg():
|
|
96
|
+
redis = MagicMock()
|
|
97
|
+
redis.hgetall.side_effect = lambda key: {
|
|
98
|
+
"STRANGLENIFTY01_29": {
|
|
99
|
+
"entry_keys": "put-order call-order",
|
|
100
|
+
"exit_keys": "",
|
|
101
|
+
},
|
|
102
|
+
"put-order": {
|
|
103
|
+
"long_symbol": "NIFTY_OPT_20261123_PUT_24900",
|
|
104
|
+
"order_type": "SHORT",
|
|
105
|
+
"quantity": "1170",
|
|
106
|
+
"broker_order_id": "put-order",
|
|
107
|
+
},
|
|
108
|
+
"call-order": {
|
|
109
|
+
"long_symbol": "NIFTY_OPT_20261123_CALL_25900",
|
|
110
|
+
"order_type": "SHORT",
|
|
111
|
+
"quantity": "1170",
|
|
112
|
+
"broker_order_id": "call-order",
|
|
113
|
+
},
|
|
114
|
+
}.get(key, {})
|
|
115
|
+
broker = MagicMock()
|
|
116
|
+
broker.redis_o = redis
|
|
117
|
+
broker.get_order_info.side_effect = [
|
|
118
|
+
OrderInfo(fill_size=0, status=OrderStatus.REJECTED, broker_order_id="put-order"),
|
|
119
|
+
OrderInfo(fill_size=1170, fill_price=14.1, status=OrderStatus.FILLED, broker_order_id="call-order"),
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
positions = _get_confirmed_open_position_by_order(broker, "STRANGLENIFTY01_29")
|
|
123
|
+
|
|
124
|
+
assert list(positions) == ["NIFTY_OPT_20261123_CALL_25900"]
|
|
125
|
+
assert positions["NIFTY_OPT_20261123_CALL_25900"].size == -1170
|
|
@@ -401,6 +401,38 @@ class FivePaisa(BrokerBase):
|
|
|
401
401
|
context = create_error_context(broker_type="FivePaisa", config_keys=list(kwargs.keys()), error=str(e))
|
|
402
402
|
raise BrokerConnectionError(f"Failed to initialize FivePaisa broker: {str(e)}", context)
|
|
403
403
|
|
|
404
|
+
def _fetch_trade_info(self, requests_list):
|
|
405
|
+
"""Validate the HTTP response before decoding trade information."""
|
|
406
|
+
from py5paisa.const import HEADERS
|
|
407
|
+
|
|
408
|
+
api = self.api
|
|
409
|
+
if api is None:
|
|
410
|
+
raise BrokerConnectionError("API client not initialized")
|
|
411
|
+
payload = {
|
|
412
|
+
"head": {"key": api.USER_KEY, "requestCode": "5PTrdInfo"},
|
|
413
|
+
"body": {"ClientCode": api.client_code, "TradeInformationList": requests_list},
|
|
414
|
+
}
|
|
415
|
+
headers = dict(HEADERS)
|
|
416
|
+
headers["Authorization"] = f"Bearer {api.access_token or api.Jwt_token}"
|
|
417
|
+
headers["5Paisa-API-Uid"] = api.APIUID
|
|
418
|
+
response = None
|
|
419
|
+
try:
|
|
420
|
+
response = api.session.post(api.TRADE_INFO_ROUTE, json=payload, headers=headers)
|
|
421
|
+
response.raise_for_status()
|
|
422
|
+
result = response.json()
|
|
423
|
+
body = result.get("body") if isinstance(result, dict) else None
|
|
424
|
+
if not isinstance(body, dict) or not isinstance(body.get("TradeDetail"), list):
|
|
425
|
+
raise ValueError("Missing TradeDetail list")
|
|
426
|
+
return body
|
|
427
|
+
except (httpx.HTTPError, ValueError) as error:
|
|
428
|
+
trading_logger.log_warning(
|
|
429
|
+
"TradeInformation unavailable; falling back to OrderBook",
|
|
430
|
+
{"url": api.TRADE_INFO_ROUTE,
|
|
431
|
+
"http_status": response.status_code if response is not None else None,
|
|
432
|
+
"error_type": type(error).__name__},
|
|
433
|
+
)
|
|
434
|
+
return None
|
|
435
|
+
|
|
404
436
|
def _configure_api_proxy_session(self, force_refresh: bool = False):
|
|
405
437
|
try:
|
|
406
438
|
if self.api is None or not hasattr(self.api, "session"):
|
|
@@ -1896,7 +1928,8 @@ class FivePaisa(BrokerBase):
|
|
|
1896
1928
|
order.price_type = new_price
|
|
1897
1929
|
order.quantity = new_quantity
|
|
1898
1930
|
order.price = new_price
|
|
1899
|
-
|
|
1931
|
+
response_id = str(out.get("BrokerOrderID") or "").strip()
|
|
1932
|
+
order.broker_order_id = response_id if response_id not in ("", "0") else str(broker_order_id)
|
|
1900
1933
|
|
|
1901
1934
|
# Get updated order info
|
|
1902
1935
|
try:
|
|
@@ -1910,7 +1943,7 @@ class FivePaisa(BrokerBase):
|
|
|
1910
1943
|
|
|
1911
1944
|
# Update broker order ID
|
|
1912
1945
|
try:
|
|
1913
|
-
self._update_broker_order_id(order.internal_order_id, broker_order_id,
|
|
1946
|
+
self._update_broker_order_id(order.internal_order_id, broker_order_id, order.broker_order_id)
|
|
1914
1947
|
except Exception as e:
|
|
1915
1948
|
trading_logger.log_warning(
|
|
1916
1949
|
"Failed to update broker order ID",
|
|
@@ -2094,12 +2127,13 @@ class FivePaisa(BrokerBase):
|
|
|
2094
2127
|
|
|
2095
2128
|
if out and "BrokerOrderID" in out:
|
|
2096
2129
|
# Convert broker_order_id to string for consistency
|
|
2097
|
-
|
|
2130
|
+
response_id = str(out["BrokerOrderID"] or "").strip()
|
|
2131
|
+
order.broker_order_id = response_id if response_id not in ("", "0") else str(broker_order_id)
|
|
2098
2132
|
|
|
2099
2133
|
# Update broker order ID
|
|
2100
2134
|
try:
|
|
2101
2135
|
self._update_broker_order_id(
|
|
2102
|
-
order.internal_order_id, broker_order_id,
|
|
2136
|
+
order.internal_order_id, broker_order_id, order.broker_order_id
|
|
2103
2137
|
)
|
|
2104
2138
|
except Exception as e:
|
|
2105
2139
|
trading_logger.log_warning(
|
|
@@ -2221,6 +2255,12 @@ class FivePaisa(BrokerBase):
|
|
|
2221
2255
|
ValidationError: If parameters are invalid
|
|
2222
2256
|
RedisError: If Redis operations fail
|
|
2223
2257
|
"""
|
|
2258
|
+
old_broker_order_id = str(old_broker_order_id).strip()
|
|
2259
|
+
new_broker_order_id = str(new_broker_order_id or "").strip()
|
|
2260
|
+
if new_broker_order_id in ("", "0") or old_broker_order_id in ("", "0"):
|
|
2261
|
+
raise ValidationError("Cannot remap an invalid broker order ID")
|
|
2262
|
+
if old_broker_order_id == new_broker_order_id:
|
|
2263
|
+
return
|
|
2224
2264
|
try:
|
|
2225
2265
|
trading_logger.log_debug(
|
|
2226
2266
|
"Updating broker order ID",
|
|
@@ -2243,8 +2283,8 @@ class FivePaisa(BrokerBase):
|
|
|
2243
2283
|
new_exit_keys = None
|
|
2244
2284
|
|
|
2245
2285
|
# Check if broker_order_id is in entry_keys
|
|
2246
|
-
if entry_keys and
|
|
2247
|
-
new_entry_keys =
|
|
2286
|
+
if entry_keys and old_broker_order_id in entry_keys.split():
|
|
2287
|
+
new_entry_keys = " ".join(new_broker_order_id if k == old_broker_order_id else k for k in entry_keys.split())
|
|
2248
2288
|
trading_logger.log_debug(
|
|
2249
2289
|
"Found broker order ID in entry keys",
|
|
2250
2290
|
{
|
|
@@ -2261,8 +2301,8 @@ class FivePaisa(BrokerBase):
|
|
|
2261
2301
|
context = create_error_context(internal_order_id=internal_order_id, error=str(e))
|
|
2262
2302
|
raise RedisError(f"Failed to retrieve exit keys: {str(e)}", context)
|
|
2263
2303
|
|
|
2264
|
-
if exit_keys and
|
|
2265
|
-
new_exit_keys =
|
|
2304
|
+
if exit_keys and old_broker_order_id in exit_keys.split():
|
|
2305
|
+
new_exit_keys = " ".join(new_broker_order_id if k == old_broker_order_id else k for k in exit_keys.split())
|
|
2266
2306
|
trading_logger.log_debug(
|
|
2267
2307
|
"Found broker order ID in exit keys",
|
|
2268
2308
|
{
|
|
@@ -2685,7 +2725,7 @@ class FivePaisa(BrokerBase):
|
|
|
2685
2725
|
]
|
|
2686
2726
|
if self.api is None:
|
|
2687
2727
|
raise BrokerConnectionError("API client not initialized")
|
|
2688
|
-
trade_info = self.
|
|
2728
|
+
trade_info = self._fetch_trade_info(req_list_)
|
|
2689
2729
|
if trade_info is None:
|
|
2690
2730
|
return get_orderinfo_from_orders(order.exch_order_id, order, broker_order_id)
|
|
2691
2731
|
trade_details = cast(List[Dict[str, Any]], trade_info["TradeDetail"])
|
|
@@ -1163,7 +1163,7 @@ def get_open_position_by_order(
|
|
|
1163
1163
|
"""Helper function to get positions from broker order IDs."""
|
|
1164
1164
|
try:
|
|
1165
1165
|
for key in keys:
|
|
1166
|
-
if not key:
|
|
1166
|
+
if not key or str(key).strip() == "0":
|
|
1167
1167
|
trading_logger.log_warning(
|
|
1168
1168
|
"Empty key found in broker order IDs", {"int_order_id": int_order_id, "keys": keys}
|
|
1169
1169
|
)
|
|
@@ -1704,6 +1704,44 @@ def transmit_entry_order(
|
|
|
1704
1704
|
return int_order_id
|
|
1705
1705
|
|
|
1706
1706
|
|
|
1707
|
+
def _get_confirmed_open_position_by_order(broker: BrokerBase, internal_order_id: str) -> Dict[str, Position]:
|
|
1708
|
+
"""Return a live order's net positions using only broker-confirmed fills.
|
|
1709
|
+
|
|
1710
|
+
Redis retains submitted order quantities so that working orders can be
|
|
1711
|
+
managed. Those quantities must never be used to construct a live exit.
|
|
1712
|
+
"""
|
|
1713
|
+
positions: Dict[str, Position] = {}
|
|
1714
|
+
order_mapping = cast(dict[str, Any], broker.redis_o.hgetall(internal_order_id))
|
|
1715
|
+
for field in ("entry_keys", "exit_keys"):
|
|
1716
|
+
for broker_order_id in str(order_mapping.get(field) or "").split():
|
|
1717
|
+
if not broker_order_id or broker_order_id == "0":
|
|
1718
|
+
continue
|
|
1719
|
+
order_data = cast(dict[str, Any], broker.redis_o.hgetall(broker_order_id))
|
|
1720
|
+
if not order_data:
|
|
1721
|
+
continue
|
|
1722
|
+
try:
|
|
1723
|
+
order = Order(**order_data)
|
|
1724
|
+
fills = broker.get_order_info(broker_order_id=broker_order_id, order=order)
|
|
1725
|
+
fill_size = _order_info_fill_size(fills)
|
|
1726
|
+
except Exception as exc:
|
|
1727
|
+
trading_logger.log_error(
|
|
1728
|
+
"Skipping unconfirmed leg while preparing exit",
|
|
1729
|
+
exc,
|
|
1730
|
+
{"internal_order_id": internal_order_id, "broker_order_id": broker_order_id},
|
|
1731
|
+
)
|
|
1732
|
+
continue
|
|
1733
|
+
if fill_size <= 0:
|
|
1734
|
+
continue
|
|
1735
|
+
position = positions.setdefault(order.long_symbol, Position())
|
|
1736
|
+
position.symbol = order.long_symbol
|
|
1737
|
+
signed_size = int(fill_size) if order.order_type in ("BUY", "COVER") else -int(fill_size)
|
|
1738
|
+
fill_price = float(fills.fill_price or order.price or 0)
|
|
1739
|
+
position.value += fill_price * signed_size
|
|
1740
|
+
position.size += signed_size
|
|
1741
|
+
position.price = position.value / position.size if position.size else 0
|
|
1742
|
+
return {symbol: position for symbol, position in positions.items() if position.size}
|
|
1743
|
+
|
|
1744
|
+
|
|
1707
1745
|
def transmit_exit_order(
|
|
1708
1746
|
broker: BrokerBase,
|
|
1709
1747
|
strategy: str,
|
|
@@ -1784,7 +1822,15 @@ def transmit_exit_order(
|
|
|
1784
1822
|
for internal_order_id in exit_candidates:
|
|
1785
1823
|
if any(quantities_remaining):
|
|
1786
1824
|
cancel_internal_order_id(broker, internal_order_id)
|
|
1787
|
-
|
|
1825
|
+
# A stored entry quantity is an order quantity, not evidence of a
|
|
1826
|
+
# fill. In particular, a rejected leg of a combo may still be
|
|
1827
|
+
# present in Redis until its status is refreshed. Live exits
|
|
1828
|
+
# must therefore be based only on broker-confirmed fills.
|
|
1829
|
+
actual_positions = (
|
|
1830
|
+
_get_confirmed_open_position_by_order(broker, internal_order_id)
|
|
1831
|
+
if not paper
|
|
1832
|
+
else get_open_position_by_order(broker, internal_order_id)
|
|
1833
|
+
)
|
|
1788
1834
|
loop_quantities_remaining = deepcopy(quantities_remaining)
|
|
1789
1835
|
for exit_symbol, quantity, price_type, additional_info, trigger_price in zip(
|
|
1790
1836
|
exit_symbols, loop_quantities_remaining, price_types, additional_infos, trigger_prices
|
|
@@ -1894,6 +1940,10 @@ def _process_broker_order_update(broker: BrokerBase, order: Order, long_symbol:
|
|
|
1894
1940
|
)
|
|
1895
1941
|
return ""
|
|
1896
1942
|
|
|
1943
|
+
if str(order.broker_order_id or "").strip() in ("", "0"):
|
|
1944
|
+
trading_logger.log_error(f"Cannot persist order with invalid broker ID: {order.internal_order_id}")
|
|
1945
|
+
return ""
|
|
1946
|
+
|
|
1897
1947
|
if order.order_type in ["BUY", "SHORT"]:
|
|
1898
1948
|
current_orders = cast(str, broker.redis_o.hget(order.internal_order_id, "entry_keys"))
|
|
1899
1949
|
entry_keys = [k for k in str(current_orders or "").split() if k]
|
|
@@ -8,6 +8,7 @@ tests/test_find_option_with_delta.py
|
|
|
8
8
|
tests/test_fivepaisa_available_capital.py
|
|
9
9
|
tests/test_fivepaisa_historical_recovery.py
|
|
10
10
|
tests/test_fivepaisa_stream_reconnect.py
|
|
11
|
+
tests/test_fivepaisa_trade_info.py
|
|
11
12
|
tests/test_flattrade_symbology.py
|
|
12
13
|
tests/test_market_hours_config.py
|
|
13
14
|
tests/test_place_combo_order_price_broker.py
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
from unittest.mock import MagicMock
|
|
2
|
-
|
|
3
|
-
from tradingapi.broker_base import Brokers, OrderInfo, OrderStatus
|
|
4
|
-
from tradingapi.utils import should_prune_terminal_zero_fill_leg, update_order_status
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
def test_cancelled_zero_fill_should_prune():
|
|
8
|
-
fills = OrderInfo(
|
|
9
|
-
order_size=65,
|
|
10
|
-
order_price=25.0,
|
|
11
|
-
fill_size=0,
|
|
12
|
-
fill_price=0,
|
|
13
|
-
status=OrderStatus.CANCELLED,
|
|
14
|
-
broker_order_id="449150478",
|
|
15
|
-
exchange_order_id="1400000189211783",
|
|
16
|
-
broker=Brokers.FIVEPAISA,
|
|
17
|
-
)
|
|
18
|
-
assert should_prune_terminal_zero_fill_leg(fills) is True
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def test_eod_undefined_zero_fill_zeros_redis_quantity():
|
|
22
|
-
redis = MagicMock()
|
|
23
|
-
redis.hgetall.return_value = {
|
|
24
|
-
"long_symbol": "NIFTY_OPT_20260915_CALL_23300",
|
|
25
|
-
"order_type": "SELL",
|
|
26
|
-
"quantity": "65",
|
|
27
|
-
"price": "25",
|
|
28
|
-
"exchange": "NSE",
|
|
29
|
-
"broker_order_id": "449150478",
|
|
30
|
-
"internal_order_id": "CASOTM01_2",
|
|
31
|
-
"status": "OPEN",
|
|
32
|
-
"broker": "FIVEPAISA",
|
|
33
|
-
"remote_order_id": "2026091515150000",
|
|
34
|
-
"exch_order_id": "1400000189211783",
|
|
35
|
-
}
|
|
36
|
-
broker = MagicMock()
|
|
37
|
-
broker.redis_o = redis
|
|
38
|
-
broker.broker = Brokers.FIVEPAISA
|
|
39
|
-
broker.get_order_info.return_value = OrderInfo(
|
|
40
|
-
order_size=65,
|
|
41
|
-
order_price=25.0,
|
|
42
|
-
fill_size=0,
|
|
43
|
-
fill_price=0,
|
|
44
|
-
status=OrderStatus.UNDEFINED,
|
|
45
|
-
broker_order_id="449150478",
|
|
46
|
-
exchange_order_id="1400000189211783",
|
|
47
|
-
broker=Brokers.FIVEPAISA,
|
|
48
|
-
)
|
|
49
|
-
|
|
50
|
-
update_order_status(broker, "CASOTM01_2", "449150478", eod=True)
|
|
51
|
-
|
|
52
|
-
redis.hset.assert_any_call("449150478", "quantity", "0")
|
|
53
|
-
redis.delete.assert_not_called()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|