HedgeTech 0.4.0b0__tar.gz → 0.4.1__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 (44) hide show
  1. hedgetech-0.4.1/HedgeTech/EmsEngine/__ime/__AsyncClient.py +855 -0
  2. hedgetech-0.4.1/HedgeTech/EmsEngine/__ime/__SyncClient.py +846 -0
  3. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__tse_ifb/__AsyncClient.py +5 -4
  4. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__tse_ifb/__SyncClient.py +5 -4
  5. hedgetech-0.4.1/HedgeTech.egg-info/PKG-INFO +2224 -0
  6. hedgetech-0.4.1/PKG-INFO +2224 -0
  7. hedgetech-0.4.1/README.md +2004 -0
  8. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/pyproject.toml +2 -4
  9. hedgetech-0.4.0b0/HedgeTech/EmsEngine/__ime/__AsyncClient.py +0 -414
  10. hedgetech-0.4.0b0/HedgeTech/EmsEngine/__ime/__SyncClient.py +0 -405
  11. hedgetech-0.4.0b0/HedgeTech.egg-info/PKG-INFO +0 -597
  12. hedgetech-0.4.0b0/PKG-INFO +0 -597
  13. hedgetech-0.4.0b0/README.md +0 -376
  14. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/Auth/__AuthAsyncClient.py +0 -0
  15. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/Auth/__AuthSyncClient.py +0 -0
  16. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/Auth/__init__.py +0 -0
  17. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/Auth/__utils/__RetriableAsyncClient.py +0 -0
  18. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/Auth/__utils/__RetriableSyncClient.py +0 -0
  19. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/Auth/__utils/__init__.py +0 -0
  20. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__ime/__AsyncClient.py +0 -0
  21. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__ime/__SyncClient.py +0 -0
  22. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__ime/__init__.py +0 -0
  23. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__ime/__io_types/__init__.py +0 -0
  24. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__ime/__io_types/__response.py +0 -0
  25. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__init__.py +0 -0
  26. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__tse_ifb/__AsyncClient.py +0 -0
  27. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__tse_ifb/__SyncClient.py +0 -0
  28. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__tse_ifb/__init__.py +0 -0
  29. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__tse_ifb/__io_types/__init__.py +0 -0
  30. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/DataEngine/__tse_ifb/__io_types/__response.py +0 -0
  31. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__ime/__init__.py +0 -0
  32. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__ime/__io_types/__init__.py +0 -0
  33. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__ime/__io_types/__response.py +0 -0
  34. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__init__.py +0 -0
  35. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__tse_ifb/__init__.py +0 -0
  36. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__tse_ifb/__io_types/__init__.py +0 -0
  37. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech/EmsEngine/__tse_ifb/__io_types/__response.py +0 -0
  38. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech.egg-info/SOURCES.txt +0 -0
  39. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech.egg-info/dependency_links.txt +0 -0
  40. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech.egg-info/requires.txt +0 -0
  41. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/HedgeTech.egg-info/top_level.txt +0 -0
  42. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/LICENSE +0 -0
  43. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/NOTICE +0 -0
  44. {hedgetech-0.4.0b0 → hedgetech-0.4.1}/setup.cfg +0 -0
