tradingapi 0.5.0__tar.gz → 0.5.2__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 (42) hide show
  1. {tradingapi-0.5.0 → tradingapi-0.5.2}/PKG-INFO +1 -1
  2. {tradingapi-0.5.0 → tradingapi-0.5.2}/pyproject.toml +2 -2
  3. tradingapi-0.5.2/tests/test_dhan_historical_diagnostics.py +89 -0
  4. tradingapi-0.5.2/tests/test_place_combo_order_price_broker.py +109 -0
  5. tradingapi-0.5.2/tests/test_unfilled_eod_pnl.py +53 -0
  6. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/attribution.py +7 -3
  7. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/dhan.py +78 -18
  8. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/fivepaisa.py +16 -3
  9. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/utils.py +69 -77
  10. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi.egg-info/PKG-INFO +1 -1
  11. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi.egg-info/SOURCES.txt +3 -0
  12. {tradingapi-0.5.0 → tradingapi-0.5.2}/README.md +0 -0
  13. {tradingapi-0.5.0 → tradingapi-0.5.2}/setup.cfg +0 -0
  14. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_broker_side_terminal_order.py +0 -0
  15. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_calculate_delta_realtime_quotes.py +0 -0
  16. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_find_option_with_delta.py +0 -0
  17. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_fivepaisa_historical_recovery.py +0 -0
  18. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_fivepaisa_stream_reconnect.py +0 -0
  19. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_flattrade_symbology.py +0 -0
  20. {tradingapi-0.5.0 → tradingapi-0.5.2}/tests/test_market_hours_config.py +0 -0
  21. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/__init__.py +0 -0
  22. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/allocation.py +0 -0
  23. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/broker_base.py +0 -0
  24. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/config/commissions_20241216.yaml +0 -0
  25. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/config/config_sample.yaml +0 -0
  26. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/config.py +0 -0
  27. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/error_handling.py +0 -0
  28. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/exceptions.py +0 -0
  29. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/flattrade.py +0 -0
  30. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/globals.py +0 -0
  31. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/ib.py +0 -0
  32. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/icicidirect.py +0 -0
  33. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/icicidirect_generate_session.py +0 -0
  34. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/market_data_exchanges.py +0 -0
  35. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/market_hours.py +0 -0
  36. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/proxy_utils.py +0 -0
  37. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/shoonya.py +0 -0
  38. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi/span.py +0 -0
  39. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi.egg-info/dependency_links.txt +0 -0
  40. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi.egg-info/entry_points.txt +0 -0
  41. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi.egg-info/requires.txt +0 -0
  42. {tradingapi-0.5.0 → tradingapi-0.5.2}/tradingapi.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tradingapi
3
- Version: 0.5.0
3
+ Version: 0.5.2
4
4
  Summary: Trade integration with brokers
5
5
  Author-email: Pankaj Sharma <sharma.pankaj.kumar@gmail.com>
6
6
  License-Expression: MIT
@@ -16,7 +16,7 @@ module = ["numpy", "pyreadr", "rpy2", "scipy"]
16
16
  ignore_missing_imports = true
17
17
 
18
18
  [build-system]
19
- requires = ["setuptools>=42", "wheel"]
19
+ requires = ["setuptools>=61", "wheel"]
20
20
  build-backend = "setuptools.build_meta"
21
21
 
22
22
  [tool.setuptools]
@@ -28,7 +28,7 @@ packages = ["tradingapi"]
28
28
 
29
29
  [project]
30
30
  name = "tradingapi"
31
- version = "0.5.0"
31
+ version = "0.5.2"
32
32
  description = "Trade integration with brokers"
33
33
  readme = "README.md"
34
34
  license = "MIT"
