tradingapi 0.5.4__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.
Files changed (47) hide show
  1. {tradingapi-0.5.4 → tradingapi-0.5.6}/PKG-INFO +1 -1
  2. {tradingapi-0.5.4 → tradingapi-0.5.6}/pyproject.toml +1 -1
  3. tradingapi-0.5.6/tests/test_fivepaisa_available_capital.py +34 -0
  4. tradingapi-0.5.6/tests/test_fivepaisa_trade_info.py +39 -0
  5. tradingapi-0.5.6/tests/test_unfilled_eod_pnl.py +125 -0
  6. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/dhan.py +86 -18
  7. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/fivepaisa.py +85 -29
  8. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/utils.py +52 -2
  9. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi.egg-info/PKG-INFO +1 -1
  10. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi.egg-info/SOURCES.txt +2 -0
  11. tradingapi-0.5.4/tests/test_unfilled_eod_pnl.py +0 -53
  12. {tradingapi-0.5.4 → tradingapi-0.5.6}/README.md +0 -0
  13. {tradingapi-0.5.4 → tradingapi-0.5.6}/setup.cfg +0 -0
  14. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_broker_side_terminal_order.py +0 -0
  15. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_calculate_delta_realtime_quotes.py +0 -0
  16. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_calculate_mtm.py +0 -0
  17. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_dhan_historical_diagnostics.py +0 -0
  18. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_find_option_with_delta.py +0 -0
  19. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_fivepaisa_historical_recovery.py +0 -0
  20. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_fivepaisa_stream_reconnect.py +0 -0
  21. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_flattrade_symbology.py +0 -0
  22. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_market_hours_config.py +0 -0
  23. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_place_combo_order_price_broker.py +0 -0
  24. {tradingapi-0.5.4 → tradingapi-0.5.6}/tests/test_symbol_matches_order.py +0 -0
  25. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/__init__.py +0 -0
  26. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/allocation.py +0 -0
  27. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/attribution.py +0 -0
  28. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/broker_base.py +0 -0
  29. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/config/commissions_20241216.yaml +0 -0
  30. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/config/config_sample.yaml +0 -0
  31. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/config.py +0 -0
  32. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/error_handling.py +0 -0
  33. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/exceptions.py +0 -0
  34. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/flattrade.py +0 -0
  35. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/globals.py +0 -0
  36. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/ib.py +0 -0
  37. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/icicidirect.py +0 -0
  38. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/icicidirect_generate_session.py +0 -0
  39. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/market_data_exchanges.py +0 -0
  40. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/market_hours.py +0 -0
  41. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/proxy_utils.py +0 -0
  42. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/shoonya.py +0 -0
  43. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi/span.py +0 -0
  44. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi.egg-info/dependency_links.txt +0 -0
  45. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi.egg-info/entry_points.txt +0 -0
  46. {tradingapi-0.5.4 → tradingapi-0.5.6}/tradingapi.egg-info/requires.txt +0 -0
  47. {tradingapi-0.5.4 → tradingapi-0.5.6}/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.4
3
+ Version: 0.5.6
4
4
  Summary: Trade integration with brokers
5
5
  Author-email: Pankaj Sharma <sharma.pankaj.kumar@gmail.com>
6
6
  License-Expression: MIT
@@ -28,7 +28,7 @@ packages = ["tradingapi"]
28
28
 
29
29
  [project]
30
30
  name = "tradingapi"
31
- version = "0.5.4"
31
+ version = "0.5.6"
32
32
  description = "Trade integration with brokers"
33
33
  readme = "README.md"
34
34
  license = "MIT"
