dnse-sdk-openapi 2.0.0__tar.gz → 2.3.0__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 (93) hide show
  1. {dnse_sdk_openapi-2.0.0/dnse_sdk_openapi.egg-info → dnse_sdk_openapi-2.3.0}/PKG-INFO +14 -1
  2. dnse_sdk_openapi-2.0.0/PKG-INFO → dnse_sdk_openapi-2.3.0/README.md +13 -6
  3. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/api/client.py +93 -1
  4. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/client.py +16 -1
  5. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/models.py +45 -0
  6. dnse_sdk_openapi-2.0.0/README.md → dnse_sdk_openapi-2.3.0/dnse_sdk_openapi.egg-info/PKG-INFO +19 -0
  7. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse_sdk_openapi.egg-info/SOURCES.txt +26 -0
  8. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse_sdk_openapi.egg-info/top_level.txt +1 -0
  9. dnse_sdk_openapi-2.3.0/examples/env_util.py +37 -0
  10. dnse_sdk_openapi-2.3.0/examples/indicators.py +152 -0
  11. dnse_sdk_openapi-2.3.0/examples/log_util.py +20 -0
  12. dnse_sdk_openapi-2.3.0/examples/market_utils.py +14 -0
  13. dnse_sdk_openapi-2.3.0/examples/otp_email.py +190 -0
  14. dnse_sdk_openapi-2.3.0/examples/position_manager.py +246 -0
  15. dnse_sdk_openapi-2.3.0/examples/position_store.py +48 -0
  16. dnse_sdk_openapi-2.3.0/examples/reference/orders-email-otp.py +146 -0
  17. dnse_sdk_openapi-2.3.0/examples/reference/orders-smart-otp.py +145 -0
  18. dnse_sdk_openapi-2.3.0/examples/strategy_base.py +68 -0
  19. dnse_sdk_openapi-2.3.0/examples/strategy_ichimoku.py +122 -0
  20. dnse_sdk_openapi-2.3.0/examples/strategy_price_action.py +66 -0
  21. dnse_sdk_openapi-2.3.0/examples/strategy_scalping.py +118 -0
  22. dnse_sdk_openapi-2.3.0/examples/token_store.py +114 -0
  23. dnse_sdk_openapi-2.3.0/examples/use-cases/auto-trader.py +316 -0
  24. dnse_sdk_openapi-2.3.0/examples/use-cases/market-data.py +51 -0
  25. dnse_sdk_openapi-2.3.0/examples/use-cases/order-history.py +67 -0
  26. dnse_sdk_openapi-2.3.0/examples/use-cases/place-a-trade.py +230 -0
  27. dnse_sdk_openapi-2.3.0/examples/use-cases/portfolio-check.py +51 -0
  28. dnse_sdk_openapi-2.3.0/marketdata-api/get_market_index.py +30 -0
  29. dnse_sdk_openapi-2.3.0/marketdata-api/get_trades_volume_profile.py +28 -0
  30. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/pyproject.toml +1 -1
  31. dnse_sdk_openapi-2.3.0/trading-api/get_account_pnl_configs.py +25 -0
  32. dnse_sdk_openapi-2.3.0/trading-api/get_loans.py +33 -0
  33. dnse_sdk_openapi-2.3.0/trading-api/patch_account_pnl_configs.py +44 -0
  34. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/post_order.py +0 -2
  35. dnse_sdk_openapi-2.3.0/trading-api/reverse_position.py +26 -0
  36. dnse_sdk_openapi-2.3.0/websocket-marketdata/market_index_influence.py +51 -0
  37. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/ohlc_closed.py +4 -4
  38. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/broker-api/get_list_care_by.py +0 -0
  39. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/__init__.py +0 -0
  40. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/api/_version.py +0 -0
  41. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/api/common.py +0 -0
  42. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/_version.py +0 -0
  43. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/auth.py +0 -0
  44. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/connection.py +0 -0
  45. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/encoding.py +0 -0
  46. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/exceptions.py +0 -0
  47. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse/websocket/py.typed +0 -0
  48. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/dnse_sdk_openapi.egg-info/dependency_links.txt +0 -0
  49. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_expected_price.py +0 -0
  50. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_foreign_trading.py +0 -0
  51. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_instruments.py +0 -0
  52. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_lastest_session.py +0 -0
  53. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_latest_quote.py +0 -0
  54. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_latest_trade.py +0 -0
  55. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_ohlc.py +0 -0
  56. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_quotes.py +0 -0
  57. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_security_definition.py +0 -0
  58. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_trades.py +0 -0
  59. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/marketdata-api/get_working_dates.py +0 -0
  60. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/setup.cfg +0 -0
  61. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/cancel_order.py +0 -0
  62. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/close_position.py +0 -0
  63. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/create_trading_token.py +0 -0
  64. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_accounts.py +0 -0
  65. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_balances.py +0 -0
  66. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_close_price.py +0 -0
  67. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_corporate_action_history.py +0 -0
  68. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_execution_detail.py +0 -0
  69. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_loan_packages.py +0 -0
  70. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_order_detail.py +0 -0
  71. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_order_history.py +0 -0
  72. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_orders.py +0 -0
  73. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_position_by_id.py +0 -0
  74. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_position_pnl_configs.py +0 -0
  75. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_positions.py +0 -0
  76. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/get_ppse.py +0 -0
  77. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/post_position_pnl_configs.py +0 -0
  78. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/put_order.py +0 -0
  79. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/trading-api/send_email_otp.py +0 -0
  80. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/estimated_market_index.py +0 -0
  81. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/expected_price.py +0 -0
  82. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/foreign_investor.py +0 -0
  83. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/market_index.py +0 -0
  84. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/ohlc.py +0 -0
  85. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/quote.py +0 -0
  86. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/sec_def.py +0 -0
  87. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/session.py +0 -0
  88. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/trade.py +0 -0
  89. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-marketdata/trade_extra.py +0 -0
  90. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-trading/broker_order.py +0 -0
  91. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-trading/broker_position.py +0 -0
  92. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-trading/order.py +0 -0
  93. {dnse_sdk_openapi-2.0.0 → dnse_sdk_openapi-2.3.0}/websocket-trading/position.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dnse-sdk-openapi