@@ -0,0 +1,89 @@
1
+ from types import SimpleNamespace
2
+
3
+ from tradingapi.dhan import (
4
+ Dhan,
5
+ _extract_dhan_error_details,
6
+ _is_dhan_auth_error,
7
+ _is_dhan_no_data_error,
8
+ )
9
+
10
+
11
+ class _Response:
12
+ status_code = 502
13
+ text = "upstream unavailable"
14
+
15
+
16
+ class _Session:
17
+ def post(self, *args, **kwargs):
18
+ return _Response()
19
+
20
+
21
+ def test_historical_failure_includes_http_diagnostics():
22
+ broker = Dhan.__new__(Dhan)
23
+ broker.api = SimpleNamespace(
24
+ base_url="https://example.test",
25
+ header={},
26
+ timeout=1,
27
+ session=_Session(),
28
+ _parse_response=lambda response: {
29
+ "status": "failure",
30
+ "remarks": "Expecting value: line 1 column 1 (char 0)",
31
+ "data": "",
32
+ },
33
+ )
34
+ broker._wait_for_historical_rate_limit = lambda: None
35
+ broker._audit_dhan_call = lambda *args, **kwargs: None
36
+
37
+ result = broker._fetch_dhan_historical(
38
+ security_id=123,
39
+ exchange_segment="NSE_FNO",
40
+ instrument_type="OPTSTK",
41
+ from_date="2026-10-06",
42
+ to_date="2026-10-06",
43
+ periodicity="1m",
44
+ include_oi=True,
45
+ symbol="TEST_OPT_20261027_CALL_100",
46
+ )
47
+
48
+ details = _extract_dhan_error_details(result)
49
+ assert details["http_status"] == 502
50
+ assert details["response_body"] == "upstream unavailable"
51
+
52
+
53
+ def test_dhan_907_is_expected_no_data():
54
+ details = _extract_dhan_error_details(
55
+ {"status": "failure", "remarks": {"error_code": "DH-907"}}
56
+ )
57
+
58
+ assert _is_dhan_no_data_error(details)
59
+
60
+
61
+ def test_auth_error_refreshes_token_and_retries_order():
62
+ auth_failure = {
63
+ "status": "failure",
64
+ "remarks": {
65
+ "error_code": "DH-901",
66
+ "error_type": "Invalid_Authentication",
67
+ "error_message": "Client ID or user generated access token is invalid or expired.",
68
+ },
69
+ }
70
+ calls = []
71
+
72
+ class _Api:
73
+ def place_order(self, **kwargs):
74
+ calls.append(kwargs)
75
+ if len(calls) == 1:
76
+ return auth_failure
77
+ return {"status": "success", "data": {"orderId": "1"}}
78
+
79
+ broker = Dhan.__new__(Dhan)
80
+ broker.api = _Api()
81
+ broker.account_key = "DHAN"
82
+ refreshed = []
83
+ broker._refresh_access_token = lambda: refreshed.append(True) or setattr(broker, "api", _Api())
84
+
85
+ assert _is_dhan_auth_error(_extract_dhan_error_details(auth_failure))
86
+ out = broker._submit_order({"security_id": "1", "quantity": 20, "amo_time": None})
87
+ assert out["status"] == "success"
88
+ assert len(calls) == 2
89
+ assert refreshed == [True]
@@ -0,0 +1,109 @@
1
+ from types import SimpleNamespace
2
+ from unittest.mock import Mock
3
+
4
+ import pytest
5
+
6
+ from tradingapi import utils
7
+
8
+
9
+ def _execution_broker():
10
+ broker = Mock()
11
+ broker.broker = SimpleNamespace(name="DHAN")
12
+ broker.map_exchange_for_api.return_value = "NSE"
13
+ broker.exchange_mappings = {
14
+ "NSE": {"exchangetype_map": {"TCS_STK___": "C"}},
15
+ }
16
+ broker.starting_order_ids_int = {}
17
+ return broker
18
+
19
+
20
+ def test_place_combo_order_forwards_price_broker_for_entry(monkeypatch):
21
+ execution_broker = _execution_broker()
22
+ data_broker = Mock()
23
+ transmit = Mock(return_value="TEST_1")
24
+ monkeypatch.setattr(utils, "transmit_entry_order", transmit)
25
+
26
+ utils.place_combo_order(
27
+ execution_broker,
28
+ "TEST",
29
+ ["TCS_STK___"],
30
+ [1],
31
+ entry=True,
32
+ exchanges=["NSE"],
33
+ price_broker=[data_broker],
34
+ price_types=["LMT"],
35
+ )
36
+
37
+ assert transmit.call_args.kwargs["price_broker"] == [data_broker]
38
+
39
+
40
+ @pytest.mark.parametrize("target,expected", [("TEST_2", ["TEST_2"]), ("", ["TEST_1"])])
41
+ def test_exit_fill_attribution_and_retry(monkeypatch, target, expected):
42
+ broker = _execution_broker()
43
+ broker.redis_o.hgetall.return_value = {}
44
+ symbol = "TCS_STK___"
45
+ positions = {"TEST_1": -520, "TEST_2": -130}
46
+ filled = []
47
+ monkeypatch.setattr(utils, "get_exit_candidates", lambda *args: ["TEST_1", "TEST_2"])
48
+ monkeypatch.setattr(utils, "get_open_position_by_order", lambda _, key: {
49
+ symbol: SimpleNamespace(size=positions[key]),
50
+ })
51
+ monkeypatch.setattr(utils, "get_limit_price", lambda *args, **kwargs: 114.3)
52
+ monkeypatch.setattr(utils, "_process_broker_order_update", lambda *args: None)
53
+
54
+ def fill(order):
55
+ positions[order.internal_order_id] += order.quantity
56
+ filled.append(order.internal_order_id)
57
+ return order
58
+
59
+ broker.place_order.side_effect = fill
60
+ utils.place_combo_order(broker, "TEST", [symbol], [130], entry=False,
61
+ price_types=["MKT"], exit_int_order_id=target)
62
+ assert filled == expected
63
+ if target:
64
+ assert positions == {"TEST_1": -520, "TEST_2": 0}
65
+ utils.place_combo_order(broker, "TEST", [symbol], [130], entry=False,
66
+ price_types=["MKT"], exit_int_order_id=target)
67
+ assert filled == ["TEST_2"]
68
+
69
+
70
+ def test_target_survives_freeze_slices(monkeypatch):
71
+ broker = _execution_broker()
72
+ transmit = Mock()
73
+ monkeypatch.setattr(utils, "transmit_exit_order", transmit)
74
+ monkeypatch.setattr(utils.time, "sleep", lambda _: None)
75
+ utils.place_combo_order(broker, "TEST", ["TCS_STK___"], [260], entry=False,
76
+ price_types=["MKT"], freeze_limit_lots=130,
77
+ exit_int_order_id="TEST_2")
78
+ assert transmit.call_count == 2
79
+ assert all(call.kwargs["int_order_id"] == "TEST_2" for call in transmit.call_args_list)
80
+
81
+
82
+ @pytest.mark.parametrize("entry,validate,target", [
83
+ (True, True, "TEST_2"), (False, False, "TEST_2"), (False, True, "OTHER_2"),
84
+ ])
85
+ def test_invalid_exit_target_rejected(entry, validate, target):
86
+ with pytest.raises(ValueError, match="exit_int_order_id"):
87
+ utils.place_combo_order(_execution_broker(), "TEST", ["TCS_STK___"], [130],
88
+ entry=entry, validate_db_position=validate,
89
+ price_types=["MKT"], exit_int_order_id=target)
90
+
91
+
92
+ def test_place_combo_order_forwards_price_broker_for_exit(monkeypatch):
93
+ execution_broker = _execution_broker()
94
+ data_broker = Mock()
95
+ transmit = Mock()
96
+ monkeypatch.setattr(utils, "transmit_exit_order", transmit)
97
+
98
+ utils.place_combo_order(
99
+ execution_broker,
100
+ "TEST",
101
+ ["TCS_STK___"],
102
+ [-1],
103
+ entry=False,
104
+ exchanges=["NSE"],
105
+ price_broker=[data_broker],
106
+ price_types=["LMT"],
107
+ )
108
+
109
+ assert transmit.call_args.kwargs["price_broker"] == [data_broker]
@@ -0,0 +1,53 @@
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()
@@ -1119,7 +1119,8 @@ def fork_partial_trades_in_dataframe(pnl: pd.DataFrame, date_str: str) -> pd.Dat
1119
1119
  for idx, row in partial_trades.iterrows():