@@ -0,0 +1,855 @@
1
+ # ========================================|======================================== #
2
+ # Imports #
3
+ # ========================================|======================================== #
4
+
5
+ from typing import (
6
+ Literal,
7
+ )
8
+ from .__io_types import (
9
+ HexUUID,
10
+ OrderStatus,
11
+ )
12
+ from HedgeTech.Auth import AuthAsyncClient
13
+ from PIL.Image import open as image_open
14
+ from PIL.ImageFile import ImageFile
15
+ from io import BytesIO
16
+ from asyncio import sleep
17
+ from uuid import uuid4
18
+
19
+ # ========================================|======================================== #
20
+ # Class Definitions #
21
+ # ========================================|======================================== #
22
+ class Order:
23
+ """
24
+ Represents a single trading order in EMS Engine (IME).
25
+
26
+ This class provides methods to send, edit, check status,
27
+ and delete an order after creation.
28
+
29
+ An Order instance is created via the ``Buy_by_ContractName``, ``Sell_by_ContractName``,
30
+ ``Buy_by_ContractId`` and ``Sell_by_ContractId`` methods of `EmsEngine_Ime_AsyncClient`.
31
+ Creating an ``Order`` does NOT send anything to the exchange: you must call
32
+ ``await order.send()``.
33
+
34
+ Typical life cycle:
35
+ 1. ``order = await client.Buy_by_ContractName(...)``: build the order (nothing is sent yet).
36
+ 2. ``await order.send()``: submit it. On success ``OrderId`` is set.
37
+ 3. ``await order.Status()``, ``await order.Edit(...)`` or ``await order.Delete()``:
38
+ follow, modify or cancel the submitted order.
39
+
40
+ Note:
41
+ ``send``, ``Edit``, ``Status`` and ``Delete`` never raise. Every error (a non-200 response,
42
+ a network failure, an unexpected response body, ...) is swallowed and the method just returns
43
+ ``None`` (the catch is a bare ``except``, so even ``asyncio.CancelledError`` is swallowed).
44
+ ``send``, ``Edit`` and ``Delete`` also return ``None`` on success, so check the outcome on the
45
+ attributes (``OrderId``, ``is_deleted``, ``OrderStatus``, ``Price``, ``Volume``) or call
46
+ ``Status()``.
47
+
48
+ Attributes:
49
+ ContractNameOrId (str | int): Contract name or contract id, depending on the method that
50
+ created the order.
51
+ Price (int): Order price, in IRR. Updated by ``Edit``.
52
+ Volume (int): Total requested order volume. Updated by ``Edit``.
53
+ ValidityType (str): Validity type of the order as reported by the server. It is NOT set in
54
+ ``__init__``: it exists only after a successful ``Edit`` (HTTP ``200``), so reading it
55
+ earlier raises ``AttributeError``.
56
+ is_deleted (bool): ``False`` at first. ``True`` once the order has been deleted
57
+ (``Delete`` succeeded, or the server reports it as ``'Cancelled'``).
58
+ OrderId (HexUUID | None): Unique identifier of the order (the server's ``order_uuid``).
59
+ ``None`` until ``send`` succeeds, so ``order.OrderId is not None`` means "was sent".
60
+ OrderOmsId (str | None): Unique identifier of the order assigned by the OMS. ``None`` until
61
+ ``send`` succeeds.
62
+ OrderStatus (Literal['Unknown', 'InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
63
+ Current lifecycle status of the order. It is ``'Unknown'`` until a status is received from
64
+ the server. ``send`` does not set it; it is updated by ``Status``, ``Delete`` and by the
65
+ reconciliation done in ``Edit`` / ``Delete``.
66
+
67
+ Example:
68
+ >>> order = await client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
69
+ >>> if order is not None:
70
+ ... await order.send()
71
+ ... print(order.OrderId)
72
+ 953097ac6ced45ca8ef205b76ca6faf2
73
+ """
74
+
75
+
76
+ def __init__(
77
+ self,
78
+ *,
79
+ SendOrder_RequestInfo : dict,
80
+ AuthASyncClient : AuthAsyncClient,
81
+ ContractNameOrId : str | int ,
82
+ Price : int,
83
+ Volume :int,
84
+ ):
85
+ """
86
+ Create an Order object. Nothing is sent to the exchange.
87
+
88
+ All arguments are keyword-only. You normally do not call this directly: the ``Buy_*`` /
89
+ ``Sell_*`` methods of ``EmsEngine_Ime_AsyncClient`` build the order and its request for you.
90
+
91
+ Args:
92
+ SendOrder_RequestInfo (dict): Keyword arguments for the ``httpx_Client.post`` call that
93
+ submits the order, prepared by the client: ``{'url': <new-order endpoint>, 'data':
94
+ {oms_session, contractName | contractId, Price, Volume, InitialOrderId}}``. What is
95
+ actually sent by ``send`` is this dictionary; ``Price`` and ``Volume`` below are only
96
+ stored on the object for reference. ``InitialOrderId`` is a random hex id generated once
97
+ when the order is created and reused if ``send`` is called again.
98
+ AuthASyncClient (AuthAsyncClient): Authenticated client used for all the requests of this
99
+ order.
100
+ ContractNameOrId (str | int): Contract name or contract id.
101
+ Price (int): Order price, in IRR.
102
+ Volume (int): Total order volume.
103
+ """
104
+
105
+
106
+ self.__AuthASyncClient = AuthASyncClient
107
+ self.__SendOrder_RequestInfo = SendOrder_RequestInfo
108
+
109
+ self.ContractNameOrId : str = ContractNameOrId
110
+ self.Price : int = Price
111
+ self.Volume : int = Volume
112
+ self.is_deleted : bool = False
113
+ self.OrderStatus : Literal[
114
+ 'Unknown',
115
+ 'InQueue',
116
+ 'PartiallyFilled',
117
+ 'Cancelled',
118
+ 'Broken',
119
+ 'Settled',
120
+ ] = 'Unknown'
121
+
122
+ self.OrderId : HexUUID | None = None
123
+ self.OrderOmsId : str | None = None
124
+
125
+ # +--------------------------------------------------------------------------------------+ #
126
+
127
+ async def send(self)-> None:
128
+ """
129
+ Sends the order to the EMS engine asynchronously.
130
+
131
+ Posts ``SendOrder_RequestInfo`` through ``httpx_Client.post``, but only if the order has not
132
+ been sent yet (``OrderId is None``). If ``OrderId`` is already set nothing happens, so calling
133
+ ``send()`` after a successful send never submits the same ``Order`` object twice.
134
+
135
+ The submission is successful only for HTTP status ``200``: then ``OrderId`` and ``OrderOmsId``
136
+ are set from the response (``Data.order_uuid`` and ``Data.order_oms_id``). ``OrderStatus`` is
137
+ not changed; call ``Status()`` to get it.
138
+
139
+ Returns:
140
+ None: Always, whether it succeeded or not. Any other status or error is swallowed and the
141
+ order stays unsent (``OrderId`` remains ``None``). Check ``order.OrderId is not None``
142
+ to know if the order was sent.
143
+
144
+ Note:
145
+ After a failure ``OrderId`` is still ``None``, so ``send()`` can be called again; the same
146
+ ``InitialOrderId`` is sent again. Whether the server uses it to de-duplicate is not defined
147
+ here; after a timeout or network error, keep in mind that the first request may already have
148
+ reached the exchange.
149
+
150
+ Example:
151
+ >>> order = await client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
152
+ >>> await order.send()
153
+ >>> if order.OrderId is not None:
154
+ ... print(order.OrderId)
155
+ 953097ac6ced45ca8ef205b76ca6faf2
156
+ """
157
+
158
+
159
+ try :
160
+
161
+ if self.OrderId is None :
162
+
163
+ SendOrder_Response = await self.__AuthASyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
164
+
165
+ match SendOrder_Response.status_code :
166
+
167
+ case 200 :
168
+
169
+ data = SendOrder_Response.json()
170
+ self.OrderId = data['Data']['order_uuid']
171
+ self.OrderOmsId = data['Data']['order_oms_id']
172
+ return None
173
+
174
+ case _ : return None
175
+
176
+ else : return None
177
+
178
+ except : return None
179
+
180
+ # +--------------------------------------------------------------------------------------+ #
181
+
182
+ async def Edit(
183
+ self,
184
+ *,
185
+ Price : int,
186
+ Volume :int,
187
+ )-> None:
188
+ """
189
+ Edits an existing order asynchronously.
190
+
191
+ Sends ``PATCH https://core.hedgetech.ir/ems-engine/ime/order/edit`` (form data: ``order_uuid``,
192
+ ``Price``, ``Volume``). Nothing happens if the order has not been sent yet (``OrderId is None``).
193
+ All arguments are keyword-only and both are always sent.
194
+
195
+ How the result is applied:
196
+ * Status ``200``: ``ValidityType``, ``Price`` and ``Volume`` are updated from the server's
197
+ reply (``order_validity_type``, ``order_price``, ``order_volume``). If one of these keys is
198
+ missing, the error is swallowed and the attributes read before it stay updated.
199
+ * Any other status: the real state is read with ``Status()`` to find out what happened.
200
+ If the order is still active (``InQueue`` / ``PartiallyFilled``) and the server already
201
+ holds exactly the requested ``Price`` and ``Volume``, the edit is considered applied and
202
+ ``Price``, ``Volume`` and ``OrderStatus`` are updated. If the order is no longer active
203
+ (``Cancelled``, ``Broken`` or ``Settled``), only ``OrderStatus`` is updated. Otherwise
204
+ nothing changes.
205
+
206
+ Args:
207
+ Price (int): New order price, in IRR.
208
+ Volume (int): New TOTAL order volume. It includes the part that is already executed (the
209
+ reconciliation above compares it with the total ``Volume`` of the status), it is not the
210
+ remaining volume.
211
+
212
+ Returns:
213
+ None: Always. Errors are swallowed. Compare ``Price`` and ``Volume`` with what you requested
214
+ (or call ``Status()``) to know whether the edit was applied.
215
+
216
+ Example:
217
+ >>> await order.Edit(Price=105, Volume=15)
218
+ >>> order.Price, order.Volume
219
+ (105, 15)
220
+ """
221
+
222
+
223
+ try :
224
+
225
+ if self.OrderId is not None:
226
+
227
+ Edit_response = await self.__AuthASyncClient.httpx_Client.patch(
228
+ url='https://core.hedgetech.ir/ems-engine/ime/order/edit',
229
+ data={
230
+ 'order_uuid' : self.OrderId,
231
+ 'Price' : Price,
232
+ 'Volume' : Volume
233
+ }
234
+ )
235
+
236
+
237
+ match Edit_response.status_code:
238
+
239
+ case 200:
240
+
241
+ Edit_response = Edit_response.json()
242
+
243
+ self.ValidityType = Edit_response['Data']['order_validity_type']
244
+ self.Price = Edit_response['Data']['order_price']
245
+ self.Volume = Edit_response['Data']['order_volume']
246
+
247
+ return None
248
+
249
+ case _ :
250
+
251
+ status_respnse = await self.Status()
252
+
253
+ if status_respnse and (
254
+ status_respnse['order_status'] in ('PartiallyFilled' , 'InQueue')
255
+ and status_respnse['Volume'] == Volume
256
+ and status_respnse['Price'] == Price
257
+ ):
258
+
259
+ self.Price = status_respnse['Price']
260
+ self.Volume = status_respnse['Volume']
261
+ self.OrderStatus = status_respnse['order_status']
262
+ return None
263
+
264
+ elif status_respnse and status_respnse['order_status'] not in ('PartiallyFilled' , 'InQueue'):
265
+
266
+ self.OrderStatus = status_respnse['order_status']
267
+
268
+ return None
269
+
270
+ else : return None
271
+
272
+ else : return None
273
+
274
+ except : return None
275
+
276
+ # +--------------------------------------------------------------------------------------+ #
277
+
278
+ async def Status(self)-> OrderStatus | None:
279
+ """
280
+ Retrieves the current status of the order asynchronously.
281
+
282
+ Sends ``GET https://core.hedgetech.ir/ems-engine/ime/order/status`` with the ``order_uuid``.
283
+ Nothing is sent if the order has not been sent yet (``OrderId is None``). As a side effect, a
284
+ successful call updates ``self.OrderStatus`` from the response (the other attributes, such as
285
+ ``Price`` and ``Volume``, are not touched).
286
+
287
+ Returns:
288
+ OrderStatus | None: The ``Data`` part of the server's reply when the HTTP status is ``200``
289
+ (see the ``OrderStatus`` type), a dictionary with the following keys. ``None`` if the
290
+ order has not been sent, the status is not ``200`` or any error occurred.
291
+
292
+ - order_uuid (HexUUID): Unique identifier of the order.
293
+ - order_status: ``'InQueue'`` | ``'PartiallyFilled'`` | ``'Cancelled'`` | ``'Broken'`` |
294
+ ``'Settled'``. ``InQueue`` and ``PartiallyFilled`` are active states; the other three
295
+ are final.
296
+ - Price (int): The order price, in IRR.
297
+ - Volume (int): The total order volume.
298
+ - RemainedVolume (int): Volume remaining unexecuted.
299
+ - ExecutedVolume (int): Executed volume so far.
300
+ - OrderSide: ``'Buy'`` | ``'Sell'``, the order side.
301
+ - ValidityType: ``'DAY'`` | ``'GTC'`` | ``'GTD'``, the type of order validity.
302
+ - ValidityDate (int): Expiration date if applicable (``0`` otherwise).
303
+
304
+ Example:
305
+ >>> status = await order.Status()
306
+ >>> print(status)
307
+ {
308
+ 'order_uuid': '953097ac6ced45ca8ef205b76ca6faf2',
309
+ 'order_status': 'InQueue',
310
+ 'Price': 100,
311
+ 'Volume': 10,
312
+ 'RemainedVolume': 10,
313
+ 'ExecutedVolume': 0,
314
+ 'OrderSide': 'Buy',
315
+ 'ValidityType': 'DAY',
316
+ 'ValidityDate': 0
317
+ }
318
+ >>> order.OrderStatus
319
+ 'InQueue'
320
+ """
321
+
322
+
323
+ try :
324
+
325
+ if self.OrderId is not None:
326
+
327
+ status_respnse = await self.__AuthASyncClient.httpx_Client.get(
328
+ url='https://core.hedgetech.ir/ems-engine/ime/order/status',
329
+ params={'order_uuid' : self.OrderId}
330
+ )
331
+
332
+ match status_respnse.status_code :
333
+
334
+ case 200:
335
+
336
+ status_respnse = status_respnse.json()['Data']
337
+ self.OrderStatus = status_respnse['order_status']
338
+
339
+ return status_respnse
340
+
341
+ case _ : return None
342
+
343
+ else : return None
344
+
345
+ except : return None
346
+
347
+ # +--------------------------------------------------------------------------------------+ #
348
+
349
+ async def Delete(self)-> None:
350
+ """
351
+ Deletes (cancels) the order asynchronously.
352
+
353
+ Sends ``DELETE https://core.hedgetech.ir/ems-engine/ime/order/delete`` with the
354
+ ``order_uuid``. Nothing is sent if the order has not been sent yet (``OrderId is None``).
355
+
356
+ How the result is applied:
357
+ * Status ``200``: ``is_deleted`` is set to ``True`` and ``OrderStatus`` to ``'Cancelled'``.
358
+ * Any other status: the real state is read with ``Status()``. If the order is already
359
+ ``'Cancelled'`` the result is the same as above. If it has any other status (for example
360
+ ``'Settled'`` because it was fully executed first), only ``OrderStatus`` is updated and
361
+ ``is_deleted`` stays ``False``. If the status cannot be read, nothing changes.
362
+
363
+ ``OrderId`` is kept after deletion.
364
+
365
+ Returns:
366
+ None: Always. Errors are swallowed. Check ``is_deleted`` (and ``OrderStatus``) to know the
367
+ outcome.
368
+
369
+ Example:
370
+ >>> await order.Delete()
371
+ >>> print(order.is_deleted)
372
+ True
373
+ """
374
+
375
+
376
+ try :
377
+
378
+ if self.OrderId is not None:
379
+
380
+ Delete_respnse = await self.__AuthASyncClient.httpx_Client.delete(
381
+ url= 'https://core.hedgetech.ir/ems-engine/ime/order/delete',
382
+ params={'order_uuid' : self.OrderId}
383
+ )
384
+
385
+ match Delete_respnse.status_code :
386
+
387
+ case 200:
388
+
389
+ self.is_deleted = True
390
+ self.OrderStatus = 'Cancelled'
391
+ return None
392
+
393
+ case _ :
394
+
395
+ status_respnse = await self.Status()
396
+
397
+ if status_respnse and status_respnse['order_status'] == 'Cancelled':
398
+ self.is_deleted = True
399
+ self.OrderStatus = 'Cancelled'
400
+ return None
401
+
402
+ elif status_respnse and status_respnse['order_status'] != 'Cancelled' :
403
+ self.OrderStatus = status_respnse['order_status']
404
+ return None
405
+
406
+ else : return None
407
+
408
+ else : return None
409
+
410
+ except : return None
411
+
412
+ # ================================================================================= #
413
+
414
+ class EmsEngine_Ime_AsyncClient:
415
+ """
416
+ Asynchronous EMS Engine client for the IME (Iran Mercantile Exchange) market.
417
+
418
+ This client manages authentication, OMS login,
419
+ and order creation.
420
+
421
+ Typical workflow:
422
+ 1. ``captcha = await client.Get_Captcha(OMS)``: get the CAPTCHA image and read its value.
423
+ 2. ``await client.oms_login(username=..., password=..., captcha_value=...)``: log into the
424
+ OMS. This sets ``oms_session``.
425
+ 3. ``order = await client.Buy_by_ContractName(...)`` (or ``Sell_by_ContractName``,
426
+ ``Buy_by_ContractId``, ``Sell_by_ContractId``): build an ``Order``. Nothing is sent yet.
427
+ 4. ``await order.send()``: submit the order. See ``Order`` for editing, status and deletion.
428
+
429
+ Attributes:
430
+ Customer_FullName (str | None): Full name of the logged-in customer. ``None`` until
431
+ ``oms_login`` succeeds.
432
+ Customer_IMEBourseCode (str | None): IME bourse code of the customer. ``None`` until
433
+ ``oms_login`` succeeds.
434
+ oms_session (HexUUID | None): Session token obtained after login. ``None`` until
435
+ ``oms_login`` succeeds. The order creation methods return ``None`` while it is ``None``.
436
+
437
+ Example:
438
+ >>> client = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth_client)
439
+ >>> captcha = await client.Get_Captcha('Sahra | Karamad')
440
+ >>> captcha.show()
441
+ >>> await client.oms_login(
442
+ ... username="user123",
443
+ ... password="pass123",
444
+ ... captcha_value="abcd",
445
+ ... )
446
+ >>> order = await client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
447
+ >>> await order.send()
448
+ >>> print(order.OrderId)
449
+ 953097ac6ced45ca8ef205b76ca6faf2
450
+ """
451
+
452
+
453
+ def __init__(
454
+ self,
455
+ AuthASyncClient : AuthAsyncClient,
456
+ ):
457
+ """
458
+ Create the EMS Engine client. Nothing is sent to the server.
459
+
460
+ Provides methods for logging in (CAPTCHA + OMS login) and for creating buy/sell orders
461
+ by contract name or contract id. See the class docstring for the workflow.
462
+
463
+ Args:
464
+ AuthASyncClient (AuthAsyncClient): An already authenticated ``AuthAsyncClient``. Its
465
+ ``httpx_Client`` is used for every request (it also keeps the cookies of the CAPTCHA /
466
+ OMS login session, so use the same client for ``Get_Captcha`` and ``oms_login``).
467
+ """
468
+
469
+
470
+
471
+ self.__AuthASyncClient = AuthASyncClient
472
+
473
+ self.Customer_FullName : str | None = None
474
+ self.Customer_IMEBourseCode : str | None = None
475
+ self.oms_session : HexUUID | None = None
476
+
477
+ # +--------------------------------------------------------------------------------------+ #
478
+
479
+ async def Get_Captcha(
480
+ self,
481
+ OMS : Literal[
482
+ 'Sahra | Karamad',
483
+ 'Sahra | Charisma',
484
+ ]
485
+ )-> ImageFile:
486
+ """
487
+ Retrieves the CAPTCHA image for the specified OMS asynchronously.
488
+
489
+ Sends ``GET https://core.hedgetech.ir/ems-engine/ime/oms/login`` with the ``oms`` parameter.
490
+ The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
491
+ established by this call: call it with the same client right after ``Get_Captcha``.
492
+
493
+ Args:
494
+ OMS (Literal['Sahra | Karamad', 'Sahra | Charisma']): The OMS (broker system) to log into.
495
+ The format is ``'<provider> | <broker>'``.
496
+
497
+ Returns:
498
+ ImageFile: The CAPTCHA image (a ``PIL`` image opened from the response bytes). Show or save it
499
+ and pass the value you read to ``oms_login``.
500
+
501
+ Raises:
502
+ ValueError: If the HTTP status is not ``200``. The message is the server's
503
+ ``detail.Status.Description.en``. If the error body does not have that structure, another
504
+ exception (for example ``KeyError``) may be raised instead.
505
+
506
+ Example:
507
+ >>> captcha = await client.Get_Captcha('Sahra | Karamad')
508
+ >>> captcha.show()
509
+ """
510
+
511
+
512
+ Captcha = await self.__AuthASyncClient.httpx_Client.get(
513
+ url='https://core.hedgetech.ir/ems-engine/ime/oms/login',
514
+ params={'oms' : OMS }
515
+ )
516
+
517
+ if Captcha.status_code == 200: return image_open(BytesIO(Captcha.content))
518
+
519
+ else : raise ValueError(Captcha.json()['detail']['Status']['Description']['en'])
520
+
521
+
522
+ # +--------------------------------------------------------------------------------------+ #
523
+
524
+ async def oms_login(
525
+ self,
526
+ *,
527
+ username: str,
528
+ password: str,
529
+ captcha_value: str,
530
+ ) -> None :
531
+ """
532
+ Logs into the OMS asynchronously with provided credentials and CAPTCHA.
533
+
534
+ Sends ``POST https://core.hedgetech.ir/ems-engine/ime/oms/login`` (form data: ``username``,
535
+ ``Password``, ``Captcha_Value``). Call ``Get_Captcha`` first, with the same client. All arguments
536
+ are keyword-only.
537
+
538
+ On success (HTTP ``200``) ``Customer_FullName``, ``Customer_IMEBourseCode`` and ``oms_session``
539
+ are set from the response. ``oms_session`` is required by the order creation methods and is
540
+ copied into every order when it is created: orders built before a later re-login keep the old
541
+ session.
542
+
543
+ Args:
544
+ username (str): OMS username.
545
+ password (str): OMS password.
546
+ captcha_value (str): Solved CAPTCHA value (the text of the image from ``Get_Captcha``).
547
+
548
+ Returns:
549
+ None
550
+
551
+ Raises:
552
+ ValueError: If the login fails. For HTTP ``400`` (for example a wrong CAPTCHA or wrong
553
+ credentials) the message is the server's ``detail.Status.Description.en``; for any other
554
+ non-``200`` status it is the raw response text.
555
+
556
+ Example:
557
+ >>> await client.oms_login(
558
+ ... username="user123",
559
+ ... password="pass123",
560
+ ... captcha_value="abcd",
561
+ ... )
562
+ >>> print(client.oms_session)
563
+ 953097ac6ced45ca8ef205b76ca6faf2
564
+ """
565
+
566
+
567
+
568
+ response = await self.__AuthASyncClient.httpx_Client.post(
569
+ url='https://core.hedgetech.ir/ems-engine/ime/oms/login',
570
+ data={
571
+ 'username' : username,
572
+ 'Password' : password,
573
+ 'Captcha_Value' : captcha_value
574
+ },
575
+ )
576
+
577
+ match response.status_code :
578
+
579
+ case 200 :
580
+
581
+ data = response.json()
582
+
583
+ self.Customer_FullName = data['Data']['Customer_FullName']
584
+ self.Customer_IMEBourseCode = data['Data']['Customer_IMEBourseCode']
585
+ self.oms_session = data['Data']['oms_session']
586
+
587
+ return None
588
+
589
+ case 400 :
590
+
591
+ raise ValueError(response.json()['detail']['Status']['Description']['en'])
592
+
593
+ case _ :
594
+
595
+ raise ValueError(response.text)
596
+
597
+ # +--------------------------------------------------------------------------------------+ #
598
+
599
+ async def Buy_by_ContractName(
600
+ self,
601
+ *,
602
+ contractName : str,
603
+ Price : int,
604
+ Volume :int,
605
+ )-> Order | None:
606
+ """
607
+ Creates a new buy order by contract name asynchronously.
608
+
609
+ This only BUILDS the order: nothing is sent to the exchange until you call
610
+ ``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
611
+ check the limits yourself if you need to.
612
+
613
+ A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
614
+ succeeded) no order is created and ``None`` is returned. The session is copied into the order at
615
+ this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
616
+ order's request.
617
+
618
+ All arguments are keyword-only.
619
+
620
+ Args:
621
+ contractName (str): Name of the contract.
622
+ Price (int): Order price, in IRR.
623
+ Volume (int): Order volume.
624
+
625
+ Returns:
626
+ Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
627
+
628
+ Example:
629
+ >>> order = await client.Buy_by_ContractName(
630
+ ... contractName="<contract name>",
631
+ ... Price=100000,
632
+ ... Volume=10,
633
+ ... )
634
+ >>> if order is not None:
635
+ ... await order.send()
636
+ """
637
+
638
+
639
+ await sleep(0)
640
+
641
+ if self.oms_session is not None:
642
+
643
+ return Order(
644
+ AuthASyncClient=self.__AuthASyncClient,
645
+ ContractNameOrId = contractName,
646
+ Price=Price,
647
+ Volume=Volume,
648
+ SendOrder_RequestInfo = {
649
+ 'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/buy/contract/name',
650
+ 'data' : {
651
+ 'oms_session' : self.oms_session,
652
+ 'contractName' : contractName,
653
+ 'Price' : Price,
654
+ 'Volume' : Volume,
655
+ 'InitialOrderId' : uuid4().hex,
656
+ }
657
+ }
658
+ )
659
+
660
+ else : return None
661
+
662
+ # +--------------------------------------------------------------------------------------+ #
663
+
664
+ async def Sell_by_ContractName(
665
+ self,
666
+ *,
667
+ contractName : str,
668
+ Price : int,
669
+ Volume :int,
670
+ )-> Order | None:
671
+ """
672
+ Creates a new sell order by contract name asynchronously.
673
+
674
+ This only BUILDS the order: nothing is sent to the exchange until you call
675
+ ``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
676
+ check the limits yourself if you need to.
677
+
678
+ A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
679
+ succeeded) no order is created and ``None`` is returned. The session is copied into the order at
680
+ this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
681
+ order's request.
682
+
683
+ All arguments are keyword-only.
684
+
685
+ Args:
686
+ contractName (str): Name of the contract.
687
+ Price (int): Order price, in IRR.
688
+ Volume (int): Order volume.
689
+
690
+ Returns:
691
+ Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
692
+
693
+ Example:
694
+ >>> order = await client.Sell_by_ContractName(
695
+ ... contractName="<contract name>",
696
+ ... Price=100000,
697
+ ... Volume=10,
698
+ ... )
699
+ >>> if order is not None:
700
+ ... await order.send()
701
+ """
702
+
703
+
704
+ await sleep(0)
705
+
706
+ if self.oms_session is not None:
707
+
708
+ return Order(
709
+ AuthASyncClient=self.__AuthASyncClient,
710
+ ContractNameOrId = contractName,
711
+ Price=Price,
712
+ Volume=Volume,
713
+ SendOrder_RequestInfo = {
714
+ 'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/sell/contract/name',
715
+ 'data' : {
716
+ 'oms_session' : self.oms_session,
717
+ 'contractName' : contractName,
718
+ 'Price' : Price,
719
+ 'Volume' : Volume,
720
+ 'InitialOrderId' : uuid4().hex,
721
+ }
722
+ }
723
+ )
724
+
725
+ else : return None
726
+
727
+ # +--------------------------------------------------------------------------------------+ #
728
+
729
+ async def Buy_by_ContractId(
730
+ self,
731
+ *,
732
+ contractId : int | str,
733
+ Price : int,
734
+ Volume :int,
735
+ )-> Order | None:
736
+ """
737
+ Creates a new buy order by contract id asynchronously.
738
+
739
+ This only BUILDS the order: nothing is sent to the exchange until you call
740
+ ``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
741
+ check the limits yourself if you need to.
742
+
743
+ A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
744
+ succeeded) no order is created and ``None`` is returned. The session is copied into the order at
745
+ this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
746
+ order's request.
747
+
748
+ All arguments are keyword-only.
749
+
750
+ Args:
751
+ contractId (int | str): Id of the contract.
752
+ Price (int): Order price, in IRR.
753
+ Volume (int): Order volume.
754
+
755
+ Returns:
756
+ Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
757
+
758
+ Example:
759
+ >>> order = await client.Buy_by_ContractId(
760
+ ... contractId=123456,
761
+ ... Price=100000,
762
+ ... Volume=10,
763
+ ... )
764
+ >>> if order is not None:
765
+ ... await order.send()
766
+ """
767
+
768
+
769
+ await sleep(0)
770
+
771
+ if self.oms_session is not None:
772
+
773
+ return Order(
774
+ AuthASyncClient=self.__AuthASyncClient,
775
+ ContractNameOrId = contractId,
776
+ Price=Price,
777
+ Volume=Volume,
778
+ SendOrder_RequestInfo = {
779
+ 'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/buy/contract/id',
780
+ 'data' : {
781
+ 'oms_session' : self.oms_session,
782
+ 'contractId' : contractId,
783
+ 'Price' : Price,
784
+ 'Volume' : Volume,
785
+ 'InitialOrderId' : uuid4().hex,
786
+ }
787
+ }
788
+ )
789
+
790
+ else : return None
791
+
792
+ # +--------------------------------------------------------------------------------------+ #
793
+
794
+ async def Sell_by_ContractId(
795
+ self,
796
+ *,
797
+ contractId : int | str,
798
+ Price : int,
799
+ Volume :int,
800
+ )-> Order | None:
801
+ """
802
+ Creates a new sell order by contract id asynchronously.
803
+
804
+ This only BUILDS the order: nothing is sent to the exchange until you call
805
+ ``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
806
+ check the limits yourself if you need to.
807
+
808
+ A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
809
+ succeeded) no order is created and ``None`` is returned. The session is copied into the order at
810
+ this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
811
+ order's request.
812
+
813
+ All arguments are keyword-only.
814
+
815
+ Args:
816
+ contractId (int | str): Id of the contract.
817
+ Price (int): Order price, in IRR.
818
+ Volume (int): Order volume.
819
+
820
+ Returns:
821
+ Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
822
+
823
+ Example:
824
+ >>> order = await client.Sell_by_ContractId(
825
+ ... contractId=123456,
826
+ ... Price=100000,
827
+ ... Volume=10,
828
+ ... )
829
+ >>> if order is not None:
830
+ ... await order.send()
831
+ """
832
+
833
+
834
+ await sleep(0)
835
+
836
+ if self.oms_session is not None:
837
+
838
+ return Order(
839
+ AuthASyncClient=self.__AuthASyncClient,
840
+ ContractNameOrId = contractId,
841
+ Price=Price,
842
+ Volume=Volume,
843
+ SendOrder_RequestInfo = {
844
+ 'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/sell/contract/id',
845
+ 'data' : {
846
+ 'oms_session' : self.oms_session,
847
+ 'contractId' : contractId,
848
+ 'Price' : Price,
849
+ 'Volume' : Volume,
850
+ 'InitialOrderId' : uuid4().hex,
851
+ }
852
+ }
853
+ )
854
+
855
+ else : return None