3
- Version: 2.0.0
3
+ Version: 2.3.0
4
4
  Summary: DNSE OpenAPI SDK
5
5
  Description-Content-Type: text/markdown
6
6
 
@@ -96,8 +96,11 @@ python sdk/python/api/get_accounts.py
96
96
  | `get_positions.py` | Demonstrates how to retrieve current holding positions. |
97
97
  | `get_positions_by_id.py` | Demonstrates how to retrieve detailed information of a specific position (by ID). |
98
98
  | `get_position_pnl_configs.py` | Demonstrates how to retrieve PnL configs of a derivative position (by ID). |
99
+ | `get_account_pnl_configs.py` | Demonstrates how to retrieve PnL configs of a derivative sub-account. |
99
100
  | `post_position_pnl_configs.py` | Demonstrates how to create or update PnL configs of a derivative position (by ID). |
101
+ | `patch_account_pnl_configs.py` | Demonstrates how to update PnL configs of a derivative sub-account. |
100
102
  | `close_position.py` | Demonstrates how to close an existing position (by ID). |
103
+ | `reverse_position.py` | Demonstrates how to reverse an existing derivative position (by ID). |
101
104
  | `send_email_otp.py` | Demonstrates how to request an OTP sent to your registered email. The OTP is required for generating a trading token. |
102
105
  | `create_trading_token.py` | Demonstrates how to generate a Trading Token required for order placement. |
103
106
  | `post_order.py` | Demonstrates how to submit a new trading order. |
@@ -129,3 +132,13 @@ python sdk/python/api/get_accounts.py
129
132
  | `expected_price.py` | Demonstrates how to receive expected price data during ATO and ATC sessions. |
130
133
  | `foreign_investor.py` | Demonstrates how to receive foreign investor trading data. |
131
134
  | `market_index.py` | Demonstrates how to receive market index data. |
135
+
136
+ ### WebSocket Trading Events
137
+
138
+ Use `TradingClient.subscribe_order_event()` for both ordinary and conditional
139
+ order updates. Conditional orders use the existing
140
+ `order.{marketType}.{encoding}` subscription and are delivered as `Order`
141
+ objects. For conditional orders, `orderCategory`, `stopPrice`,
142
+ `stopOrderPrice`, `conditionOperator`, `durationType`, `durationDateTime`,
143
+ `errorMessage`, and `externalOrderId` are populated when provided; they are
144
+ `None` for ordinary-order payloads.
@@ -1,9 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: dnse-sdk-openapi
3
- Version: 2.0.0
4
- Summary: DNSE OpenAPI SDK
5
- Description-Content-Type: text/markdown
6
-
7
1
  # DNSE OpenAPI Python SDK
8
2
 
9
3
  Official Python SDK for integrating with DNSE OpenAPI.
@@ -96,8 +90,11 @@ python sdk/python/api/get_accounts.py
96
90
  | `get_positions.py` | Demonstrates how to retrieve current holding positions. |
97
91
  | `get_positions_by_id.py` | Demonstrates how to retrieve detailed information of a specific position (by ID). |
98
92
  | `get_position_pnl_configs.py` | Demonstrates how to retrieve PnL configs of a derivative position (by ID). |