1120
1120
  entry_quantity = float(row["entry_quantity"])
1121
1121
  exit_quantity = float(row["exit_quantity"])
1122
- closed_quantity = -exit_quantity
1122
+ # Closed size only; keeping original entry_quantity double-counts the open fork.
1123
+ closed_entry_quantity = -exit_quantity
1123
1124
  open_quantity = entry_quantity + exit_quantity
1124
1125
 
1125
1126
  entry_keys_str = str(row.get("entry_keys", ""))
@@ -1138,7 +1139,8 @@ def fork_partial_trades_in_dataframe(pnl: pd.DataFrame, date_str: str) -> pd.Dat
1138
1139
  forked_entry_keys = [f"{ek}F{fork_num}" for ek in entry_keys] if entry_keys else []
1139
1140
 
1140
1141
  closed_row = row.copy()
1141
- closed_row["exit_quantity"] = closed_quantity
1142
+ closed_row["entry_quantity"] = closed_entry_quantity
1143
+ closed_row["exit_quantity"] = exit_quantity
1142
1144
  new_rows.append(closed_row)
1143
1145
 
1144
1146
  open_row = row.copy()
@@ -1155,7 +1157,9 @@ def fork_partial_trades_in_dataframe(pnl: pd.DataFrame, date_str: str) -> pd.Dat
1155
1157
  new_rows.append(open_row)
1156
1158
  rows_to_drop.append(idx)