@@ -0,0 +1,34 @@
1
+ import sys
2
+
3
+ sys.path.insert(0, "/home/psharma/onedrive/code/tradingapi2")
4
+
5
+ from tradingapi.fivepaisa import _cash_and_collateral_from_margin
6
+
7
+
8
+ def test_total_collateral_when_stock_field_is_zero():
9
+ cash, collateral = _cash_and_collateral_from_margin(
10
+ {
11
+ "Ledgerbalance": 353996.5,
12
+ "FundsPayln": 0,
13
+ "MFCollateralValueAfterHaircut": 8613729.14,
14
+ "CollateralValueAfterHairCut": 0,
15
+ "TotalCollateralValue": 14131237.12,
16
+ }
17
+ )
18
+ assert cash == 353996.5
19
+ assert collateral == 14131237.12
20
+ assert round(cash + collateral, 2) == 14485233.62
21
+
22
+
23
+ def test_split_collateral_when_it_is_larger_than_total():
24
+ cash, collateral = _cash_and_collateral_from_margin(
25
+ {
26
+ "Ledgerbalance": 100.0,
27
+ "FundsPayln": 20.0,
28
+ "MFCollateralValueAfterHaircut": 50.0,
29
+ "CollateralValueAfterHairCut": 80.0,
30
+ "TotalCollateralValue": 100.0,
31
+ }
32
+ )
33
+ assert cash == 120.0
34
+ assert collateral == 130.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
@@ -609,6 +609,17 @@ class Dhan(BrokerBase):
609
609
  context = create_error_context(redis_db=redis_db, broker_name=self.account_key, error=str(e))
610
610
  raise BrokerConnectionError(f"Unexpected error connecting to Dhan: {str(e)}", context)
611
611
 
612
+ def _read_todays_access_token(self, token_path: Optional[str]) -> Optional[str]:
613
+ """Return today's USERTOKEN contents, or None if missing/stale/empty."""
614
+ if not token_path or not os.path.exists(token_path):
615
+ return None
616
+ mod_date = dt.datetime.fromtimestamp(os.path.getmtime(token_path)).date()
617
+ if mod_date != dt.datetime.now().date():
618
+ return None
619
+ with open(token_path, "r") as f:
620
+ token = f.read().strip()
621
+ return token or None
622
+
612
623
  def _load_access_token(self, force_refresh: bool = False) -> str:
613
624
  """
614
625
  Load access token from file, refreshing via TOTP if stale or missing.
@@ -618,30 +629,67 @@ class Dhan(BrokerBase):
618
629
  2. TOTP_TOKEN configured → do a fresh login and write to file
619
630
  3. ACCESS_TOKEN in config → use it as a last resort (no auto-refresh)
620
631
 
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.
632
+ Concurrent jobs share a Redis lock so only one process hits generateAccessToken;
633
+ losers re-read the file the winner wrote. force_refresh skips the file and the
634
+ static config token. A DH-901 means today's file is already rejected, so only a
635
+ new TOTP login is usable.
623
636
  """
624
637
  token_path = config.get(f"{self.account_key}.USERTOKEN")
625
638
 
626
- # Check if today's token is already on disk
627
- if not force_refresh and token_path and os.path.exists(token_path):
628
- mod_date = dt.datetime.fromtimestamp(os.path.getmtime(token_path)).date()
629
- if mod_date == dt.datetime.now().date():
630
- with open(token_path, "r") as f:
631
- token = f.read().strip()
632
- if token:
633
- trading_logger.log_info("Loaded today's token from file", {"broker": self.account_key})
634
- return token
639
+ if not force_refresh:
640
+ token = self._read_todays_access_token(token_path)
641
+ if token:
642
+ trading_logger.log_info("Loaded today's token from file", {"broker": self.account_key})
643
+ return token
635
644
 
636
- # Try TOTP-based fresh login
637
645
  totp_token = config.get(f"{self.account_key}.TOTP_TOKEN")
638
646
  client_id = config.get(f"{self.account_key}.CLIENT_ID")
639
647
  pin = config.get(f"{self.account_key}.PIN")
640
648
 
641
649
  if totp_token and client_id and pin:
642
- token = self._fresh_login_totp(client_id, pin, totp_token, token_path)
643
- if token:
644
- return token
650
+ distributed_lock = None
651
+ lock_acquired = False
652
+ try:
653
+ lock_redis = redis.Redis(db=0, encoding="utf-8", decode_responses=True)
654
+ distributed_lock = lock_redis.lock(
655
+ f"dhan:totp-refresh:{self.account_key}",
656
+ timeout=300,
657
+ blocking_timeout=310,
658
+ )
659
+ lock_acquired = bool(distributed_lock.acquire(blocking=True))
660
+ except Exception as e:
661
+ trading_logger.log_warning(
662
+ "Distributed Dhan TOTP lock unavailable; generating token without it",
663
+ {"broker": self.account_key, "error": str(e)},
664
+ )
665
+
666
+ try:
667
+ # Winner may have written the file while we waited for the lock.
668
+ if not force_refresh:
669
+ token = self._read_todays_access_token(token_path)
670
+ if token:
671
+ trading_logger.log_info(
672
+ "Loaded today's token from file after lock wait",
673
+ {"broker": self.account_key},
674
+ )
675
+ return token
676
+
677
+ token = self._fresh_login_totp(
678
+ client_id,
679
+ pin,
680
+ totp_token,
681
+ token_path,
682
+ reuse_existing=not force_refresh,
683
+ )
684
+ if token:
685
+ return token
686
+ finally:
687
+ if lock_acquired and distributed_lock is not None:
688
+ try:
689
+ distributed_lock.release()
690
+ except Exception:
691
+ pass
692
+
645
693
  if force_refresh:
646
694
  raise AuthenticationError(
647
695
  f"Dhan rejected the access token and TOTP login failed for {self.account_key}"
@@ -694,7 +742,14 @@ class Dhan(BrokerBase):
694
742
  out = self.api.place_order(**kwargs)
695
743
  return out
696
744
 
697
- def _fresh_login_totp(self, client_id: str, pin: str, totp_secret: str, token_path: Optional[str]) -> Optional[str]:
745
+ def _fresh_login_totp(
746
+ self,
747
+ client_id: str,
748
+ pin: str,
749
+ totp_secret: str,
750
+ token_path: Optional[str],
751
+ reuse_existing: bool = True,
752
+ ) -> Optional[str]:
698
753
  """
699
754
  Obtain a fresh Dhan access token using TOTP, mirroring FivePaisa's _fresh_login logic.
700
755
 
@@ -703,7 +758,8 @@ class Dhan(BrokerBase):
703
758
  body: { dhanClientId, pin, totp }
704
759
 
705
760
  Retries up to 5 times with 40-second waits (same as FivePaisa) to handle
706
- TOTP window boundaries.
761
+ TOTP window boundaries. On Dhan's 2-minute rate limit, prefers reusing a
762
+ token another process just wrote (unless reuse_existing is False).
707
763
  """
708
764
  import pyotp
709
765
 
@@ -741,8 +797,20 @@ class Dhan(BrokerBase):
741
797
  "TOTP login returned no token",
742
798
  {"attempt": attempt, "status_code": resp.status_code, "response": data},
743
799
  )
800
+ # Another process may already have minted today's token.
801
+ if reuse_existing:
802
+ reused = self._read_todays_access_token(token_path)
803
+ if reused:
804
+ trading_logger.log_info(
805
+ "Reusing token written by another process after TOTP rate limit",
806
+ {"broker": self.account_key, "attempt": attempt},
807
+ )
808
+ return reused
744
809
  if attempt < max_attempts:
745
- time.sleep(40)
810
+ msg = str((data or {}).get("message") or "").lower()
811
+ # Dhan allows one generateAccessToken per client every 2 minutes.
812
+ sleep_secs = 125 if "once every 2 minutes" in msg else 40
813
+ time.sleep(sleep_secs)
746
814
 
747
815
  except Exception as e:
748
816
  trading_logger.log_error(
@@ -298,6 +298,38 @@ def save_symbol_data(saveToFolder: bool = False):
298
298
  raise
299
299
 
300
300
 
301
+ def _margin_float(row: Dict, key: str, default: float = 0.0) -> float:
302
+ try:
303
+ value = row.get(key, default)
304
+ if value is None or value == "":
305
+ return float(default)
306
+ return float(value)
307
+ except (TypeError, ValueError):
308
+ return float(default)
309
+
310
+
311
+ def _cash_and_collateral_from_margin(row: Dict) -> tuple:
312
+ """Cash available plus collateral from a FivePaisa margin row.
313
+
314
+ Cash is ledger plus pay-in. Collateral is the larger of TotalCollateralValue
315
+ and mutual-fund collateral plus CollateralValueAfterHairCut. The total is
316
+ the figure that matches free margin plus margin already blocked.
317
+ """
318
+ if "Ledgerbalance" not in row:
319
+ raise KeyError("Ledgerbalance")
320
+ cash = _margin_float(row, "Ledgerbalance") + _margin_float(row, "FundsPayln")
321
+ split = _margin_float(row, "MFCollateralValueAfterHaircut") + _margin_float(
322
+ row, "CollateralValueAfterHairCut"
323
+ )
324
+ collateral = max(split, _margin_float(row, "TotalCollateralValue"))
325
+ if collateral <= 0.0:
326
+ for field in ("Collateral", "collateral", "CollateralValue", "collateral_value"):
327
+ collateral = _margin_float(row, field)
328
+ if collateral > 0.0:
329
+ break
330
+ return cash, collateral
331
+
332
+
301
333
  class FivePaisa(BrokerBase):
302
334
  """
303
335
  FivePaisa broker implementation with enhanced error handling and logging.
@@ -369,6 +401,38 @@ class FivePaisa(BrokerBase):
369
401
  context = create_error_context(broker_type="FivePaisa", config_keys=list(kwargs.keys()), error=str(e))
370
402
  raise BrokerConnectionError(f"Failed to initialize FivePaisa broker: {str(e)}", context)
371
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
+
372
436
  def _configure_api_proxy_session(self, force_refresh: bool = False):
373
437
  try:
374
438
  if self.api is None or not hasattr(self.api, "session"):
@@ -1207,26 +1271,10 @@ class FivePaisa(BrokerBase):
1207
1271
  if not margin_data or len(margin_data) == 0:
1208
1272
  raise MarketDataError("No margin data available")
1209
1273
 
1210
- ledger_balance = float(margin_data[0]["Ledgerbalance"])
1211
- funds_payln = float(margin_data[0]["FundsPayln"])
1212
- cash = ledger_balance + funds_payln
1213
-
1214
- # Get collateral value (FivePaisa has both MF and regular collateral)
1215
- collateral = 0.0
1216
- try:
1217
- mf_collateral = float(margin_data[0].get("MFCollateralValueAfterHaircut", 0))
1218
- regular_collateral = float(margin_data[0].get("CollateralValueAfterHairCut", 0))
1219
- collateral = mf_collateral + regular_collateral
1220
- except (ValueError, TypeError, KeyError):
1221
- # If specific fields not found, try alternative field names
1222
- collateral_fields = ["Collateral", "collateral", "CollateralValue", "collateral_value"]
1223
- for field in collateral_fields:
1224
- if field in margin_data[0]:
1225
- try:
1226
- collateral = float(margin_data[0][field])
1227
- break
1228
- except (ValueError, TypeError):
1229
- continue
1274
+ row = margin_data[0]
1275
+ cash, collateral = _cash_and_collateral_from_margin(row)
1276
+ ledger_balance = float(row["Ledgerbalance"])
1277
+ funds_payln = _margin_float(row, "FundsPayln")
1230
1278
 
1231
1279
  used = 0.0
1232
1280
  used_fields = [
@@ -1880,7 +1928,8 @@ class FivePaisa(BrokerBase):
1880
1928
  order.price_type = new_price
1881
1929
  order.quantity = new_quantity
1882
1930
  order.price = new_price
1883
- order.broker_order_id = str(out.get("BrokerOrderID", ""))
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)
1884
1933
 
1885
1934
  # Get updated order info
1886
1935
  try:
@@ -1894,7 +1943,7 @@ class FivePaisa(BrokerBase):
1894
1943
 
1895
1944
  # Update broker order ID
1896
1945
  try:
1897
- self._update_broker_order_id(order.internal_order_id, broker_order_id, out["BrokerOrderID"])
1946
+ self._update_broker_order_id(order.internal_order_id, broker_order_id, order.broker_order_id)
1898
1947
  except Exception as e:
1899
1948
  trading_logger.log_warning(
1900
1949
  "Failed to update broker order ID",
@@ -2078,12 +2127,13 @@ class FivePaisa(BrokerBase):
2078
2127
 
2079
2128
  if out and "BrokerOrderID" in out:
2080
2129
  # Convert broker_order_id to string for consistency
2081
- order.broker_order_id = str(out["BrokerOrderID"])
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)
2082
2132
 
2083
2133
  # Update broker order ID
2084
2134
  try:
2085
2135
  self._update_broker_order_id(
2086
- order.internal_order_id, broker_order_id, out["BrokerOrderID"]
2136
+ order.internal_order_id, broker_order_id, order.broker_order_id
2087
2137
  )
2088
2138
  except Exception as e:
2089
2139
  trading_logger.log_warning(
@@ -2205,6 +2255,12 @@ class FivePaisa(BrokerBase):
2205
2255
  ValidationError: If parameters are invalid
2206
2256
  RedisError: If Redis operations fail
2207
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
2208
2264
  try:
2209
2265
  trading_logger.log_debug(
2210
2266
  "Updating broker order ID",
@@ -2227,8 +2283,8 @@ class FivePaisa(BrokerBase):
2227
2283
  new_exit_keys = None
2228
2284
 
2229
2285
  # Check if broker_order_id is in entry_keys
2230
- if entry_keys and str(old_broker_order_id) in entry_keys:
2231
- new_entry_keys = entry_keys.replace(str(old_broker_order_id), str(new_broker_order_id))
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())
2232
2288
  trading_logger.log_debug(
2233
2289
  "Found broker order ID in entry keys",
2234
2290
  {
@@ -2245,8 +2301,8 @@ class FivePaisa(BrokerBase):
2245
2301
  context = create_error_context(internal_order_id=internal_order_id, error=str(e))
2246
2302
  raise RedisError(f"Failed to retrieve exit keys: {str(e)}", context)
2247
2303
 
2248
- if exit_keys and str(old_broker_order_id) in exit_keys:
2249
- new_exit_keys = exit_keys.replace(str(old_broker_order_id), str(new_broker_order_id))
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())
2250
2306
  trading_logger.log_debug(
2251
2307
  "Found broker order ID in exit keys",
2252
2308
  {
@@ -2669,7 +2725,7 @@ class FivePaisa(BrokerBase):
2669
2725
  ]
2670
2726
  if self.api is None:
2671
2727
  raise BrokerConnectionError("API client not initialized")
2672
- trade_info = self.api.fetch_trade_info(req_list_)
2728
+ trade_info = self._fetch_trade_info(req_list_)
2673
2729
  if trade_info is None:
2674
2730
  return get_orderinfo_from_orders(order.exch_order_id, order, broker_order_id)
2675
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
- actual_positions = get_open_position_by_order(broker, internal_order_id)
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]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tradingapi
3
- Version: 0.5.4
3
+ Version: 0.5.6
4
4
  Summary: Trade integration with brokers
5
5
  Author-email: Pankaj Sharma <sharma.pankaj.kumar@gmail.com>
6
6
  License-Expression: MIT
@@ -5,8 +5,10 @@ tests/test_calculate_delta_realtime_quotes.py
5
5
  tests/test_calculate_mtm.py
6
6
  tests/test_dhan_historical_diagnostics.py
7
7
  tests/test_find_option_with_delta.py
8
+ tests/test_fivepaisa_available_capital.py
8
9
  tests/test_fivepaisa_historical_recovery.py
9
10
  tests/test_fivepaisa_stream_reconnect.py
11
+ tests/test_fivepaisa_trade_info.py
10
12
  tests/test_flattrade_symbology.py
11
13
  tests/test_market_hours_config.py
12
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