93
+ | `get_account_pnl_configs.py` | Demonstrates how to retrieve PnL configs of a derivative sub-account. |
99
94
  | `post_position_pnl_configs.py` | Demonstrates how to create or update PnL configs of a derivative position (by ID). |
95
+ | `patch_account_pnl_configs.py` | Demonstrates how to update PnL configs of a derivative sub-account. |
100
96
  | `close_position.py` | Demonstrates how to close an existing position (by ID). |
97
+ | `reverse_position.py` | Demonstrates how to reverse an existing derivative position (by ID). |
101
98
  | `send_email_otp.py` | Demonstrates how to request an OTP sent to your registered email. The OTP is required for generating a trading token. |
102
99
  | `create_trading_token.py` | Demonstrates how to generate a Trading Token required for order placement. |
103
100
  | `post_order.py` | Demonstrates how to submit a new trading order. |
@@ -129,3 +126,13 @@ python sdk/python/api/get_accounts.py
129
126
  | `expected_price.py` | Demonstrates how to receive expected price data during ATO and ATC sessions. |
130
127
  | `foreign_investor.py` | Demonstrates how to receive foreign investor trading data. |
131
128
  | `market_index.py` | Demonstrates how to receive market index data. |
129
+
130
+ ### WebSocket Trading Events
131
+
132
+ Use `TradingClient.subscribe_order_event()` for both ordinary and conditional
133
+ order updates. Conditional orders use the existing
134
+ `order.{marketType}.{encoding}` subscription and are delivered as `Order`
135
+ objects. For conditional orders, `orderCategory`, `stopPrice`,
136
+ `stopOrderPrice`, `conditionOperator`, `durationType`, `durationDateTime`,
137
+ `errorMessage`, and `externalOrderId` are populated when provided; they are
138
+ `None` for ordinary-order payloads.
@@ -31,7 +31,7 @@ class DNSEClient:
31
31
  maxsize=10, # Số connections tối đa mỗi pool
32
32
  block=False, # Không block khi pool đầy
33
33
  timeout=urllib3.Timeout(connect=30.0, read=60.0),
34
- cert_reqs = 'CERT_NONE', # Không yêu cầu certificate
34
+ # cert_reqs = 'CERT_NONE', # Không yêu cầu certificate
35
35
  assert_hostname = False # Không kiểm tra hostname
36
36
  )
37
37
 
@@ -52,6 +52,41 @@ class DNSEClient:
52
52
  dry_run=dry_run,
53
53
  )
54
54
 
55
+ def get_loans(
56
+ self,
57
+ account_no,
58
+ market_type,
59
+ disbursement_from=None,
60
+ disbursement_to=None,
61
+ due_date_from=None,
62
+ due_date_to=None,
63
+ position_id=None,
64
+ page_index=None,
65
+ page_size=None,
66
+ dry_run=False,
67
+ ):
68
+ query = {"marketType": market_type}
69
+ if disbursement_from is not None:
70
+ query["disbursementFrom"] = disbursement_from
71
+ if disbursement_to is not None:
72
+ query["disbursementTo"] = disbursement_to
73
+ if due_date_from is not None:
74
+ query["dueDateFrom"] = due_date_from
75
+ if due_date_to is not None:
76
+ query["dueDateTo"] = due_date_to
77
+ if position_id is not None:
78
+ query["positionId"] = position_id
79
+ if page_index is not None:
80
+ query["pageIndex"] = page_index
81
+ if page_size is not None:
82
+ query["pageSize"] = page_size
83
+ return self._request(
84
+ "GET",
85
+ f"/accounts/{account_no}/loans",
86
+ query=query,
87
+ dry_run=dry_run,
88
+ )
89
+
55
90
  def get_positions(self, account_no, market_type, dry_run=False):
56
91
  return self._request(
57
92
  "GET",
@@ -78,6 +113,22 @@ class DNSEClient:
78
113
  dry_run=dry_run,
79
114
  )
80
115
 
116
+ def get_account_pnl_configs(self, account_no, market_type, version=None, dry_run=False):
117
+ return self._request("GET",
118
+ f"/accounts/{account_no}/pnl-configs",
119
+ query={"marketType": market_type},
120
+ version=version,
121
+ dry_run=dry_run)
122
+
123
+ def patch_account_pnl_configs(self, account_no, market_type, payload, trading_token, version=None, dry_run=False):
124
+ return self._request("PATCH",
125
+ f"/accounts/{account_no}/pnl-configs",
126
+ query={"marketType": market_type},
127
+ body=payload,
128
+ headers={"trading-token": trading_token},
129
+ version=version,
130
+ dry_run=dry_run)
131
+
81
132
  def post_position_pnl_configs(self, market_type, position_id, payload, trading_token, version=None, dry_run=False):