1157
1159
  trading_logger.log_debug(
1158
- f" Forked {row.get('int_order_id', 'unknown')}: closed_qty={closed_quantity}, open_qty={open_quantity}, fork_suffix=F{fork_num}"
1160
+ f" Forked {row.get('int_order_id', 'unknown')}: "
1161
+ f"closed_entry={closed_entry_quantity}, exit={exit_quantity}, "
1162
+ f"open_qty={open_quantity}, fork_suffix=F{fork_num}"
1159
1163
  )
1160
1164
 
1161
1165
  pnl = pnl.drop(index=rows_to_drop)
@@ -201,6 +201,8 @@ def _extract_dhan_error(response: Any) -> str:
201
201
  def _extract_dhan_error_details(response: Any) -> Dict[str, Any]:
202
202
  details: Dict[str, Any] = {
203
203
  "status": None,
204
+ "http_status": None,
205
+ "response_body": None,
204
206
  "error_code": None,
205
207
  "error_type": None,
206
208
  "error_message": None,
@@ -210,6 +212,8 @@ def _extract_dhan_error_details(response: Any) -> Dict[str, Any]:
210
212
  return details
211
213
 
212
214
  details["status"] = response.get("status")
215
+ details["http_status"] = response.get("http_status")
216
+ details["response_body"] = response.get("response_body")
213
217
  remarks = response.get("remarks")
214
218
  data = response.get("data")
215
219
 
@@ -233,6 +237,16 @@ def _extract_dhan_error_details(response: Any) -> Dict[str, Any]:
233
237
  return details
234
238
 
235
239
 
240
+ def _is_dhan_auth_error(details: Dict[str, Any]) -> bool:
241
+ code = str(details.get("error_code") or "").upper()
242
+ error_type = str(details.get("error_type") or "").lower()
243
+ return code == "DH-901" or error_type == "invalid_authentication"
244
+
245
+
246
+ def _is_dhan_no_data_error(details: Dict[str, Any]) -> bool:
247
+ return str(details.get("error_code") or "").upper() == "DH-907"
248
+
249
+
236
250
  def _symbol_supports_oi(long_symbol: str) -> bool:
237
251
  return "_FUT_" in long_symbol or "_OPT_" in long_symbol
238
252
 
@@ -595,7 +609,7 @@ class Dhan(BrokerBase):
595
609
  context = create_error_context(redis_db=redis_db, broker_name=self.account_key, error=str(e))
596
610
  raise BrokerConnectionError(f"Unexpected error connecting to Dhan: {str(e)}", context)
597
611
 
598
- def _load_access_token(self) -> str:
612
+ def _load_access_token(self, force_refresh: bool = False) -> str:
599
613
  """
600
614
  Load access token from file, refreshing via TOTP if stale or missing.
601
615
 
@@ -603,11 +617,14 @@ class Dhan(BrokerBase):
603
617
  1. Token file exists and was written today → use it directly
604
618
  2. TOTP_TOKEN configured → do a fresh login and write to file
605
619
  3. ACCESS_TOKEN in config → use it as a last resort (no auto-refresh)
620
+
621
+ force_refresh skips the file and the static config token. A DH-901 means
622
+ today's file is already rejected, so only a new TOTP login is usable.
606
623
  """
607
624
  token_path = config.get(f"{self.account_key}.USERTOKEN")
608
625
 
609
626
  # Check if today's token is already on disk
610
- if token_path and os.path.exists(token_path):
627
+ if not force_refresh and token_path and os.path.exists(token_path):
611
628
  mod_date = dt.datetime.fromtimestamp(os.path.getmtime(token_path)).date()
612
629
  if mod_date == dt.datetime.now().date():
613
630
  with open(token_path, "r") as f:
@@ -625,6 +642,15 @@ class Dhan(BrokerBase):
625
642
  token = self._fresh_login_totp(client_id, pin, totp_token, token_path)
626
643
  if token:
627
644
  return token
645
+ if force_refresh:
646
+ raise AuthenticationError(
647
+ f"Dhan rejected the access token and TOTP login failed for {self.account_key}"
648
+ )
649
+
650
+ if force_refresh:
651
+ raise AuthenticationError(
652
+ f"Dhan rejected the access token for {self.account_key} and TOTP login is not configured"
653
+ )
628
654
 
629
655
  # Last resort: static token in config
630
656
  token = config.get(f"{self.account_key}.ACCESS_TOKEN")
@@ -638,8 +664,36 @@ class Dhan(BrokerBase):
638
664
  raise AuthenticationError(
639
665
  f"Could not obtain Dhan access token for {self.account_key}. Configure TOTP_TOKEN+PIN or ACCESS_TOKEN."
640
666
  )
641
-
642
-
667
+
668
+ def _refresh_access_token(self) -> None:
669
+ """Replace the live client after Dhan rejects the current access token."""
670
+ client_id = config.get(f"{self.account_key}.CLIENT_ID")
671
+ if not client_id:
672
+ raise AuthenticationError(f"{self.account_key}.CLIENT_ID not configured")
673
+ access_token = self._load_access_token(force_refresh=True)
674
+ self._stream_credentials = {"client_id": str(client_id), "access_token": str(access_token)}
675
+ self.api = dhanhq_sdk(client_id, access_token)
676
+ self._last_is_connected_result = None
677
+ self._last_is_connected_check_ts = 0.0
678
+ trading_logger.log_info("Refreshed Dhan access token", {"broker": self.account_key})
679
+
680
+ def _submit_order(self, payload: Dict[str, Any]) -> Any:
681
+ """Place one order. On DH-901, log in again and retry once."""
682
+ if self.api is None:
683
+ raise BrokerConnectionError("Dhan API client not initialized")
684
+ kwargs = {k: v for k, v in payload.items() if v is not None}
685
+ out = self.api.place_order(**kwargs)
686
+ if out and out.get("status") == "success":
687
+ return out
688
+ if _is_dhan_auth_error(_extract_dhan_error_details(out)):
689
+ trading_logger.log_warning(
690
+ "Dhan access token rejected; refreshing and retrying order",
691
+ {"broker": self.account_key, "response": out},
692
+ )
693
+ self._refresh_access_token()
694
+ out = self.api.place_order(**kwargs)
695
+ return out
696
+
643
697
  def _fresh_login_totp(self, client_id: str, pin: str, totp_secret: str, token_path: Optional[str]) -> Optional[str]:
644
698
  """
645
699
  Obtain a fresh Dhan access token using TOTP, mirroring FivePaisa's _fresh_login logic.
@@ -1085,7 +1139,11 @@ class Dhan(BrokerBase):
1085
1139
  "to_date": to_date,
1086
1140
  })
1087
1141
  response = self.api.session.post(url, headers=self.api.header, timeout=self.api.timeout, data=json.dumps(payload))
1088
- return self.api._parse_response(response)
1142
+ parsed = self.api._parse_response(response)
1143
+ if parsed.get("status") != "success":
1144
+ parsed["http_status"] = response.status_code
1145
+ parsed["response_body"] = response.text[:1000].strip()
1146
+ return parsed
1089
1147
 
1090
1148
  def _persist_order_to_redis(self, order: Order, side_hint: Optional[str] = None) -> None:
1091
1149
  broker_order_id = str(getattr(order, "broker_order_id", "") or "").strip()
@@ -1266,10 +1324,7 @@ class Dhan(BrokerBase):
1266
1324
  tag=order.internal_order_id[:20] if order.internal_order_id else None,
1267
1325
  )
1268
1326
 
1269
- if self.api is None:
1270
- raise BrokerConnectionError("Dhan API client not initialized")
1271
-
1272
- out = self.api.place_order(**{k: v for k, v in payload.items() if v is not None})
1327
+ out = self._submit_order(payload)
1273
1328
  trading_logger.log_info(
1274
1329
  "Dhan place_order response",
1275
1330
  {"response": json.dumps(out, default=str), "long_symbol": order.long_symbol},
@@ -1862,15 +1917,20 @@ class Dhan(BrokerBase):
1862
1917
  historical_data_list.sort(key=lambda x: x.date)
1863
1918
  else:
1864
1919
  _hist_err = _extract_dhan_error_details(data)
1865
- trading_logger.log_error(
1866
- "No data from Dhan historical API",
1867
- None,
1868
- {
1869
- "symbol": long_symbol,
1870
- **_hist_err,
1871
- },
1872
- )
1873
- self._audit_dhan_call("error", {
1920
+ _hist_context = {"symbol": long_symbol, **_hist_err}
1921
+ _is_no_data = _is_dhan_no_data_error(_hist_err)
1922
+ if _is_no_data:
1923
+ trading_logger.log_info(
1924
+ "No historical candles available from Dhan",
1925
+ _hist_context,
1926
+ )
1927
+ else:
1928
+ trading_logger.log_error(
1929
+ "No data from Dhan historical API",
1930
+ None,
1931
+ _hist_context,
1932
+ )
1933
+ self._audit_dhan_call("no_data" if _is_no_data else "error", {
1874
1934
  "call_type": "historical",
1875
1935
  "symbol": long_symbol,
1876
1936
  "security_id": security_id,
@@ -2359,7 +2359,13 @@ class FivePaisa(BrokerBase):
2359
2359
  return order_info
2360
2360
  return self._apply_broker_side_terminal_resolution(order, order_info, message=reason or order.message)
2361
2361
 
2362
- def get_orderinfo_from_orders(exch_order_id: str, order: Order, broker_order_id: str) -> OrderInfo:
2362
+ def get_orderinfo_from_orders(
2363
+ exch_order_id: str,
2364
+ order: Order,
2365
+ broker_order_id: str,
2366
+ *,
2367
+ missing_as_cancelled: bool = False,
2368
+ ) -> OrderInfo:
2363
2369
  """Get order info from order book."""
2364
2370
  try:
2365
2371
  if self.api is None:
@@ -2533,7 +2539,7 @@ class FivePaisa(BrokerBase):
2533
2539
  order_price=order.price,
2534
2540
  fill_size=0,
2535
2541
  fill_price=0,
2536
- status=OrderStatus.UNDEFINED,
2542
+ status=OrderStatus.CANCELLED if missing_as_cancelled else OrderStatus.UNDEFINED,
2537
2543
  broker_order_id=order.broker_order_id,
2538
2544
  exchange_order_id=order.exch_order_id,
2539
2545
  broker=self.broker,
@@ -2702,7 +2708,14 @@ class FivePaisa(BrokerBase):
2702
2708
  broker=self.broker,
2703
2709
  )
2704
2710
  else:
2705
- return get_orderinfo_from_orders(order.exch_order_id, order, broker_order_id)
2711
+ # No executions: if the order is also gone from the book,
2712
+ # it was cancelled/expired unfilled — not an open position.
2713
+ return get_orderinfo_from_orders(
2714
+ order.exch_order_id,
2715
+ order,
2716
+ broker_order_id,
2717
+ missing_as_cancelled=True,
2718
+ )
2706
2719
  except Exception as e:
2707
2720
  context = create_error_context(
2708
2721
  broker_order_id=broker_order_id,
@@ -204,89 +204,57 @@ def publish_trades_to_redis(
204
204
  int: Number of trade rows published, or 0 if nothing was published.
205
205
  """
206
206
  try:
207
- today = dt.date.today().strftime("%Y-%m-%d")
208
207
  trades = get_pnl_table(broker, strategy_name, refresh_status=True)
209
208
 
210
209
  if trades is None or trades.empty:
211
- trading_logger.log_info(
212
- f"No trades found for {strategy_name} to publish",
213
- {"strategy_name": strategy_name},
214
- )
215
- return 0
216
-
217
- # Filter to relevant trades: today's trades + open positions from earlier days
218
- # This matches the logic used by pnl_publisher._initial_load
219
- relevant_trades = trades
220
- try:
221
- if "entry_time" in trades.columns and "exit_time" in trades.columns:
222
- # Today's trades (entered or exited today)
223
- # Use date boundaries for comparison (start of today to end of today)
224
- today_start = dt.datetime.combine(dt.date.today(), dt.time.min)
225
- today_end = dt.datetime.combine(dt.date.today(), dt.time.max)
226
- entry_today = safe_datetime_compare(trades.entry_time, today_start, ">=") & safe_datetime_compare(
227
- trades.entry_time, today_end, "<="
228
- )
229
- exit_today = safe_datetime_compare(trades.exit_time, today_start, ">=") & safe_datetime_compare(
230
- trades.exit_time, today_end, "<="
231
- )
232
- today_trades = entry_today | exit_today
233
-
234
- # Open trades from earlier days (entered before today, still have open position)
235
- entry_before_today = safe_datetime_compare(trades.entry_time, today_start, "<")
236
-
237
- # Check if position is still open
238
- if "entry_quantity" in trades.columns and "exit_quantity" in trades.columns:
239
- # Primary check: actual open position quantity
240
- has_open_position = trades["entry_quantity"] + trades["exit_quantity"] != 0
241
- # Fallback check: exit_time status (empty string '', None, 0, or >= today)
242
- exit_time_normalized = trades.exit_time.fillna("").astype(str).replace("NaT", "").replace("nan", "")
243
- exit_time_empty = (
244
- (exit_time_normalized == "") | (exit_time_normalized == "0") | (trades.exit_time == 0)
210
+ relevant_trades = empty_trades.copy()
211
+ else:
212
+ relevant_trades = trades
213
+ try:
214
+ if "entry_time" in trades.columns and "exit_time" in trades.columns:
215
+ today_start = dt.datetime.combine(dt.date.today(), dt.time.min)
216
+ today_end = dt.datetime.combine(dt.date.today(), dt.time.max)
217
+ entry_today = safe_datetime_compare(trades.entry_time, today_start, ">=") & safe_datetime_compare(
218
+ trades.entry_time, today_end, "<="
245
219
  )
246
- # A trade is still open if it has no exit recorded OR has open quantity
247
- # (don't consider trades with exit times as "still open", even if exit was today)
248
- exit_time_still_open = exit_time_empty
249
- still_open = has_open_position | exit_time_still_open
250
- else:
251
- # Fallback if quantity columns missing
252
- exit_time_normalized = trades.exit_time.fillna("").astype(str).replace("NaT", "").replace("nan", "")
253
- exit_time_empty = (
254
- (exit_time_normalized == "") | (exit_time_normalized == "0") | (trades.exit_time == 0)
220
+ exit_today = safe_datetime_compare(trades.exit_time, today_start, ">=") & safe_datetime_compare(
221
+ trades.exit_time, today_end, "<="
255
222
  )
256
- # A trade is still open if it has no exit recorded
257
- # (don't consider trades with exit times as "still open", even if exit was today)
258
- still_open = exit_time_empty
259
-
260
- open_from_earlier = entry_before_today & still_open
223
+ today_trades = entry_today | exit_today
224
+ entry_before_today = safe_datetime_compare(trades.entry_time, today_start, "<")
225
+ if "entry_quantity" in trades.columns and "exit_quantity" in trades.columns:
226
+ has_open_position = trades["entry_quantity"] + trades["exit_quantity"] != 0
227
+ exit_time_normalized = trades.exit_time.fillna("").astype(str).replace("NaT", "").replace("nan", "")
228
+ exit_time_empty = (
229
+ (exit_time_normalized == "") | (exit_time_normalized == "0") | (trades.exit_time == 0)
230
+ )
231
+ still_open = has_open_position | exit_time_empty
232
+ else:
233
+ exit_time_normalized = trades.exit_time.fillna("").astype(str).replace("NaT", "").replace("nan", "")
234
+ exit_time_empty = (
235
+ (exit_time_normalized == "") | (exit_time_normalized == "0") | (trades.exit_time == 0)
236
+ )
237
+ still_open = exit_time_empty
238
+ relevant_trades = trades[today_trades | (entry_before_today & still_open)]
239
+ except Exception as e:
240
+ trading_logger.log_warning(
241
+ f"Error filtering trades for {strategy_name}: {e}",
242
+ {"strategy_name": strategy_name, "error": str(e)},
243
+ )
244
+ relevant_trades = trades
245
+ if relevant_trades is None or relevant_trades.empty:
246
+ relevant_trades = empty_trades.copy()
261
247
 
262
- # Combine: today's trades OR open trades from earlier days
263
- relevant_mask = today_trades | open_from_earlier
264
- relevant_trades = trades[relevant_mask]
265
- except Exception as e:
266
- trading_logger.log_warning(
267
- f"Error filtering trades for {strategy_name}: {e}",
268
- {"strategy_name": strategy_name, "error": str(e)},
248
+ if not publish:
249
+ trading_logger.log_debug(
250
+ f"Skipping publish for {strategy_name} (publish=False)",
251
+ {"strategy_name": strategy_name},
269
252
  )
270
- relevant_trades = trades
271
-
272
- if not publish or relevant_trades.empty:
273
- if not publish:
274
- trading_logger.log_debug(
275
- f"Skipping publish for {strategy_name} (publish=False)",
276
- {"strategy_name": strategy_name},
277
- )
278
- # Populate trades_out if provided
279
- if trades_out is not None:
280
- trades_out.append(relevant_trades)
281
- else:
282
- trading_logger.log_info(
283
- f"No relevant trades to publish for {strategy_name} (relevant_trades is empty)",
284
- {"strategy_name": strategy_name, "today": today},
285
- )
253
+ if trades_out is not None:
254
+ trades_out.append(relevant_trades)
286
255
  return 0
287
256
 
288
257
  publish_channel = channel or strategy_name
289
-
290
258
  try:
291
259
  pnl_json = relevant_trades.to_json(orient="split")
292
260
  broker.redis_o.publish(publish_channel, pnl_json)
@@ -794,6 +762,17 @@ def get_pnl_table(
794
762
  exit_quantity = 0
795
763
  exit_price = 0.0
796
764
 
765
+ if entry_quantity == 0 and exit_quantity == 0:
766
+ trading_logger.log_info(
767
+ "Skipping unfilled order in P&L table",
768
+ {
769
+ "int_order_id": int_order_id,
770
+ "strategy": strategy,
771
+ "symbol": effective_symbol,
772
+ },
773
+ )
774
+ continue
775
+
797
776
  # Validate quantity consistency
798
777
  if abs(exit_quantity) > abs(entry_quantity):
799
778
  trading_logger.log_error(
@@ -2176,10 +2155,12 @@ def update_order_status(
2176
2155
  # Broker confirmed terminal zero-fill — safe to prune.
2177
2156
  delete_broker_order_id(broker, internal_order_id, broker_order_id)
2178
2157
  else:
2179
- # UNDEFINED/OPEN/PENDING with fill_size=0 is often a failed/wrong-account
2180
- # lookup; never delete Redis state in that case.
2158
+ # UNDEFINED/OPEN/PENDING with fill_size=0: do not delete (lookup can be
2159
+ # wrong-account), but Redis order_size is not a fill — zero it so EOD
2160
+ # MTM/expiry does not treat the working order as a position.
2161
+ broker.redis_o.hset(broker_order_id, "quantity", "0")
2181
2162
  trading_logger.log_warning(
2182
- "EOD skip delete for ambiguous zero-fill order status",
2163
+ "EOD skip delete for ambiguous zero-fill order status; quantity set to 0",
2183
2164
  {
2184
2165
  "internal_order_id": internal_order_id,
2185
2166
  "broker_order_id": broker_order_id,
@@ -3950,6 +3931,7 @@ def place_combo_order(
3950
3931
  validate_db_position: bool = True,
3951
3932
  paper: bool = True,
3952
3933
  freeze_limit_lots: Optional[int] = None,
3934
+ exit_int_order_id: str = "",
3953
3935
  ) -> dict[str, Any]:
3954
3936
  """Place a combo order with broker with enhanced error handling.
3955
3937
 
@@ -3965,6 +3947,7 @@ def place_combo_order(
3965
3947
  price_types: List of price types for each symbol
3966
3948
  validate_db_position: Whether to validate database position
3967
3949
  paper: Whether this is a paper trade
3950
+ exit_int_order_id: Restrict all exit legs/slices to this internal order; empty uses FIFO.
3968
3951
 
3969
3952
  Returns:
3970
3953
  dict: Dictionary with symbol to internal order ID mapping
@@ -3991,6 +3974,10 @@ def place_combo_order(
3991
3974
  dict: for entry orders a dict containing symbol:int order id is returned. dict is empty for exit orders
3992
3975
  """
3993
3976
 
3977
+ if exit_int_order_id and (
3978
+ entry or not validate_db_position or not exit_int_order_id.startswith(f"{strategy}_")
3979
+ ):
3980
+ raise ValueError("exit_int_order_id requires a validated exit for the same strategy")
3994
3981
  if price_broker is None:
3995
3982
  price_broker = [execution_broker]
3996
3983
  if not isinstance(symbols, list):
@@ -4125,7 +4112,10 @@ def place_combo_order(
4125
4112
  temp_order.is_stoploss_order = True
4126
4113
  trading_logger.log_info(f"{symbol} {exch} {slice_qty} {side} slice={idx}/{len(slices)}")
4127
4114
  if entry:
4128
- temp = transmit_entry_order(execution_broker, strategy, temp_order, paper=paper, mds=mds)
4115
+ temp = transmit_entry_order(
4116
+ execution_broker, strategy, temp_order, paper=paper,
4117
+ price_broker=price_broker, mds=mds,
4118
+ )
4129
4119
  out[symbol] = temp
4130
4120
  else:
4131
4121
  transmit_exit_order(
@@ -4134,7 +4124,9 @@ def place_combo_order(
4134
4124
  temp_order,
4135
4125
  validate_db_position,
4136
4126
  paper=paper,
4127
+ price_broker=price_broker,
4137
4128
  mds=mds,
4129
+ int_order_id=exit_int_order_id,
4138
4130
  )
4139
4131
  if idx < len(slices):
4140
4132
  time.sleep(5)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tradingapi
3
- Version: 0.5.0
3
+ Version: 0.5.2
4
4
  Summary: Trade integration with brokers
5
5
  Author-email: Pankaj Sharma <sharma.pankaj.kumar@gmail.com>
6
6
  License-Expression: MIT
@@ -2,11 +2,14 @@ README.md
2
2
  pyproject.toml
3
3
  tests/test_broker_side_terminal_order.py
4
4
  tests/test_calculate_delta_realtime_quotes.py
5
+ tests/test_dhan_historical_diagnostics.py
5
6
  tests/test_find_option_with_delta.py
6
7
  tests/test_fivepaisa_historical_recovery.py
7
8
  tests/test_fivepaisa_stream_reconnect.py
8
9
  tests/test_flattrade_symbology.py
9
10
  tests/test_market_hours_config.py
11
+ tests/test_place_combo_order_price_broker.py
12
+ tests/test_unfilled_eod_pnl.py
10
13
  tradingapi/__init__.py
11
14
  tradingapi/allocation.py
12
15
  tradingapi/attribution.py
File without changes
File without changes
File without changes