4 Commits
Author SHA1 Message Date
mtrshirazi21 e8e2e028a7 chore: mark project as production/stable 2026-10-26 22:19:48 +03:30
mtrshirazi21 cead5ef4f4 update README 2026-10-26 22:14:56 +03:30
mtrshirazi21 dba5684940 update README 2026-10-26 22:03:44 +03:30
mtrshirazi21 7295d07c03 docs: finalize docstrings 2026-10-26 16:58:08 +03:30
4 changed files with 2755 additions and 247 deletions

No files matched your search

+441
View File
@@ -20,6 +20,58 @@ from uuid import uuid4
# Class Definitions #
# ========================================|======================================== #
class Order:
"""
Represents a single trading order in EMS Engine (IME).
This class provides methods to send, edit, check status,
and delete an order after creation.
An Order instance is created via the ``Buy_by_ContractName``, ``Sell_by_ContractName``,
``Buy_by_ContractId`` and ``Sell_by_ContractId`` methods of `EmsEngine_Ime_AsyncClient`.
Creating an ``Order`` does NOT send anything to the exchange: you must call
``await order.send()``.
Typical life cycle:
1. ``order = await client.Buy_by_ContractName(...)``: build the order (nothing is sent yet).
2. ``await order.send()``: submit it. On success ``OrderId`` is set.
3. ``await order.Status()``, ``await order.Edit(...)`` or ``await order.Delete()``:
follow, modify or cancel the submitted order.
Note:
``send``, ``Edit``, ``Status`` and ``Delete`` never raise. Every error (a non-200 response,
a network failure, an unexpected response body, ...) is swallowed and the method just returns
``None`` (the catch is a bare ``except``, so even ``asyncio.CancelledError`` is swallowed).
``send``, ``Edit`` and ``Delete`` also return ``None`` on success, so check the outcome on the
attributes (``OrderId``, ``is_deleted``, ``OrderStatus``, ``Price``, ``Volume``) or call
``Status()``.
Attributes:
ContractNameOrId (str | int): Contract name or contract id, depending on the method that
created the order.
Price (int): Order price, in IRR. Updated by ``Edit``.
Volume (int): Total requested order volume. Updated by ``Edit``.
ValidityType (str): Validity type of the order as reported by the server. It is NOT set in
``__init__``: it exists only after a successful ``Edit`` (HTTP ``200``), so reading it
earlier raises ``AttributeError``.
is_deleted (bool): ``False`` at first. ``True`` once the order has been deleted
(``Delete`` succeeded, or the server reports it as ``'Cancelled'``).
OrderId (HexUUID | None): Unique identifier of the order (the server's ``order_uuid``).
``None`` until ``send`` succeeds, so ``order.OrderId is not None`` means "was sent".
OrderOmsId (str | None): Unique identifier of the order assigned by the OMS. ``None`` until
``send`` succeeds.
OrderStatus (Literal['Unknown', 'InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
Current lifecycle status of the order. It is ``'Unknown'`` until a status is received from
the server. ``send`` does not set it; it is updated by ``Status``, ``Delete`` and by the
reconciliation done in ``Edit`` / ``Delete``.
Example:
>>> order = await client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
>>> if order is not None:
... await order.send()
... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
"""
def __init__(
self,
@@ -30,6 +82,26 @@ class Order:
Price : int,
Volume :int,
):
"""
Create an Order object. Nothing is sent to the exchange.
All arguments are keyword-only. You normally do not call this directly: the ``Buy_*`` /
``Sell_*`` methods of ``EmsEngine_Ime_AsyncClient`` build the order and its request for you.
Args:
SendOrder_RequestInfo (dict): Keyword arguments for the ``httpx_Client.post`` call that
submits the order, prepared by the client: ``{'url': <new-order endpoint>, 'data':
{oms_session, contractName | contractId, Price, Volume, InitialOrderId}}``. What is
actually sent by ``send`` is this dictionary; ``Price`` and ``Volume`` below are only
stored on the object for reference. ``InitialOrderId`` is a random hex id generated once
when the order is created and reused if ``send`` is called again.
AuthASyncClient (AuthAsyncClient): Authenticated client used for all the requests of this
order.
ContractNameOrId (str | int): Contract name or contract id.
Price (int): Order price, in IRR.
Volume (int): Total order volume.
"""
self.__AuthASyncClient = AuthASyncClient
self.__SendOrder_RequestInfo = SendOrder_RequestInfo
@@ -53,6 +125,36 @@ class Order:
# +--------------------------------------------------------------------------------------+ #
async def send(self)-> None:
"""
Sends the order to the EMS engine asynchronously.
Posts ``SendOrder_RequestInfo`` through ``httpx_Client.post``, but only if the order has not
been sent yet (``OrderId is None``). If ``OrderId`` is already set nothing happens, so calling
``send()`` after a successful send never submits the same ``Order`` object twice.
The submission is successful only for HTTP status ``200``: then ``OrderId`` and ``OrderOmsId``
are set from the response (``Data.order_uuid`` and ``Data.order_oms_id``). ``OrderStatus`` is
not changed; call ``Status()`` to get it.
Returns:
None: Always, whether it succeeded or not. Any other status or error is swallowed and the
order stays unsent (``OrderId`` remains ``None``). Check ``order.OrderId is not None``
to know if the order was sent.
Note:
After a failure ``OrderId`` is still ``None``, so ``send()`` can be called again; the same
``InitialOrderId`` is sent again. Whether the server uses it to de-duplicate is not defined
here; after a timeout or network error, keep in mind that the first request may already have
reached the exchange.
Example:
>>> order = await client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
>>> await order.send()
>>> if order.OrderId is not None:
... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
"""
try :
@@ -83,6 +185,40 @@ class Order:
Price : int,
Volume :int,
)-> None:
"""
Edits an existing order asynchronously.
Sends ``PATCH https://core.hedgetech.ir/ems-engine/ime/order/edit`` (form data: ``order_uuid``,
``Price``, ``Volume``). Nothing happens if the order has not been sent yet (``OrderId is None``).
All arguments are keyword-only and both are always sent.
How the result is applied:
* Status ``200``: ``ValidityType``, ``Price`` and ``Volume`` are updated from the server's
reply (``order_validity_type``, ``order_price``, ``order_volume``). If one of these keys is
missing, the error is swallowed and the attributes read before it stay updated.
* Any other status: the real state is read with ``Status()`` to find out what happened.
If the order is still active (``InQueue`` / ``PartiallyFilled``) and the server already
holds exactly the requested ``Price`` and ``Volume``, the edit is considered applied and
``Price``, ``Volume`` and ``OrderStatus`` are updated. If the order is no longer active
(``Cancelled``, ``Broken`` or ``Settled``), only ``OrderStatus`` is updated. Otherwise
nothing changes.
Args:
Price (int): New order price, in IRR.
Volume (int): New TOTAL order volume. It includes the part that is already executed (the
reconciliation above compares it with the total ``Volume`` of the status), it is not the
remaining volume.
Returns:
None: Always. Errors are swallowed. Compare ``Price`` and ``Volume`` with what you requested
(or call ``Status()``) to know whether the edit was applied.
Example:
>>> await order.Edit(Price=105, Volume=15)
>>> order.Price, order.Volume
(105, 15)
"""
try :
@@ -140,6 +276,49 @@ class Order:
# +--------------------------------------------------------------------------------------+ #
async def Status(self)-> OrderStatus | None:
"""
Retrieves the current status of the order asynchronously.
Sends ``GET https://core.hedgetech.ir/ems-engine/ime/order/status`` with the ``order_uuid``.
Nothing is sent if the order has not been sent yet (``OrderId is None``). As a side effect, a
successful call updates ``self.OrderStatus`` from the response (the other attributes, such as
``Price`` and ``Volume``, are not touched).
Returns:
OrderStatus | None: The ``Data`` part of the server's reply when the HTTP status is ``200``
(see the ``OrderStatus`` type), a dictionary with the following keys. ``None`` if the
order has not been sent, the status is not ``200`` or any error occurred.
- order_uuid (HexUUID): Unique identifier of the order.
- order_status: ``'InQueue'`` | ``'PartiallyFilled'`` | ``'Cancelled'`` | ``'Broken'`` |
``'Settled'``. ``InQueue`` and ``PartiallyFilled`` are active states; the other three
are final.
- Price (int): The order price, in IRR.
- Volume (int): The total order volume.
- RemainedVolume (int): Volume remaining unexecuted.
- ExecutedVolume (int): Executed volume so far.
- OrderSide: ``'Buy'`` | ``'Sell'``, the order side.
- ValidityType: ``'DAY'`` | ``'GTC'`` | ``'GTD'``, the type of order validity.
- ValidityDate (int): Expiration date if applicable (``0`` otherwise).
Example:
>>> status = await order.Status()
>>> print(status)
{
'order_uuid': '953097ac6ced45ca8ef205b76ca6faf2',
'order_status': 'InQueue',
'Price': 100,
'Volume': 10,
'RemainedVolume': 10,
'ExecutedVolume': 0,
'OrderSide': 'Buy',
'ValidityType': 'DAY',
'ValidityDate': 0
}
>>> order.OrderStatus
'InQueue'
"""
try :
@@ -168,6 +347,31 @@ class Order:
# +--------------------------------------------------------------------------------------+ #
async def Delete(self)-> None:
"""
Deletes (cancels) the order asynchronously.
Sends ``DELETE https://core.hedgetech.ir/ems-engine/ime/order/delete`` with the
``order_uuid``. Nothing is sent if the order has not been sent yet (``OrderId is None``).
How the result is applied:
* Status ``200``: ``is_deleted`` is set to ``True`` and ``OrderStatus`` to ``'Cancelled'``.
* Any other status: the real state is read with ``Status()``. If the order is already
``'Cancelled'`` the result is the same as above. If it has any other status (for example
``'Settled'`` because it was fully executed first), only ``OrderStatus`` is updated and
``is_deleted`` stays ``False``. If the status cannot be read, nothing changes.
``OrderId`` is kept after deletion.
Returns:
None: Always. Errors are swallowed. Check ``is_deleted`` (and ``OrderStatus``) to know the
outcome.
Example:
>>> await order.Delete()
>>> print(order.is_deleted)
True
"""
try :
@@ -208,11 +412,60 @@ class Order:
# ================================================================================= #
class EmsEngine_Ime_AsyncClient:
"""
Asynchronous EMS Engine client for the IME (Iran Mercantile Exchange) market.
This client manages authentication, OMS login,
and order creation.
Typical workflow:
1. ``captcha = await client.Get_Captcha(OMS)``: get the CAPTCHA image and read its value.
2. ``await client.oms_login(username=..., password=..., captcha_value=...)``: log into the
OMS. This sets ``oms_session``.
3. ``order = await client.Buy_by_ContractName(...)`` (or ``Sell_by_ContractName``,
``Buy_by_ContractId``, ``Sell_by_ContractId``): build an ``Order``. Nothing is sent yet.
4. ``await order.send()``: submit the order. See ``Order`` for editing, status and deletion.
Attributes:
Customer_FullName (str | None): Full name of the logged-in customer. ``None`` until
``oms_login`` succeeds.
Customer_IMEBourseCode (str | None): IME bourse code of the customer. ``None`` until
``oms_login`` succeeds.
oms_session (HexUUID | None): Session token obtained after login. ``None`` until
``oms_login`` succeeds. The order creation methods return ``None`` while it is ``None``.
Example:
>>> client = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth_client)
>>> captcha = await client.Get_Captcha('Sahra | Karamad')
>>> captcha.show()
>>> await client.oms_login(
... username="user123",
... password="pass123",
... captcha_value="abcd",
... )
>>> order = await client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
>>> await order.send()
>>> print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
"""
def __init__(
self,
AuthASyncClient : AuthAsyncClient,
):
"""
Create the EMS Engine client. Nothing is sent to the server.
Provides methods for logging in (CAPTCHA + OMS login) and for creating buy/sell orders
by contract name or contract id. See the class docstring for the workflow.
Args:
AuthASyncClient (AuthAsyncClient): An already authenticated ``AuthAsyncClient``. Its
``httpx_Client`` is used for every request (it also keeps the cookies of the CAPTCHA /
OMS login session, so use the same client for ``Get_Captcha`` and ``oms_login``).
"""
self.__AuthASyncClient = AuthASyncClient
@@ -230,6 +483,31 @@ class EmsEngine_Ime_AsyncClient:
'Sahra | Charisma',
]
)-> ImageFile:
"""
Retrieves the CAPTCHA image for the specified OMS asynchronously.
Sends ``GET https://core.hedgetech.ir/ems-engine/ime/oms/login`` with the ``oms`` parameter.
The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
established by this call: call it with the same client right after ``Get_Captcha``.
Args:
OMS (Literal['Sahra | Karamad', 'Sahra | Charisma']): The OMS (broker system) to log into.
The format is ``'<provider> | <broker>'``.
Returns:
ImageFile: The CAPTCHA image (a ``PIL`` image opened from the response bytes). Show or save it
and pass the value you read to ``oms_login``.
Raises:
ValueError: If the HTTP status is not ``200``. The message is the server's
``detail.Status.Description.en``. If the error body does not have that structure, another
exception (for example ``KeyError``) may be raised instead.
Example:
>>> captcha = await client.Get_Captcha('Sahra | Karamad')
>>> captcha.show()
"""
Captcha = await self.__AuthASyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/ems-engine/ime/oms/login',
@@ -250,6 +528,41 @@ class EmsEngine_Ime_AsyncClient:
password: str,
captcha_value: str,
) -> None :
"""
Logs into the OMS asynchronously with provided credentials and CAPTCHA.
Sends ``POST https://core.hedgetech.ir/ems-engine/ime/oms/login`` (form data: ``username``,
``Password``, ``Captcha_Value``). Call ``Get_Captcha`` first, with the same client. All arguments
are keyword-only.
On success (HTTP ``200``) ``Customer_FullName``, ``Customer_IMEBourseCode`` and ``oms_session``
are set from the response. ``oms_session`` is required by the order creation methods and is
copied into every order when it is created: orders built before a later re-login keep the old
session.
Args:
username (str): OMS username.
password (str): OMS password.
captcha_value (str): Solved CAPTCHA value (the text of the image from ``Get_Captcha``).
Returns:
None
Raises:
ValueError: If the login fails. For HTTP ``400`` (for example a wrong CAPTCHA or wrong
credentials) the message is the server's ``detail.Status.Description.en``; for any other
non-``200`` status it is the raw response text.
Example:
>>> await client.oms_login(
... username="user123",
... password="pass123",
... captcha_value="abcd",
... )
>>> print(client.oms_session)
953097ac6ced45ca8ef205b76ca6faf2
"""
response = await self.__AuthASyncClient.httpx_Client.post(
@@ -290,6 +603,38 @@ class EmsEngine_Ime_AsyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new buy order by contract name asynchronously.
This only BUILDS the order: nothing is sent to the exchange until you call
``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractName (str): Name of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Buy_by_ContractName(
... contractName="<contract name>",
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... await order.send()
"""
await sleep(0)
@@ -323,6 +668,38 @@ class EmsEngine_Ime_AsyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new sell order by contract name asynchronously.
This only BUILDS the order: nothing is sent to the exchange until you call
``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractName (str): Name of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Sell_by_ContractName(
... contractName="<contract name>",
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... await order.send()
"""
await sleep(0)
@@ -356,6 +733,38 @@ class EmsEngine_Ime_AsyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new buy order by contract id asynchronously.
This only BUILDS the order: nothing is sent to the exchange until you call
``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractId (int | str): Id of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Buy_by_ContractId(
... contractId=123456,
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... await order.send()
"""
await sleep(0)
@@ -389,6 +798,38 @@ class EmsEngine_Ime_AsyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new sell order by contract id asynchronously.
This only BUILDS the order: nothing is sent to the exchange until you call
``await order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractId (int | str): Id of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Sell_by_ContractId(
... contractId=123456,
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... await order.send()
"""
await sleep(0)
+441
View File
@@ -19,6 +19,58 @@ from uuid import uuid4
# Class Definitions #
# ========================================|======================================== #
class Order:
"""
Represents a single trading order in EMS Engine (IME).
This class provides methods to send, edit, check status,
and delete an order after creation. All of them are blocking calls.
An Order instance is created via the ``Buy_by_ContractName``, ``Sell_by_ContractName``,
``Buy_by_ContractId`` and ``Sell_by_ContractId`` methods of `EmsEngine_Ime_SyncClient`.
Creating an ``Order`` does NOT send anything to the exchange: you must call
``order.send()``.
Typical life cycle:
1. ``order = client.Buy_by_ContractName(...)``: build the order (nothing is sent yet).
2. ``order.send()``: submit it. On success ``OrderId`` is set.
3. ``order.Status()``, ``order.Edit(...)`` or ``order.Delete()``:
follow, modify or cancel the submitted order.
Note:
``send``, ``Edit``, ``Status`` and ``Delete`` never raise. Every error (a non-200 response,
a network failure, an unexpected response body, ...) is swallowed and the method just returns
``None`` (the catch is a bare ``except``, so even ``KeyboardInterrupt`` is swallowed).
``send``, ``Edit`` and ``Delete`` also return ``None`` on success, so check the outcome on the
attributes (``OrderId``, ``is_deleted``, ``OrderStatus``, ``Price``, ``Volume``) or call
``Status()``.
Attributes:
ContractNameOrId (str | int): Contract name or contract id, depending on the method that
created the order.
Price (int): Order price, in IRR. Updated by ``Edit``.
Volume (int): Total requested order volume. Updated by ``Edit``.
ValidityType (str): Validity type of the order as reported by the server. It is NOT set in
``__init__``: it exists only after a successful ``Edit`` (HTTP ``200``), so reading it
earlier raises ``AttributeError``.
is_deleted (bool): ``False`` at first. ``True`` once the order has been deleted
(``Delete`` succeeded, or the server reports it as ``'Cancelled'``).
OrderId (HexUUID | None): Unique identifier of the order (the server's ``order_uuid``).
``None`` until ``send`` succeeds, so ``order.OrderId is not None`` means "was sent".
OrderOmsId (str | None): Unique identifier of the order assigned by the OMS. ``None`` until
``send`` succeeds.
OrderStatus (Literal['Unknown', 'InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
Current lifecycle status of the order. It is ``'Unknown'`` until a status is received from
the server. ``send`` does not set it; it is updated by ``Status``, ``Delete`` and by the
reconciliation done in ``Edit`` / ``Delete``.
Example:
>>> order = client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
>>> if order is not None:
... order.send()
... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
"""
def __init__(
self,
@@ -29,6 +81,26 @@ class Order:
Price : int,
Volume :int,
):
"""
Create an Order object. Nothing is sent to the exchange.
All arguments are keyword-only. You normally do not call this directly: the ``Buy_*`` /
``Sell_*`` methods of ``EmsEngine_Ime_SyncClient`` build the order and its request for you.
Args:
SendOrder_RequestInfo (dict): Keyword arguments for the ``httpx_Client.post`` call that
submits the order, prepared by the client: ``{'url': <new-order endpoint>, 'data':
{oms_session, contractName | contractId, Price, Volume, InitialOrderId}}``. What is
actually sent by ``send`` is this dictionary; ``Price`` and ``Volume`` below are only
stored on the object for reference. ``InitialOrderId`` is a random hex id generated once
when the order is created and reused if ``send`` is called again.
AuthSyncClient (AuthSyncClient): Authenticated client used for all the requests of this
order.
ContractNameOrId (str | int): Contract name or contract id.
Price (int): Order price, in IRR.
Volume (int): Total order volume.
"""
self.__AuthSyncClient = AuthSyncClient
self.__SendOrder_RequestInfo = SendOrder_RequestInfo
@@ -52,6 +124,36 @@ class Order:
# +--------------------------------------------------------------------------------------+ #
def send(self)-> None:
"""
Sends the order to the EMS engine.
Posts ``SendOrder_RequestInfo`` through ``httpx_Client.post``, but only if the order has not
been sent yet (``OrderId is None``). If ``OrderId`` is already set nothing happens, so calling
``send()`` after a successful send never submits the same ``Order`` object twice.
The submission is successful only for HTTP status ``200``: then ``OrderId`` and ``OrderOmsId``
are set from the response (``Data.order_uuid`` and ``Data.order_oms_id``). ``OrderStatus`` is
not changed; call ``Status()`` to get it.
Returns:
None: Always, whether it succeeded or not. Any other status or error is swallowed and the
order stays unsent (``OrderId`` remains ``None``). Check ``order.OrderId is not None``
to know if the order was sent.
Note:
After a failure ``OrderId`` is still ``None``, so ``send()`` can be called again; the same
``InitialOrderId`` is sent again. Whether the server uses it to de-duplicate is not defined
here; after a timeout or network error, keep in mind that the first request may already have
reached the exchange.
Example:
>>> order = client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
>>> order.send()
>>> if order.OrderId is not None:
... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
"""
try :
@@ -82,6 +184,40 @@ class Order:
Price : int,
Volume :int,
)-> None:
"""
Edits an existing order.
Sends ``PATCH https://core.hedgetech.ir/ems-engine/ime/order/edit`` (form data: ``order_uuid``,
``Price``, ``Volume``). Nothing happens if the order has not been sent yet (``OrderId is None``).
All arguments are keyword-only and both are always sent.
How the result is applied:
* Status ``200``: ``ValidityType``, ``Price`` and ``Volume`` are updated from the server's
reply (``order_validity_type``, ``order_price``, ``order_volume``). If one of these keys is
missing, the error is swallowed and the attributes read before it stay updated.
* Any other status: the real state is read with ``Status()`` to find out what happened.
If the order is still active (``InQueue`` / ``PartiallyFilled``) and the server already
holds exactly the requested ``Price`` and ``Volume``, the edit is considered applied and
``Price``, ``Volume`` and ``OrderStatus`` are updated. If the order is no longer active
(``Cancelled``, ``Broken`` or ``Settled``), only ``OrderStatus`` is updated. Otherwise
nothing changes.
Args:
Price (int): New order price, in IRR.
Volume (int): New TOTAL order volume. It includes the part that is already executed (the
reconciliation above compares it with the total ``Volume`` of the status), it is not the
remaining volume.
Returns:
None: Always. Errors are swallowed. Compare ``Price`` and ``Volume`` with what you requested
(or call ``Status()``) to know whether the edit was applied.
Example:
>>> order.Edit(Price=105, Volume=15)
>>> order.Price, order.Volume
(105, 15)
"""
try :
@@ -139,6 +275,49 @@ class Order:
# +--------------------------------------------------------------------------------------+ #
def Status(self)-> OrderStatus | None:
"""
Retrieves the current status of the order.
Sends ``GET https://core.hedgetech.ir/ems-engine/ime/order/status`` with the ``order_uuid``.
Nothing is sent if the order has not been sent yet (``OrderId is None``). As a side effect, a
successful call updates ``self.OrderStatus`` from the response (the other attributes, such as
``Price`` and ``Volume``, are not touched).
Returns:
OrderStatus | None: The ``Data`` part of the server's reply when the HTTP status is ``200``
(see the ``OrderStatus`` type), a dictionary with the following keys. ``None`` if the
order has not been sent, the status is not ``200`` or any error occurred.
- order_uuid (HexUUID): Unique identifier of the order.
- order_status: ``'InQueue'`` | ``'PartiallyFilled'`` | ``'Cancelled'`` | ``'Broken'`` |
``'Settled'``. ``InQueue`` and ``PartiallyFilled`` are active states; the other three
are final.
- Price (int): The order price, in IRR.
- Volume (int): The total order volume.
- RemainedVolume (int): Volume remaining unexecuted.
- ExecutedVolume (int): Executed volume so far.
- OrderSide: ``'Buy'`` | ``'Sell'``, the order side.
- ValidityType: ``'DAY'`` | ``'GTC'`` | ``'GTD'``, the type of order validity.
- ValidityDate (int): Expiration date if applicable (``0`` otherwise).
Example:
>>> status = order.Status()
>>> print(status)
{
'order_uuid': '953097ac6ced45ca8ef205b76ca6faf2',
'order_status': 'InQueue',
'Price': 100,
'Volume': 10,
'RemainedVolume': 10,
'ExecutedVolume': 0,
'OrderSide': 'Buy',
'ValidityType': 'DAY',
'ValidityDate': 0
}
>>> order.OrderStatus
'InQueue'
"""
try :
@@ -167,6 +346,31 @@ class Order:
# +--------------------------------------------------------------------------------------+ #
def Delete(self)-> None:
"""
Deletes (cancels) the order.
Sends ``DELETE https://core.hedgetech.ir/ems-engine/ime/order/delete`` with the
``order_uuid``. Nothing is sent if the order has not been sent yet (``OrderId is None``).
How the result is applied:
* Status ``200``: ``is_deleted`` is set to ``True`` and ``OrderStatus`` to ``'Cancelled'``.
* Any other status: the real state is read with ``Status()``. If the order is already
``'Cancelled'`` the result is the same as above. If it has any other status (for example
``'Settled'`` because it was fully executed first), only ``OrderStatus`` is updated and
``is_deleted`` stays ``False``. If the status cannot be read, nothing changes.
``OrderId`` is kept after deletion.
Returns:
None: Always. Errors are swallowed. Check ``is_deleted`` (and ``OrderStatus``) to know the
outcome.
Example:
>>> order.Delete()
>>> print(order.is_deleted)
True
"""
try :
@@ -207,11 +411,60 @@ class Order:
# ================================================================================= #
class EmsEngine_Ime_SyncClient:
"""
Synchronous (blocking) EMS Engine client for the IME (Iran Mercantile Exchange) market.
This client manages authentication, OMS login,
and order creation. All of its methods, and those of ``Order``, are blocking calls.
Typical workflow:
1. ``captcha = client.Get_Captcha(OMS)``: get the CAPTCHA image and read its value.
2. ``client.oms_login(username=..., password=..., captcha_value=...)``: log into the
OMS. This sets ``oms_session``.
3. ``order = client.Buy_by_ContractName(...)`` (or ``Sell_by_ContractName``,
``Buy_by_ContractId``, ``Sell_by_ContractId``): build an ``Order``. Nothing is sent yet.
4. ``order.send()``: submit the order. See ``Order`` for editing, status and deletion.
Attributes:
Customer_FullName (str | None): Full name of the logged-in customer. ``None`` until
``oms_login`` succeeds.
Customer_IMEBourseCode (str | None): IME bourse code of the customer. ``None`` until
``oms_login`` succeeds.
oms_session (HexUUID | None): Session token obtained after login. ``None`` until
``oms_login`` succeeds. The order creation methods return ``None`` while it is ``None``.
Example:
>>> client = EmsEngine_Ime_SyncClient(AuthSyncClient=auth_client)
>>> captcha = client.Get_Captcha('Sahra | Karamad')
>>> captcha.show()
>>> client.oms_login(
... username="user123",
... password="pass123",
... captcha_value="abcd",
... )
>>> order = client.Buy_by_ContractName(contractName="<contract name>", Price=100000, Volume=10)
>>> order.send()
>>> print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
"""
def __init__(
self,
AuthSyncClient : AuthSyncClient,
):
"""
Create the EMS Engine client. Nothing is sent to the server.
Provides methods for logging in (CAPTCHA + OMS login) and for creating buy/sell orders
by contract name or contract id. See the class docstring for the workflow.
Args:
AuthSyncClient (AuthSyncClient): An already authenticated ``AuthSyncClient``. Its
``httpx_Client`` is used for every request (it also keeps the cookies of the CAPTCHA /
OMS login session, so use the same client for ``Get_Captcha`` and ``oms_login``).
"""
self.__AuthSyncClient = AuthSyncClient
@@ -229,6 +482,31 @@ class EmsEngine_Ime_SyncClient:
'Sahra | Charisma',
]
)-> ImageFile:
"""
Retrieves the CAPTCHA image for the specified OMS.
Sends ``GET https://core.hedgetech.ir/ems-engine/ime/oms/login`` with the ``oms`` parameter.
The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
established by this call: call it with the same client right after ``Get_Captcha``.
Args:
OMS (Literal['Sahra | Karamad', 'Sahra | Charisma']): The OMS (broker system) to log into.
The format is ``'<provider> | <broker>'``.
Returns:
ImageFile: The CAPTCHA image (a ``PIL`` image opened from the response bytes). Show or save it
and pass the value you read to ``oms_login``.
Raises:
ValueError: If the HTTP status is not ``200``. The message is the server's
``detail.Status.Description.en``. If the error body does not have that structure, another
exception (for example ``KeyError``) may be raised instead.
Example:
>>> captcha = client.Get_Captcha('Sahra | Karamad')
>>> captcha.show()
"""
Captcha = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/ems-engine/ime/oms/login',
@@ -249,6 +527,41 @@ class EmsEngine_Ime_SyncClient:
password: str,
captcha_value: str,
) -> None :
"""
Logs into the OMS with provided credentials and CAPTCHA.
Sends ``POST https://core.hedgetech.ir/ems-engine/ime/oms/login`` (form data: ``username``,
``Password``, ``Captcha_Value``). Call ``Get_Captcha`` first, with the same client. All arguments
are keyword-only.
On success (HTTP ``200``) ``Customer_FullName``, ``Customer_IMEBourseCode`` and ``oms_session``
are set from the response. ``oms_session`` is required by the order creation methods and is
copied into every order when it is created: orders built before a later re-login keep the old
session.
Args:
username (str): OMS username.
password (str): OMS password.
captcha_value (str): Solved CAPTCHA value (the text of the image from ``Get_Captcha``).
Returns:
None
Raises:
ValueError: If the login fails. For HTTP ``400`` (for example a wrong CAPTCHA or wrong
credentials) the message is the server's ``detail.Status.Description.en``; for any other
non-``200`` status it is the raw response text.
Example:
>>> client.oms_login(
... username="user123",
... password="pass123",
... captcha_value="abcd",
... )
>>> print(client.oms_session)
953097ac6ced45ca8ef205b76ca6faf2
"""
response = self.__AuthSyncClient.httpx_Client.post(
@@ -289,6 +602,38 @@ class EmsEngine_Ime_SyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new buy order by contract name.
This only BUILDS the order: nothing is sent to the exchange until you call
``order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractName (str): Name of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = client.Buy_by_ContractName(
... contractName="<contract name>",
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... order.send()
"""
if self.oms_session is not None:
@@ -320,6 +665,38 @@ class EmsEngine_Ime_SyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new sell order by contract name.
This only BUILDS the order: nothing is sent to the exchange until you call
``order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractName (str): Name of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = client.Sell_by_ContractName(
... contractName="<contract name>",
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... order.send()
"""
if self.oms_session is not None:
@@ -351,6 +728,38 @@ class EmsEngine_Ime_SyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new buy order by contract id.
This only BUILDS the order: nothing is sent to the exchange until you call
``order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractId (int | str): Id of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = client.Buy_by_ContractId(
... contractId=123456,
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... order.send()
"""
if self.oms_session is not None:
@@ -382,6 +791,38 @@ class EmsEngine_Ime_SyncClient:
Price : int,
Volume :int,
)-> Order | None:
"""
Creates a new sell order by contract id.
This only BUILDS the order: nothing is sent to the exchange until you call
``order.send()`` on the returned ``Order``. No local validation of price or volume is done;
check the limits yourself if you need to.
A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
succeeded) no order is created and ``None`` is returned. The session is copied into the order at
this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
order's request.
All arguments are keyword-only.
Args:
contractId (int | str): Id of the contract.
Price (int): Order price, in IRR.
Volume (int): Order volume.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = client.Sell_by_ContractId(
... contractId=123456,
... Price=100000,
... Volume=10,
... )
>>> if order is not None:
... order.send()
"""
if self.oms_session is not None:
+1871 -243
View File
File diff suppressed because it is too large. Load diff
+2 -4
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "HedgeTech"
version = "0.4.0b1"
version = "0.4.0"
description = "A unified, high-performance API layer that powers all trading infrastructure across the HedgeTech ecosystem, providing modular, scalable, and real-time interfaces for market data, order management, and execution systems."
readme = "README.md"
requires-python = ">=3.10"
@@ -29,13 +29,11 @@ classifiers = [
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Python :: 3.15",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Financial and Insurance Industry",