82
133
  headers = {"trading-token": trading_token}
83
134
  return self._request(
@@ -244,6 +295,17 @@ class DNSEClient:
244
295
  dry_run=dry_run,
245
296
  )
246
297
 
298
+ def get_trades_volume_profile(self, symbol, from_date, to_date, board_id=None, dry_run=False):
299
+ query = {"from": from_date, "to": to_date}
300
+ if board_id is not None:
301
+ query["board_id"] = board_id
302
+ return self._request(
303
+ "GET",
304
+ f"/price/{symbol}/trades/volume-profile",
305
+ query=query,
306
+ dry_run=dry_run,
307
+ )
308
+
247
309
  def get_expected_price(self, symbol, board_id=None, from_date=None, to_date=None, limit=None, order = None, next_page_token=None, dry_run=False):
248
310
  query = {}
249
311
  if board_id is not None:
@@ -307,6 +369,25 @@ class DNSEClient:
307
369
  dry_run=dry_run,
308
370
  )
309
371
 
372
+ def get_market_index(self, index_name, from_date=None, to_date=None, limit=None, order=None, next_page_token=None, dry_run=False):
373
+ query = {}
374
+ if from_date is not None:
375
+ query["from"] = from_date
376
+ if to_date is not None:
377
+ query["to"] = to_date
378
+ if limit is not None:
379
+ query["limit"] = limit
380
+ if order is not None:
381
+ query["order"] = order
382
+ if next_page_token is not None:
383
+ query["nextPageToken"] = next_page_token
384
+ return self._request(
385
+ "GET",
386
+ f"/price/{index_name}/market-index",
387
+ query=query if query else None,
388
+ dry_run=dry_run,
389
+ )
390
+
310
391
  def get_instruments(self, symbol=None, market_id=None, security_group_id=None, index_name=None, limit=None, page=None, version=None, dry_run=False):
311
392
  query = {}
312
393
  if symbol is not None:
@@ -475,6 +556,17 @@ class DNSEClient:
475
556
  dry_run=dry_run,
476
557
  )
477
558
 
559
+ def reverse_position(self, position_id, trading_token, dry_run=False):
560
+ headers = {"trading-token": trading_token}
561
+ return self._request(
562
+ "POST",
563
+ f"/positions/{position_id}/reverse",
564
+ query={"marketType": "DERIVATIVE"},
565
+ headers=headers,
566
+ version="2026-01-01",
567
+ dry_run=dry_run,
568
+ )
569
+
478
570
  def _request(self, method, path, query=None, body=None, headers=None, version=None, dry_run=False):
479
571
  debug = os.getenv("DEBUG", "").lower() == "true"
480
572
  url = self._build_url(path, query)
@@ -25,7 +25,7 @@ from .exceptions import (
25
25
  ConnectionClosed,
26
26
  )
27
27
  from .models import Trade, Quote, Ohlc, Order, AccountUpdate, ExpectedPrice, SecurityDefinition, TradeExtra, \
28
- MarketIndex, ForeignInvestor, Position, EstimatedMarketIndex, Session
28
+ MarketIndex, ForeignInvestor, Position, EstimatedMarketIndex, Session, IndexInfluence
29
29
 
30
30
  logger = logging.getLogger(__name__)
31
31
  logger.setLevel(logging.INFO)
@@ -52,6 +52,7 @@ _MSG_TYPE_MAP = {
52
52
  "ep": ("position_event", Position, "position"),
53
53
  "mi": ("market_index", MarketIndex, None),
54
54
  "emi": ("estimated_market_index", EstimatedMarketIndex, "marketIndex"),
55
+ "ii": ("market_index_influence", IndexInfluence, None),
55
56
  "a": ("account", AccountUpdate, None),
56
57
  "f": ("foreign", ForeignInvestor, None),
57
58
  "s": ("session", Session, None),
@@ -348,6 +349,20 @@ class TradingClient:
348
349
  if on_estimated_market_index:
349
350
  self.on("estimated_market_index", on_estimated_market_index)
350
351
 
352
+ async def subscribe_market_index_influence(
353
+ self, index_name: str, resolution: int = 1,
354
+ on_market_index_influence: Optional[Callable[[IndexInfluence], None]] = None, encoding="json"
355
+ ) -> None:
356
+ channel = f"market_index_influence.{index_name}.{resolution}.json"
357
+ if encoding == "msgpack":
358
+ channel = f"market_index_influence.{index_name}.{resolution}.msgpack"
359
+ # Index name is encoded in the channel; symbols would create an
360
+ # additional server-side suffix and no longer match the publisher.
361
+ await self._subscribe_channel(channel, [])
362
+
363
+ if on_market_index_influence:
364
+ self.on("market_index_influence", on_market_index_influence)
365
+
351
366
  async def subscribe_quotes(
352
367
  self, symbols: List[str], on_quote: Optional[Callable[[Quote], None]] = None, encoding="json", board_id=None
353
368
  ) -> None:
@@ -54,6 +54,7 @@ def parse_timestamp(v: Any, date_only: bool = False) -> Optional[str]:
54
54
  except Exception:
55
55
  return None
56
56
 
57
+
57
58
  @dataclass
58
59
  class PriceLevel:
59
60
  price: float
@@ -296,6 +297,50 @@ class EstimatedMarketIndex:
296
297
  )
297
298
 
298
299
 
300
+ @dataclass
301
+ class IndexInfluenceItem:
302
+ time: Optional[str]
303
+ symbol: str
304
+ influence: float
305
+ influenceRatio: float
306
+ proportion: float
307
+ changeRatio: float
308
+ changeValue: float
309
+ price: float
310
+ grossTradeAmount: float
311
+ totalVolumeTraded: float
312
+
313
+ @classmethod
314
+ def from_dict(cls, data: Dict[str, Any]) -> "IndexInfluenceItem":
315
+ return cls(
316
+ time=data.get("time"),
317
+ symbol=data.get("symbol"),
318
+ influence=data.get("influence"),
319
+ influenceRatio=data.get("influenceRatio"),
320
+ proportion=data.get("proportion"),
321
+ changeRatio=data.get("changeRatio"),
322
+ changeValue=data.get("changeValue"),
323
+ price=data.get("price"),
324
+ grossTradeAmount=data.get("grossTradeAmount"),
325
+ totalVolumeTraded=data.get("totalVolumeTraded"),
326
+ )
327
+
328
+
329
+ @dataclass
330
+ class IndexInfluence:
331
+ index_name: Optional[str]
332
+ data: List[IndexInfluenceItem]
333
+ receivedAt: Optional[float] = field(default=None, repr=False)
334
+
335
+ @classmethod
336
+ def from_dict(cls, data: Dict[str, Any]) -> "IndexInfluence":
337
+ return cls(
338
+ index_name=data.get("index_name"),
339
+ data=[IndexInfluenceItem.from_dict(item) for item in (data.get("Data") or data.get("data") or [])],
340
+ receivedAt=data.get("_receivedAt"),
341
+ )
342
+
343
+
299
344
  @dataclass
300
345
  class ExpectedPrice:
301
346
  marketId: str
@@ -1,3 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: dnse-sdk-openapi
3
+ Version: 2.3.0
4
+ Summary: DNSE OpenAPI SDK
5
+ Description-Content-Type: text/markdown
6
+
1
7
  # DNSE OpenAPI Python SDK
2
8
 
3
9
  Official Python SDK for integrating with DNSE OpenAPI.
@@ -90,8 +96,11 @@ python sdk/python/api/get_accounts.py
90
96
  | `get_positions.py` | Demonstrates how to retrieve current holding positions. |
91
97
  | `get_positions_by_id.py` | Demonstrates how to retrieve detailed information of a specific position (by ID). |
92
98
  | `get_position_pnl_configs.py` | Demonstrates how to retrieve PnL configs of a derivative position (by ID). |
99
+ | `get_account_pnl_configs.py` | Demonstrates how to retrieve PnL configs of a derivative sub-account. |
93
100
  | `post_position_pnl_configs.py` | Demonstrates how to create or update PnL configs of a derivative position (by ID). |
101
+ | `patch_account_pnl_configs.py` | Demonstrates how to update PnL configs of a derivative sub-account. |
94
102
  | `close_position.py` | Demonstrates how to close an existing position (by ID). |
103
+ | `reverse_position.py` | Demonstrates how to reverse an existing derivative position (by ID). |
95
104
  | `send_email_otp.py` | Demonstrates how to request an OTP sent to your registered email. The OTP is required for generating a trading token. |
96
105
  | `create_trading_token.py` | Demonstrates how to generate a Trading Token required for order placement. |
97
106
  | `post_order.py` | Demonstrates how to submit a new trading order. |
@@ -123,3 +132,13 @@ python sdk/python/api/get_accounts.py
123
132
  | `expected_price.py` | Demonstrates how to receive expected price data during ATO and ATC sessions. |
124
133
  | `foreign_investor.py` | Demonstrates how to receive foreign investor trading data. |
125
134
  | `market_index.py` | Demonstrates how to receive market index data. |
135
+
136
+ ### WebSocket Trading Events
137
+
138
+ Use `TradingClient.subscribe_order_event()` for both ordinary and conditional
139
+ order updates. Conditional orders use the existing
140
+ `order.{marketType}.{encoding}` subscription and are delivered as `Order`
141
+ objects. For conditional orders, `orderCategory`, `stopPrice`,
142
+ `stopOrderPrice`, `conditionOperator`, `durationType`, `durationDateTime`,
143
+ `errorMessage`, and `externalOrderId` are populated when provided; they are
144
+ `None` for ordinary-order payloads.
@@ -17,26 +17,49 @@ dnse_sdk_openapi.egg-info/PKG-INFO
17
17
  dnse_sdk_openapi.egg-info/SOURCES.txt
18
18
  dnse_sdk_openapi.egg-info/dependency_links.txt
19
19
  dnse_sdk_openapi.egg-info/top_level.txt
20
+ examples/env_util.py
21
+ examples/indicators.py
22
+ examples/log_util.py
23
+ examples/market_utils.py
24
+ examples/otp_email.py
25
+ examples/position_manager.py
26
+ examples/position_store.py
27
+ examples/strategy_base.py
28
+ examples/strategy_ichimoku.py
29
+ examples/strategy_price_action.py
30
+ examples/strategy_scalping.py
31
+ examples/token_store.py
32
+ examples/reference/orders-email-otp.py
33
+ examples/reference/orders-smart-otp.py
34
+ examples/use-cases/auto-trader.py
35
+ examples/use-cases/market-data.py
36
+ examples/use-cases/order-history.py
37
+ examples/use-cases/place-a-trade.py
38
+ examples/use-cases/portfolio-check.py
20
39
  marketdata-api/get_expected_price.py
21
40
  marketdata-api/get_foreign_trading.py
22
41
  marketdata-api/get_instruments.py
23
42
  marketdata-api/get_lastest_session.py
24
43
  marketdata-api/get_latest_quote.py
25
44
  marketdata-api/get_latest_trade.py
45
+ marketdata-api/get_market_index.py
26
46
  marketdata-api/get_ohlc.py
27
47
  marketdata-api/get_quotes.py
28
48
  marketdata-api/get_security_definition.py
29
49
  marketdata-api/get_trades.py
50
+ marketdata-api/get_trades_volume_profile.py
30
51
  marketdata-api/get_working_dates.py
31
52
  trading-api/cancel_order.py
32
53
  trading-api/close_position.py
33
54
  trading-api/create_trading_token.py
55
+ trading-api/get_account_pnl_configs.py
34
56
  trading-api/get_accounts.py
35
57
  trading-api/get_balances.py
36
58
  trading-api/get_close_price.py
37
59
  trading-api/get_corporate_action_history.py
38
60
  trading-api/get_execution_detail.py
39
61
  trading-api/get_loan_packages.py
62
+ trading-api/get_loans.py
40
63
  trading-api/get_order_detail.py
41
64
  trading-api/get_order_history.py
42
65
  trading-api/get_orders.py
@@ -44,14 +67,17 @@ trading-api/get_position_by_id.py
44
67
  trading-api/get_position_pnl_configs.py
45
68
  trading-api/get_positions.py
46
69
  trading-api/get_ppse.py
70
+ trading-api/patch_account_pnl_configs.py
47
71
  trading-api/post_order.py
48
72
  trading-api/post_position_pnl_configs.py
49
73
  trading-api/put_order.py
74
+ trading-api/reverse_position.py
50
75
  trading-api/send_email_otp.py
51
76
  websocket-marketdata/estimated_market_index.py
52
77
  websocket-marketdata/expected_price.py
53
78
  websocket-marketdata/foreign_investor.py
54
79
  websocket-marketdata/market_index.py
80
+ websocket-marketdata/market_index_influence.py
55
81
  websocket-marketdata/ohlc.py
56
82
  websocket-marketdata/ohlc_closed.py
57
83
  websocket-marketdata/quote.py
@@ -1,6 +1,7 @@
1
1
  broker-api
2
2
  dist
3
3
  dnse
4
+ examples
4
5
  marketdata-api
5
6
  trading-api
6
7
  websocket-marketdata
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for loading example configuration from .env files."""
3
+ import os
4
+
5
+ from log_util import log
6
+
7
+
8
+ def load_dotenv():
9
+ """Load KEY=VALUE lines from nearby .env files into os.environ.
10
+
11
+ Search order:
12
+ - current working directory
13
+ - examples/ (this file's directory)
14
+ - repo python/ root (parent of examples/)
15
+
16
+ Existing environment variables win over .env values.
17
+ """
18
+ here = os.path.dirname(os.path.abspath(__file__))
19
+ seen = set()
20
+ for directory in (os.getcwd(), here, os.path.dirname(here)):
21
+ path = os.path.join(directory, ".env")
22
+ if path in seen or not os.path.isfile(path):
23
+ continue
24
+ seen.add(path)
25
+ try:
26
+ with open(path, encoding="utf-8") as handle:
27
+ for raw in handle:
28
+ line = raw.strip()
29
+ if not line or line.startswith("#") or "=" not in line:
30
+ continue
31
+ if line.lower().startswith("export "):
32
+ line = line[len("export "):]
33
+ key, _, val = line.partition("=")
34
+ os.environ.setdefault(key.strip(), val.strip().strip('"').strip("'"))
35
+ log(f"Đã nạp .env từ {path}")
36
+ except OSError:
37
+ pass
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env python3
2
+ """Tiny pure-Python technical indicators for the demo strategies.
3
+
4
+ Standard-library only (no numpy/talib). Good enough for examples; for production
5
+ use a vetted TA library. Each function returns None when there isn't enough data.
6
+ """
7
+ from typing import List, Optional, Tuple
8
+
9
+
10
+ def rsi_series(closes: List[float], period: int = 14) -> List[float]:
11
+ """Wilder's RSI as a series (one value per bar from index `period` onward)."""
12
+ if len(closes) <= period:
13
+ return []
14
+ gains = losses = 0.0
15
+ for i in range(1, period + 1):
16
+ d = closes[i] - closes[i - 1]
17
+ gains += max(d, 0.0)
18
+ losses += max(-d, 0.0)
19
+ avg_gain, avg_loss = gains / period, losses / period
20
+
21
+ def _rsi(g, loss):
22
+ return 100.0 if loss == 0 else 100.0 - 100.0 / (1.0 + g / loss)
23
+
24
+ out = [_rsi(avg_gain, avg_loss)]
25
+ for i in range(period + 1, len(closes)):
26
+ d = closes[i] - closes[i - 1]
27
+ avg_gain = (avg_gain * (period - 1) + max(d, 0.0)) / period
28
+ avg_loss = (avg_loss * (period - 1) + max(-d, 0.0)) / period
29
+ out.append(_rsi(avg_gain, avg_loss))
30
+ return out
31
+
32
+
33
+ def rsi(closes: List[float], period: int = 14) -> Optional[float]:
34
+ """Wilder's RSI of the latest bar."""
35
+ series = rsi_series(closes, period)
36
+ return series[-1] if series else None
37
+
38
+
39
+ def ema_series(values: List[float], period: int) -> List[float]:
40
+ """EMA as a series (seeded with the SMA of the first `period` values)."""
41
+ if len(values) < period:
42
+ return []
43
+ k = 2.0 / (period + 1)
44
+ ema = sum(values[:period]) / period
45
+ out = [ema]
46
+ for v in values[period:]:
47
+ ema += k * (v - ema)
48
+ out.append(ema)
49
+ return out # out[-1] aligns with the latest bar
50
+
51
+
52
+ def macd_hist(closes: List[float], fast: int = 12, slow: int = 26, signal: int = 9
53
+ ) -> List[float]:
54
+ """MACD histogram (macd line - signal line) as a series aligned to the latest bar."""
55
+ fast_ema = ema_series(closes, fast)
56
+ slow_ema = ema_series(closes, slow)
57
+ if not fast_ema or not slow_ema:
58
+ return []
59
+ m = min(len(fast_ema), len(slow_ema))
60
+ macd_line = [fast_ema[-m + i] - slow_ema[-m + i] for i in range(m)]
61
+ sig = ema_series(macd_line, signal)
62
+ if not sig:
63
+ return []
64
+ k = min(len(macd_line), len(sig))
65
+ return [macd_line[-k + i] - sig[-k + i] for i in range(k)]
66
+
67
+
68
+ def atr(highs, lows, closes, period: int = 14) -> Optional[float]:
69
+ """Wilder's ATR of the latest bar."""
70
+ n = len(closes)
71
+ if n <= period:
72
+ return None
73
+ trs = [max(highs[i] - lows[i],
74
+ abs(highs[i] - closes[i - 1]),
75
+ abs(lows[i] - closes[i - 1])) for i in range(1, n)]
76
+ val = sum(trs[:period]) / period
77
+ for i in range(period, len(trs)):
78
+ val = (val * (period - 1) + trs[i]) / period
79
+ return val
80
+
81
+
82
+ def _wilder_smooth(values: List[float], period: int) -> List[float]:
83
+ """Wilder running sum smoothing (seed = sum of first `period`)."""
84
+ if len(values) < period:
85
+ return []
86
+ smoothed = [sum(values[:period])]
87
+ for i in range(period, len(values)):
88
+ smoothed.append(smoothed[-1] - smoothed[-1] / period + values[i])
89
+ return smoothed
90
+
91
+
92
+ def adx(highs, lows, closes, period: int = 14) -> Optional[float]:
93
+ """Wilder's ADX (trend strength) of the latest bar."""
94
+ n = len(closes)
95
+ if n <= 2 * period:
96
+ return None
97
+ trs, plus_dm, minus_dm = [], [], []
98
+ for i in range(1, n):
99
+ up = highs[i] - highs[i - 1]
100
+ down = lows[i - 1] - lows[i]
101
+ plus_dm.append(up if (up > down and up > 0) else 0.0)
102
+ minus_dm.append(down if (down > up and down > 0) else 0.0)
103
+ trs.append(max(highs[i] - lows[i],
104
+ abs(highs[i] - closes[i - 1]),
105
+ abs(lows[i] - closes[i - 1])))
106
+ atr = _wilder_smooth(trs, period)
107
+ pdm = _wilder_smooth(plus_dm, period)
108
+ mdm = _wilder_smooth(minus_dm, period)
109
+ dxs = []
110
+ for a, p, m in zip(atr, pdm, mdm):
111
+ if a == 0:
112
+ dxs.append(0.0)
113
+ continue
114
+ pdi, mdi = 100 * p / a, 100 * m / a
115
+ s = pdi + mdi
116
+ dxs.append(100 * abs(pdi - mdi) / s if s else 0.0)
117
+ if len(dxs) < period:
118
+ return sum(dxs) / len(dxs) if dxs else None
119
+ val = sum(dxs[:period]) / period
120
+ for i in range(period, len(dxs)):
121
+ val = (val * (period - 1) + dxs[i]) / period
122
+ return val
123
+
124
+
125
+ def _midpoint_at(highs, lows, end: int, period: int) -> float:
126
+ """(highest high + lowest low) / 2 over the `period` bars ending at index `end`."""
127
+ lo = end - period + 1
128
+ return (max(highs[lo:end + 1]) + min(lows[lo:end + 1])) / 2.0
129
+
130
+
131
+ def ichimoku(highs, lows, tenkan_p=9, kijun_p=26, senkou_b_p=52, displacement=26
132
+ ) -> Optional[Tuple[float, float, float, float]]:
133
+ """Return (tenkan, kijun, senkou_a, senkou_b) at the latest bar — full Ichimoku.
134
+
135
+ Tenkan and Kijun are the current conversion/base lines. Senkou A/B are the
136
+ *cloud under the current price*: the leading spans are plotted `displacement`
137
+ bars into the future, so the cloud aligned with "now" is the one computed
138
+ `displacement` bars ago. We therefore evaluate the spans at index
139
+ (n - 1 - displacement), i.e. with the standard 26-period forward shift.
140
+
141
+ Returns None until there is enough history (senkou_b_p + displacement bars).
142
+ """
143
+ n = len(highs)
144
+ past = n - 1 - displacement # bar whose leading spans display at "now"
145
+ if past < senkou_b_p - 1:
146
+ return None
147
+ tenkan = _midpoint_at(highs, lows, n - 1, tenkan_p)
148
+ kijun = _midpoint_at(highs, lows, n - 1, kijun_p)
149
+ senkou_a = (_midpoint_at(highs, lows, past, tenkan_p)
150
+ + _midpoint_at(highs, lows, past, kijun_p)) / 2.0
151
+ senkou_b = _midpoint_at(highs, lows, past, senkou_b_p)
152
+ return tenkan, kijun, senkou_a, senkou_b
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env python3
2
+ """Tiny logging helper: print with the current time prefixed.
3
+
4
+ Standard library only (`datetime`) — no external logging dependency.
5
+ The timestamp is Vietnam local time (UTC+7).
6
+ """
7
+ from datetime import datetime, timedelta, timezone
8
+
9
+ _VN_TZ = timezone(timedelta(hours=7))
10
+
11
+
12
+ def now_str():
13
+ """Current time as 'YYYY-MM-DD HH:MM:SS,mmm' (VN, UTC+7) — matches the WS logs."""
14
+ dt = datetime.now(_VN_TZ)
15
+ return dt.strftime("%Y-%m-%d %H:%M:%S") + f",{dt.microsecond // 1000:03d}"
16
+
17
+
18
+ def log(*args, **kwargs):
19
+ """Like print(), but prefixed with the current [HH:MM:SS] time."""
20
+ print(f"[{now_str()}]", *args, **kwargs)
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env python3
2
+ """Small shared market helpers for the examples."""
3
+
4
+
5
+ def to_order_price(market_type, price):
6
+ """Convert a secdef/stream price into the unit the order API expects.
7
+
8
+ STOCK prices are quoted in thousands of VND, but the order API wants VND,
9
+ so multiply by 1000 (e.g. 23.1 -> 23100). DERIVATIVE (index futures) prices
10
+ are index points and are sent unchanged.
11
+ """
12
+ if market_type == "STOCK":
13
+ return int(round(price * 1000))
14
+ return price