14 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
mtrshirazi21 66aa5b41e6 Fixed the handling of Customer_IMEBourseCode in the EMS IME engine. 2026-10-26 16:30:11 +03:30
mtrshirazi21 f841157084 fix: correct invalid URL syntax in pyproject.toml 2026-10-26 13:25:29 +03:30
mtrshirazi21 20d99ff661 chore: release version 0.4.0b0
- Add `EmsEngine_Ime` with sync and async client implementations
- Improve class and datetime data documentation
2026-10-26 12:55:39 +03:30
mtrshirazi21 115add658f docs(ime): add full docstrings to io types and sync/async clients
- __io_types: unify commission/margin/tax docs as fractions, clarify volume and
  deal-limit fields, document None/zero semantics, fix wrong example outputs
  and type references
- DataEngine_Ime_AsyncClient / DataEngine_Ime_SyncClient: add class, __init__
  and per-method docstrings (endpoints, args, return types, errors, examples)
- document websocket stop-event behavior and silent error handling

No functional changes.
2026-10-25 18:25:52 +03:30
mtrshirazi21 57d2c7c8fd Definition of ems ime constructor 2026-10-24 23:10:40 +03:30
mtrshirazi21 a0351324f9 update sdk version 2026-09-30 10:36:26 +03:30
mtrshirazi21 3f936c17d7 Align SDK order submission mechanism with Core v2.1.0 2026-09-30 10:35:38 +03:30
mtrshirazi21 71aeebfb44 edit 2026-09-26 00:03:26 +03:30
mtrshirazi21 0aa91d4e79 add OrderOmsId to order response 2026-09-26 00:00:07 +03:30
mtrshirazi21 08244f17f2 Add Omex | Khobregan in OMS par on Get_Captcha def 2026-07-30 01:40:42 +03:30
19 changed files with 6452 additions and 1155 deletions

No files matched your search

+76 -6
View File
@@ -20,9 +20,33 @@ class AuthAsyncClient:
This class provides a high-level interface to authenticate users, manage JWT tokens, This class provides a high-level interface to authenticate users, manage JWT tokens,
and make authorized HTTP requests using an `httpx.AsyncClient`. and make authorized HTTP requests using an `httpx.AsyncClient`.
Normally an instance is created with ``AuthAsyncClient.login(...)``. Calling the
constructor directly is only useful when you already have a configured HTTP client and
a valid token. The resulting object is what the data clients
(``DataEngine_Ime_AsyncClient``, ``DataEngine_TseIfb_AsyncClient``) receive: they use
``httpx_Client`` for REST requests and ``token`` as the WebSocket headers.
Note:
* The client does not refresh the token. When the JWT expires, requests start to
fail and you need to call ``login`` again to get a new client.
* ``Permissions`` is decoded WITHOUT verifying the signature or the expiry, so it is
only meant for reading the claims (e.g. to display them), never for making
security decisions.
Attributes: Attributes:
httpx_Client (AsyncClient): An instance of `httpx.AsyncClient` configured with authentication headers. httpx_Client (AsyncClient): The HTTP client used for authorized requests. When created
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'. by ``login`` it is a ``RetriableAsyncClient`` (a wrapper around ``httpx.AsyncClient``
that retries failed requests, up to 10 times) configured with:
- the authentication headers (the token returned by the server plus an ``origin``
header) and the cookies received at login;
- HTTP/2 only (``http1=False``, ``http2=True``) with TLS verification enabled;
- short timeouts: connect 0.25 s, read 1.5 s, write 1.5 s, pool 0.25 s.
token (dict[str, str]): Dictionary containing the authentication tokens. It must contain
the ``'Authorization'`` key holding the JWT string. It is also passed as the
``additional_headers`` of WebSocket connections.
Permissions (dict): The decoded JWT payload (its claims), set by ``UpdatePermission``
when the object is created. The available claims depend on the server.
Example: Example:
>>> client = await AuthAsyncClient.login( >>> client = await AuthAsyncClient.login(
@@ -33,6 +57,7 @@ class AuthAsyncClient:
'eyJ0eXAiOi' 'eyJ0eXAiOi'
>>> client.Permissions # Decoded JWT payload >>> client.Permissions # Decoded JWT payload
{'sub': 'user_id', 'exp': 1700350200, ...} {'sub': 'user_id', 'exp': 1700350200, ...}
>>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=client)
""" """
def __init__( def __init__(
@@ -44,9 +69,25 @@ class AuthAsyncClient:
""" """
Initialize the AuthAsyncClient with an existing httpx.AsyncClient and authentication token. Initialize the AuthAsyncClient with an existing httpx.AsyncClient and authentication token.
Both arguments are keyword-only. The token is decoded immediately (see
``UpdatePermission``), so ``Permissions`` is available right after construction.
Args: Args:
httpx_Client (AsyncClient): Preconfigured AsyncClient for making authorized requests. httpx_Client (AsyncClient): Preconfigured AsyncClient for making authorized requests.
token (dict[str, str]): Dictionary containing authentication tokens. It should already send the authentication headers (``login`` does this for you).
token (dict[str, str]): Dictionary containing authentication tokens. It must contain
the ``'Authorization'`` key with the JWT string.
Raises:
ValueError: If the token cannot be decoded (see ``UpdatePermission``).
Example:
>>> client = AuthAsyncClient(
... httpx_Client=my_httpx_client,
... token={"Authorization": "<jwt>"}
... )
>>> client.Permissions
{'sub': 'user_id', 'exp': 1700350200, ...}
""" """
self.httpx_Client : AsyncClient = httpx_Client self.httpx_Client : AsyncClient = httpx_Client
@@ -61,8 +102,22 @@ class AuthAsyncClient:
""" """
Decodes the JWT 'Authorization' token to extract user permissions. Decodes the JWT 'Authorization' token to extract user permissions.
This is a **property**, not a method: reading ``client.UpdatePermission`` (without
parentheses) performs the work and returns ``None``. It is read once in ``__init__``;
read it again to re-decode ``token`` after you replace it.
The decoded payload is stored in ``self.Permissions``. The token is decoded
WITHOUT verifying the signature, and the expiry (``exp``) is not checked either.
Raises: Raises:
ValueError: If the JWT cannot be decoded. ValueError: If the JWT cannot be decoded. Any underlying error is wrapped in
``ValueError``, including a missing ``'Authorization'`` key in ``token``.
Example:
>>> client.token = new_token
>>> client.UpdatePermission # no parentheses; re-decodes the token
>>> client.Permissions
{'sub': 'user_id', 'exp': 1700350200, ...}
""" """
try : try :
@@ -92,15 +147,30 @@ class AuthAsyncClient:
This method performs the login request to the HedgeTech API, retrieves JWT tokens, This method performs the login request to the HedgeTech API, retrieves JWT tokens,
and configures an `httpx.AsyncClient` with authentication headers and cookies. and configures an `httpx.AsyncClient` with authentication headers and cookies.
It sends ``POST https://core.hedgetech.ir/auth/user/token/issue`` with the credentials as
form data. The login succeeds only when the server answers with HTTP status ``201``.
The JSON body of that answer is used as ``token`` and is also sent as headers on every
later request, together with an ``origin: https://core.hedgetech.ir`` header. The cookies
set at login are kept.
Args: Args:
UserName_or_Email (str): The username or email of the user. UserName_or_Email (str): The username or email of the user.
Password (str): The user's password. Password (str): The user's password.
Returns: Returns:
AuthAsyncClient: An initialized client ready to make authorized requests. AuthAsyncClient: An initialized client ready to make authorized requests. Its
``httpx_Client`` is a ``RetriableAsyncClient`` (10 retries) using HTTP/2 with the
short timeouts described in the class docstring.
Raises: Raises:
ValueError: If the login attempt fails (e.g., wrong credentials). ValueError: If the login attempt fails (e.g., wrong credentials), i.e. the status is
not ``201``. The message is the server's ``detail`` field, which is ``None`` if
the server did not send one. The same exception is raised if the token returned
by the server cannot be decoded (see ``UpdatePermission``).
Note:
Network errors while sending the login request (for example a connection failure or
timeout) are raised by ``httpx`` as they are and are not converted to ``ValueError``.
Example: Example:
>>> client = await AuthAsyncClient.login( >>> client = await AuthAsyncClient.login(
+79 -6
View File
@@ -21,9 +21,36 @@ class AuthSyncClient:
This class provides a high-level interface to authenticate users, manage JWT tokens, This class provides a high-level interface to authenticate users, manage JWT tokens,
and make authorized HTTP requests using an `httpx.Client`. and make authorized HTTP requests using an `httpx.Client`.
This is the blocking twin of ``AuthAsyncClient``: same login endpoint, token handling and
configuration, only the calling style differs (plain calls instead of ``await``).
Normally an instance is created with ``AuthSyncClient.login(...)``. Calling the
constructor directly is only useful when you already have a configured HTTP client and
a valid token. The resulting object is what the data clients
(``DataEngine_Ime_SyncClient``, ``DataEngine_TseIfb_SyncClient``) receive: they use
``httpx_Client`` for REST requests and ``token`` as the WebSocket headers.
Note:
* The client does not refresh the token. When the JWT expires, requests start to
fail and you need to call ``login`` again to get a new client.
* ``Permissions`` is decoded WITHOUT verifying the signature or the expiry, so it is
only meant for reading the claims (e.g. to display them), never for making
security decisions.
Attributes: Attributes:
httpx_Client (Client): An instance of `httpx.Client` configured with authentication headers. httpx_Client (Client): The HTTP client used for authorized requests. When created
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'. by ``login`` it is a ``RetriableSyncClient`` (a wrapper around ``httpx.Client``
that retries failed requests, up to 10 times) configured with:
- the authentication headers (the token returned by the server plus an ``origin``
header) and the cookies received at login;
- HTTP/2 only (``http1=False``, ``http2=True``) with TLS verification enabled;
- short timeouts: connect 0.25 s, read 1.5 s, write 1.5 s, pool 0.25 s.
token (dict[str, str]): Dictionary containing the authentication tokens. It must contain
the ``'Authorization'`` key holding the JWT string. It is also passed as the
``additional_headers`` of WebSocket connections.
Permissions (dict): The decoded JWT payload (its claims), set by ``UpdatePermission``
when the object is created. The available claims depend on the server.
Example: Example:
>>> client = AuthSyncClient.login( >>> client = AuthSyncClient.login(
@@ -34,6 +61,7 @@ class AuthSyncClient:
'eyJ0eXAiOi' 'eyJ0eXAiOi'
>>> client.Permissions # Decoded JWT payload >>> client.Permissions # Decoded JWT payload
{'sub': 'user_id', 'exp': 1700350200, ...} {'sub': 'user_id', 'exp': 1700350200, ...}
>>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=client)
""" """
def __init__( def __init__(
@@ -45,9 +73,25 @@ class AuthSyncClient:
""" """
Initialize the AuthSyncClient with an existing httpx.Client and authentication token. Initialize the AuthSyncClient with an existing httpx.Client and authentication token.
Both arguments are keyword-only. The token is decoded immediately (see
``UpdatePermission``), so ``Permissions`` is available right after construction.
Args: Args:
httpx_Client (Client): Preconfigured Client for making authorized requests. httpx_Client (Client): Preconfigured Client for making authorized requests.
token (dict[str, str]): Dictionary containing authentication tokens. It should already send the authentication headers (``login`` does this for you).
token (dict[str, str]): Dictionary containing authentication tokens. It must contain
the ``'Authorization'`` key with the JWT string.
Raises:
ValueError: If the token cannot be decoded (see ``UpdatePermission``).
Example:
>>> client = AuthSyncClient(
... httpx_Client=my_httpx_client,
... token={"Authorization": "<jwt>"}
... )
>>> client.Permissions
{'sub': 'user_id', 'exp': 1700350200, ...}
""" """
self.httpx_Client : Client = httpx_Client self.httpx_Client : Client = httpx_Client
@@ -62,8 +106,22 @@ class AuthSyncClient:
""" """
Decodes the JWT 'Authorization' token to extract user permissions. Decodes the JWT 'Authorization' token to extract user permissions.
This is a **property**, not a method: reading ``client.UpdatePermission`` (without
parentheses) performs the work and returns ``None``. It is read once in ``__init__``;
read it again to re-decode ``token`` after you replace it.
The decoded payload is stored in ``self.Permissions``. The token is decoded
WITHOUT verifying the signature, and the expiry (``exp``) is not checked either.
Raises: Raises:
ValueError: If the JWT cannot be decoded. ValueError: If the JWT cannot be decoded. Any underlying error is wrapped in
``ValueError``, including a missing ``'Authorization'`` key in ``token``.
Example:
>>> client.token = new_token
>>> client.UpdatePermission # no parentheses; re-decodes the token
>>> client.Permissions
{'sub': 'user_id', 'exp': 1700350200, ...}
""" """
try : try :
@@ -93,15 +151,30 @@ class AuthSyncClient:
This method performs the login request to the HedgeTech API, retrieves JWT tokens, This method performs the login request to the HedgeTech API, retrieves JWT tokens,
and configures an `httpx.Client` with authentication headers and cookies. and configures an `httpx.Client` with authentication headers and cookies.
It sends ``POST https://core.hedgetech.ir/auth/user/token/issue`` with the credentials as
form data. The login succeeds only when the server answers with HTTP status ``201``.
The JSON body of that answer is used as ``token`` and is also sent as headers on every
later request, together with an ``origin: https://core.hedgetech.ir`` header. The cookies
set at login are kept.
Args: Args:
UserName_or_Email (str): The username or email of the user. UserName_or_Email (str): The username or email of the user.
Password (str): The user's password. Password (str): The user's password.
Returns: Returns:
AuthSyncClient: An initialized client ready to make authorized requests. AuthSyncClient: An initialized client ready to make authorized requests. Its
``httpx_Client`` is a ``RetriableSyncClient`` (10 retries) using HTTP/2 with the
short timeouts described in the class docstring.
Raises: Raises:
ValueError: If the login attempt fails (e.g., wrong credentials). ValueError: If the login attempt fails (e.g., wrong credentials), i.e. the status is
not ``201``. The message is the server's ``detail`` field, which is ``None`` if
the server did not send one. The same exception is raised if the token returned
by the server cannot be decoded (see ``UpdatePermission``).
Note:
Network errors while sending the login request (for example a connection failure or
timeout) are raised by ``httpx`` as they are and are not converted to ``ValueError``.
Example: Example:
>>> client = AuthSyncClient.login( >>> client = AuthSyncClient.login(
+519
View File
@@ -34,11 +34,73 @@ from .__io_types import (
# ========================================|======================================== # # ========================================|======================================== #
class DataEngine_Ime_AsyncClient: class DataEngine_Ime_AsyncClient:
"""
Asynchronous client for the HedgeTech Data Engine (Iran Mercantile Exchange - IME).
This client wraps the IME endpoints of the HedgeTech Data Engine
(``core.hedgetech.ir/data-engine/ime``) and exposes them as ``async`` methods.
All requests are sent through the authenticated ``httpx`` client held by the
``AuthAsyncClient`` passed to the constructor, so the caller never handles tokens
manually.
The endpoints are grouped into three families:
1. **Static data** (contract metadata that rarely changes):
``search_contracts``, ``contracts_static_info_by_name``,
``contracts_static_info_by_id`` -> return ``Contracts``.
2. **Live snapshots** (one-shot REST requests for the current market state):
``live_overview_by_*``, ``live_best_limit_by_*``, ``live_aggregate_by_*``,
``live_contract_info_by_*``, ``live_allowed_price_range_by_*``.
3. **Live streams** (continuous WebSocket push of full market snapshots):
``websocket_by_name``, ``websocket_by_id``.
Every REST method (except ``search_contracts``) exists in two variants:
* ``*_by_name`` - contracts are identified by ``contractName``
(e.g. ``"KASH05C170"``).
* ``*_by_id`` - contracts are identified by ``contractId``
(e.g. ``"123456789"``; ``int`` values are accepted and sent as text).
Every REST response is the raw JSON body returned by the server, typed with the
response structures from ``__io_types``. Each response contains a ``Data`` section
and a ``Status`` section (see ``Status``). Whenever the HTTP status is not a
success, the method raises ``ValueError`` carrying the server's ``detail`` message.
Note:
Prices, volumes and values follow the conventions documented in
``__io_types`` (prices in IRR; commissions, margins and taxes as fractions,
e.g. ``0.0025`` = 0.25%).
Attributes:
__AuthAsyncClient (AuthAsyncClient): The authenticated client used for all
HTTP requests (via ``httpx_Client``) and for the WebSocket auth headers
(via ``token``). Stored privately (name-mangled).
Example:
>>> auth = AuthAsyncClient(...)
>>> client = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
>>> response = await client.live_best_limit_by_name(["KASH05C170"])
>>> response['Data']['KASH05C170']['1']['buy_price']
35200
"""
def __init__( def __init__(
self, self,
AuthAsyncClient : AuthAsyncClient, AuthAsyncClient : AuthAsyncClient,
): ):
"""
Create a new IME Data Engine client.
Args:
AuthAsyncClient (AuthAsyncClient): An already authenticated HedgeTech
client. Its ``httpx_Client`` is used for every REST call and its
``token`` is used as the header set for WebSocket connections.
Example:
>>> client = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
"""
self.__AuthAsyncClient = AuthAsyncClient self.__AuthAsyncClient = AuthAsyncClient
@@ -53,6 +115,39 @@ class DataEngine_Ime_AsyncClient:
], ],
Search_char : str, Search_char : str,
)-> Contracts : )-> Contracts :
"""
Search IME contracts of a given market by a text fragment.
Sends ``GET /data-engine/ime/static/data/contract/search`` and returns the
static metadata of the matching contracts.
Args:
market (Literal["IMEDepositCertificate", "IMEFutures", "IMEOption"]):
The market (instrument class) to search in. It decides which
structure the items in the result have:
``IMEDepositCertificate`` -> ``IMEDepositCertificate``,
``IMEFutures`` -> ``IMEFutures``, ``IMEOption`` -> ``IMEOption``.
Search_char (str): The text to search for (e.g. part of a contract name
such as ``"KASH05C"``).
Returns:
Contracts: ``{"Data": [...], "Status": {...}}`` where ``Data`` is the
list of matching instruments (static metadata only, no live prices).
Use the returned ``contractName`` / ``contractId`` values with the
other methods of this client.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.search_contracts(
... market="IMEOption",
... Search_char="KASH05C",
... )
>>> [item['contractName'] for item in response['Data'] if item]
['KASH05C170', 'KASH05C180']
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search', url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search',
@@ -73,6 +168,31 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def contracts_static_info_by_name(self,contract_names : List[str])-> Contracts: async def contracts_static_info_by_name(self,contract_names : List[str])-> Contracts:
"""
Get the static metadata of contracts identified by contract name.
Sends ``GET /data-engine/ime/static/data/contract/name`` with one
``contract_names`` query parameter per name.
Args:
contract_names (List[str]): Contract names to look up
(e.g. ``["KASH05C170", "KASH05P170"]``).
Returns:
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in
``Data`` is an ``IMEOption``, ``IMEFutures`` or
``IMEDepositCertificate`` structure, or ``None`` when no
instrument was found for the corresponding name.
Raises:
ValueError: If the server answers with a non-success HTTP status.
The message is the server's ``detail`` field.
Example:
>>> response = await client.contracts_static_info_by_name(["KASH05C170"])
>>> response['Data'][0]['strikePrice']
170000.0
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name', url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name',
@@ -90,6 +210,31 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def contracts_static_info_by_id(self,contract_ids : List[str | int])-> Contracts: async def contracts_static_info_by_id(self,contract_ids : List[str | int])-> Contracts:
"""
Get the static metadata of contracts identified by contract ID.
Sends ``GET /data-engine/ime/static/data/contract/id`` with one
``contract_ids`` query parameter per ID.
Args:
contract_ids (List[str | int]): Contract IDs to look up
(e.g. ``["123456789", 987654321]``).
Returns:
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in ``Data`` is
an ``IMEOption``, ``IMEFutures`` or ``IMEDepositCertificate``
structure, or ``None`` when no instrument was found for the
corresponding ID.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.contracts_static_info_by_id(["123456789"])
>>> response['Data'][0]['contractName']
'KASH05C170'
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id', url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id',
@@ -107,6 +252,34 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_overview_by_name(self,contract_names : List[str])-> OverviewResponse: async def live_overview_by_name(self,contract_names : List[str])-> OverviewResponse:
"""
Get the live market overview of contracts identified by contract name.
Sends ``GET /data-engine/ime/live/data/overview/contract/name``. The overview
combines each contract's static metadata with its live ``BestLimit``,
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo`` sections in a single
request.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every requested contract name to an ``OverviewIMEOption``,
``OverviewIMEFutures`` or ``OverviewIMEDepositCertificate``
structure, or to ``None`` if the contract was not found.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_overview_by_name(["KASH05C170"])
>>> overview = response['Data']['KASH05C170']
>>> if overview:
... print(overview['Aggregate']['last_price'])
35250.0
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name',
@@ -124,6 +297,33 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_overview_by_id(self,contract_ids : List[str | int])-> OverviewResponse: async def live_overview_by_id(self,contract_ids : List[str | int])-> OverviewResponse:
"""
Get the live market overview of contracts identified by contract ID.
Sends ``GET /data-engine/ime/live/data/overview/contract/id``. Same content
as ``live_overview_by_name`` (static metadata + live ``BestLimit``,
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo``), but the keys of
``Data`` are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every requested contract ID to its overview structure, or to
``None`` if the contract was not found.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_overview_by_id(["123456789"])
>>> overview = response['Data']['123456789']
>>> if overview:
... print(overview['BestLimit']['1']['buy_price'])
35200
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id',
@@ -141,6 +341,33 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_best_limit_by_name(self,contract_names : List[str])-> BestLimitResponse: async def live_best_limit_by_name(self,contract_names : List[str])-> BestLimitResponse:
"""
Get the live best-limit order book of contracts identified by contract name.
Sends ``GET /data-engine/ime/live/data/best-limit/contract/name``.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract name to its order book, a dictionary with up to three
levels (``"1"`` best, ``"2"``, ``"3"``), each a ``BestLimitItem``
(``buy_quantity``, ``buy_price``, ``sell_quantity``, ``sell_price``).
Empty sides carry zero values, so check that a price is greater than
zero before using it.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_best_limit_by_name(["KASH05C170"])
>>> level = response['Data']['KASH05C170']['1']
>>> if level['buy_price'] > 0 and level['sell_price'] > 0:
... print(level['sell_price'] - level['buy_price'])
100
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name',
@@ -158,6 +385,29 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_best_limit_by_id(self,contract_ids : List[str | int])-> BestLimitResponse: async def live_best_limit_by_id(self,contract_ids : List[str | int])-> BestLimitResponse:
"""
Get the live best-limit order book of contracts identified by contract ID.
Sends ``GET /data-engine/ime/live/data/best-limit/contract/id``. Same content
as ``live_best_limit_by_name`` but the keys of ``Data`` are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract ID to its order book levels (``"1"``, ``"2"``,
``"3"``), each a ``BestLimitItem``. Empty sides carry zero values.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_best_limit_by_id(["123456789"])
>>> response['Data']['123456789']['1']['sell_price']
35300
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id',
@@ -175,6 +425,32 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_aggregate_by_name(self,contract_names : List[str])-> AggregateResponse: async def live_aggregate_by_name(self,contract_names : List[str])-> AggregateResponse:
"""
Get the live aggregate trading statistics of contracts identified by name.
Sends ``GET /data-engine/ime/live/data/aggregate/contract/name``.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract name to an ``Aggregate`` structure: ``date``,
``time``, ``trade_count``, ``total_volume``, ``total_value`` (IRR),
and the OHLC-style prices ``open_price``, ``high_price``,
``low_price``, ``last_price``, ``closing_price`` and
``previous_close``.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_aggregate_by_name(["KASH05C170"])
>>> agg = response['Data']['KASH05C170']
>>> (agg['closing_price'] - agg['previous_close']) / agg['previous_close'] * 100
0.8
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name',
@@ -193,6 +469,29 @@ class DataEngine_Ime_AsyncClient:
async def live_aggregate_by_id(self,contract_ids : List[str | int])-> AggregateResponse : async def live_aggregate_by_id(self,contract_ids : List[str | int])-> AggregateResponse :
"""
Get the live aggregate trading statistics of contracts identified by ID.
Sends ``GET /data-engine/ime/live/data/aggregate/contract/id``. Same content
as ``live_aggregate_by_name`` but the keys of ``Data`` are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract ID to an ``Aggregate`` structure (trade count, volume,
value and OHLC-style prices).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_aggregate_by_id(["123456789"])
>>> response['Data']['123456789']['last_price']
35250.0
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id',
@@ -210,6 +509,30 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_contract_info_by_name(self,contract_names : List[str])-> ContractInfoResponse: async def live_contract_info_by_name(self,contract_names : List[str])-> ContractInfoResponse:
"""
Get the live contract information (open interest) of contracts by name.
Sends ``GET /data-engine/ime/live/data/contract-info/contract/name``.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract name to a ``ContractInfo`` structure with
``open_interest`` (number of open positions) and
``open_interest_changes`` (change versus the previous period;
positive = increase, negative = decrease).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_contract_info_by_name(["KASH05C170"])
>>> response['Data']['KASH05C170']['open_interest']
15000
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name',
@@ -228,6 +551,30 @@ class DataEngine_Ime_AsyncClient:
async def live_contract_info_by_id(self,contract_ids : List[str | int])-> ContractInfoResponse : async def live_contract_info_by_id(self,contract_ids : List[str | int])-> ContractInfoResponse :
"""
Get the live contract information (open interest) of contracts by ID.
Sends ``GET /data-engine/ime/live/data/contract-info/contract/id``. Same
content as ``live_contract_info_by_name`` but the keys of ``Data`` are
contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract ID to a ``ContractInfo`` structure (``open_interest``
and ``open_interest_changes``).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_contract_info_by_id(["123456789"])
>>> response['Data']['123456789']['open_interest_changes']
250
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id',
@@ -245,6 +592,32 @@ class DataEngine_Ime_AsyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
async def live_allowed_price_range_by_name(self,contract_names : List[str])-> AllowedPriceRangeResponse: async def live_allowed_price_range_by_name(self,contract_names : List[str])-> AllowedPriceRangeResponse:
"""
Get the live allowed (daily limit) price range of contracts by name.
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/name``.
Orders placed outside this range are rejected by the exchange, so it is
useful to clamp prices before sending an order.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
maps every contract name to an ``AllowedPriceRange`` structure with
``minAllowedPrice`` (lower limit) and ``maxAllowedPrice`` (upper
limit).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_allowed_price_range_by_name(["KASH05C170"])
>>> limits = response['Data']['KASH05C170']
>>> limits['minAllowedPrice'], limits['maxAllowedPrice']
(23500.0, 26500.0)
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name',
@@ -263,6 +636,30 @@ class DataEngine_Ime_AsyncClient:
async def live_allowed_price_range_by_id(self,contract_ids : List[str | int])-> AllowedPriceRangeResponse : async def live_allowed_price_range_by_id(self,contract_ids : List[str | int])-> AllowedPriceRangeResponse :
"""
Get the live allowed (daily limit) price range of contracts by ID.
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/id``.
Same content as ``live_allowed_price_range_by_name`` but the keys of ``Data``
are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
maps every contract ID to an ``AllowedPriceRange`` structure
(``minAllowedPrice`` and ``maxAllowedPrice``).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = await client.live_allowed_price_range_by_id(["123456789"])
>>> response['Data']['123456789']['maxAllowedPrice']
26500.0
"""
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id',
@@ -288,6 +685,68 @@ class DataEngine_Ime_AsyncClient:
WebsocketBase_contractName, WebsocketBase_contractName,
None None
]: ]:
"""
Stream live market data for contracts identified by contract name.
Opens a WebSocket connection to
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name``
(one ``contract_name`` query parameter per name, authenticated with the
``AuthAsyncClient`` token) and yields every message received as a decoded
``WebsocketBase_contractName`` dictionary.
Each message is a full snapshot for one contract::
{
"channel": "IME Stream",
"contractName": "KASH05C170",
"timestamp": "2025-01-15T14:30:00.123456",
"data": {"BestLimit": ..., "Aggregate": ...,
"AllowedPriceRange": ..., "ContractInfo": ...},
}
Messages for all requested contracts arrive on the same connection, so use
``message['contractName']`` to tell them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (for
example from another task) to stop it. The check happens each time a
message arrives, after a receive timeout (2 seconds without messages),
and when the generator is resumed, so the stream ends within about 2
seconds at most. The connection is closed automatically when the
generator finishes.
Args:
contract_names (List[str]): Contract names to subscribe to.
event (Event | None): Optional ``asyncio.Event`` used as a stop switch.
It must be set for the stream to run. If ``None`` (or not an
``Event``), an already-set internal event is created, which means
the stream runs until the connection ends.
Yields:
WebsocketBase_contractName: One live message per update, containing
``channel``, ``contractName``, ``timestamp`` and ``data``
(a ``Websocket_data`` snapshot).
Note:
* Any error after the connection is established (connection closed by
the server, invalid JSON, network error, ...) is swallowed: the
connection is closed and the generator simply ends without raising.
If you need a permanent stream, wrap the ``async for`` loop in a
reconnect loop.
* Errors while connecting (for example authentication failure) are
raised by ``connect`` and are not caught here.
* A receive timeout is not an error; the generator just keeps waiting.
Example:
>>> stop = Event()
>>> stop.set()
>>> async for message in client.websocket_by_name(["KASH05C170"], event=stop):
... best = message['data']['BestLimit']['1']
... print(message['contractName'], best['buy_price'], best['sell_price'])
... if best['buy_price'] >= 36000:
... stop.clear()
KASH05C170 35200 35300
"""
if not isinstance(event,Event): if not isinstance(event,Event):
event = Event() event = Event()
@@ -323,6 +782,66 @@ class DataEngine_Ime_AsyncClient:
WebsocketBase_contractId, WebsocketBase_contractId,
None None
]: ]:
"""
Stream live market data for contracts identified by contract ID.
Opens a WebSocket connection to
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id``
(one ``contract_id`` query parameter per ID, authenticated with the
``AuthAsyncClient`` token) and yields every message received as a decoded
``WebsocketBase_contractId`` dictionary.
Each message is a full snapshot for one contract::
{
"channel": "IME Stream",
"contractId": "123456789",
"timestamp": "2025-01-15T14:30:00.123456",
"data": {"BestLimit": ..., "Aggregate": ...,
"AllowedPriceRange": ..., "ContractInfo": ...},
}
Messages for all requested contracts arrive on the same connection, so use
``message['contractId']`` to tell them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (for
example from another task) to stop it. The check happens each time a
message arrives, after a receive timeout (2 seconds without messages),
and when the generator is resumed, so the stream ends within about 2
seconds at most. The connection is closed automatically when the
generator finishes.
Args:
contract_ids (List[str | int]): Contract IDs to subscribe to.
event (Event | None): Optional ``asyncio.Event`` used as a stop switch.
It must be set for the stream to run. If ``None`` (or not an
``Event``), an already-set internal event is created, which means
the stream runs until the connection ends.
Yields:
WebsocketBase_contractId: One live message per update, containing
``channel``, ``contractId``, ``timestamp`` and ``data``
(a ``Websocket_data`` snapshot).
Note:
* Any error after the connection is established (connection closed by
the server, invalid JSON, network error, ...) is swallowed: the
connection is closed and the generator simply ends without raising.
If you need a permanent stream, wrap the ``async for`` loop in a
reconnect loop.
* Errors while connecting (for example authentication failure) are
raised by ``connect`` and are not caught here.
* A receive timeout is not an error; the generator just keeps waiting.
Example:
>>> stop = Event()
>>> stop.set()
>>> async for message in client.websocket_by_id(["123456789"], event=stop):
... print(message['contractId'], message['data']['Aggregate']['last_price'])
... stop.clear()
123456789 35250.0
"""
if not isinstance(event,Event): if not isinstance(event,Event):
event = Event() event = Event()
+529 -1
View File
@@ -29,11 +29,77 @@ from .__io_types import (
# ========================================|======================================== # # ========================================|======================================== #
class DataEngine_Ime_SyncClient: class DataEngine_Ime_SyncClient:
"""
Synchronous (blocking) client for the HedgeTech Data Engine (Iran Mercantile Exchange - IME).
This client wraps the IME endpoints of the HedgeTech Data Engine
(``core.hedgetech.ir/data-engine/ime``) as regular blocking methods. All requests
are sent through the authenticated ``httpx`` client held by the ``AuthSyncClient``
passed to the constructor, so the caller never handles tokens manually.
The endpoints are grouped into three families:
1. **Static data** (contract metadata that rarely changes):
``search_contracts``, ``contracts_static_info_by_name``,
``contracts_static_info_by_id`` -> return ``Contracts``.
2. **Live snapshots** (one-shot REST requests for the current market state):
``live_overview_by_*``, ``live_best_limit_by_*``, ``live_aggregate_by_*``,
``live_contract_info_by_*``, ``live_allowed_price_range_by_*``.
3. **Live streams** (continuous WebSocket push of full market snapshots):
``websocket_by_name``, ``websocket_by_id``.
Every REST method (except ``search_contracts``) exists in two variants:
* ``*_by_name`` - contracts are identified by ``contractName``
(e.g. ``"KASH05C170"``).
* ``*_by_id`` - contracts are identified by ``contractId``
(e.g. ``"123456789"``; ``int`` values are accepted and sent as text).
Every REST response is the raw JSON body returned by the server, typed with the
response structures from ``__io_types``. Each response contains a ``Data`` section
and a ``Status`` section (see ``Status``). Whenever the HTTP status is not a
success, the method raises ``ValueError`` carrying the server's ``detail`` message.
This is the blocking twin of ``DataEngine_Ime_AsyncClient``: the endpoints,
arguments and return types are identical, only the calling style differs
(plain calls instead of ``await``, ``threading.Event`` instead of
``asyncio.Event``, a normal generator instead of an async generator).
Note:
Prices, volumes and values follow the conventions documented in
``__io_types`` (prices in IRR; commissions, margins and taxes as fractions,
e.g. ``0.0025`` = 0.25%).
Attributes:
__AuthSyncClient (AuthSyncClient): The authenticated client used for all
HTTP requests (via ``httpx_Client``) and for the WebSocket auth headers
(via ``token``). Stored privately (name-mangled).
Example:
>>> auth = AuthSyncClient(...)
>>> client = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
>>> response = client.live_best_limit_by_name(["KASH05C170"])
>>> response['Data']['KASH05C170']['1']['buy_price']
35200
"""
def __init__( def __init__(
self, self,
AuthSyncClient : AuthSyncClient, AuthSyncClient : AuthSyncClient,
): ):
"""
Create a new IME Data Engine client.
Args:
AuthSyncClient (AuthSyncClient): An already authenticated HedgeTech
client. Its ``httpx_Client`` is used for every REST call and its
``token`` is used as the header set for WebSocket connections.
Example:
>>> client = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
"""
self.__AuthSyncClient = AuthSyncClient self.__AuthSyncClient = AuthSyncClient
@@ -48,6 +114,39 @@ class DataEngine_Ime_SyncClient:
], ],
Search_char : str, Search_char : str,
)-> Contracts : )-> Contracts :
"""
Search IME contracts of a given market by a text fragment.
Sends ``GET /data-engine/ime/static/data/contract/search`` and returns the
static metadata of the matching contracts.
Args:
market (Literal["IMEDepositCertificate", "IMEFutures", "IMEOption"]):
The market (instrument class) to search in. It decides which
structure the items in the result have:
``IMEDepositCertificate`` -> ``IMEDepositCertificate``,
``IMEFutures`` -> ``IMEFutures``, ``IMEOption`` -> ``IMEOption``.
Search_char (str): The text to search for (e.g. part of a contract name
such as ``"KASH05C"``).
Returns:
Contracts: ``{"Data": [...], "Status": {...}}`` where ``Data`` is the
list of matching instruments (static metadata only, no live prices).
Use the returned ``contractName`` / ``contractId`` values with the
other methods of this client.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.search_contracts(
... market="IMEOption",
... Search_char="KASH05C",
... )
>>> [item['contractName'] for item in response['Data'] if item]
['KASH05C170', 'KASH05C180']
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search', url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search',
@@ -68,6 +167,31 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def contracts_static_info_by_name(self,contract_names : List[str])-> Contracts: def contracts_static_info_by_name(self,contract_names : List[str])-> Contracts:
"""
Get the static metadata of contracts identified by contract name.
Sends ``GET /data-engine/ime/static/data/contract/name`` with one
``contract_names`` query parameter per name.
Args:
contract_names (List[str]): Contract names to look up
(e.g. ``["KASH05C170", "KASH05P170"]``).
Returns:
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in
``Data`` is an ``IMEOption``, ``IMEFutures`` or
``IMEDepositCertificate`` structure, or ``None`` when no
instrument was found for the corresponding name.
Raises:
ValueError: If the server answers with a non-success HTTP status.
The message is the server's ``detail`` field.
Example:
>>> response = client.contracts_static_info_by_name(["KASH05C170"])
>>> response['Data'][0]['strikePrice']
170000.0
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name', url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name',
@@ -85,6 +209,31 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def contracts_static_info_by_id(self,contract_ids : List[str | int])-> Contracts: def contracts_static_info_by_id(self,contract_ids : List[str | int])-> Contracts:
"""
Get the static metadata of contracts identified by contract ID.
Sends ``GET /data-engine/ime/static/data/contract/id`` with one
``contract_ids`` query parameter per ID.
Args:
contract_ids (List[str | int]): Contract IDs to look up
(e.g. ``["123456789", 987654321]``).
Returns:
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in ``Data`` is
an ``IMEOption``, ``IMEFutures`` or ``IMEDepositCertificate``
structure, or ``None`` when no instrument was found for the
corresponding ID.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.contracts_static_info_by_id(["123456789"])
>>> response['Data'][0]['contractName']
'KASH05C170'
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id', url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id',
@@ -102,6 +251,34 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_overview_by_name(self,contract_names : List[str])-> OverviewResponse: def live_overview_by_name(self,contract_names : List[str])-> OverviewResponse:
"""
Get the live market overview of contracts identified by contract name.
Sends ``GET /data-engine/ime/live/data/overview/contract/name``. The overview
combines each contract's static metadata with its live ``BestLimit``,
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo`` sections in a single
request.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every requested contract name to an ``OverviewIMEOption``,
``OverviewIMEFutures`` or ``OverviewIMEDepositCertificate``
structure, or to ``None`` if the contract was not found.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_overview_by_name(["KASH05C170"])
>>> overview = response['Data']['KASH05C170']
>>> if overview:
... print(overview['Aggregate']['last_price'])
35250.0
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name',
@@ -119,6 +296,33 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_overview_by_id(self,contract_ids : List[str | int])-> OverviewResponse: def live_overview_by_id(self,contract_ids : List[str | int])-> OverviewResponse:
"""
Get the live market overview of contracts identified by contract ID.
Sends ``GET /data-engine/ime/live/data/overview/contract/id``. Same content
as ``live_overview_by_name`` (static metadata + live ``BestLimit``,
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo``), but the keys of
``Data`` are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every requested contract ID to its overview structure, or to
``None`` if the contract was not found.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_overview_by_id(["123456789"])
>>> overview = response['Data']['123456789']
>>> if overview:
... print(overview['BestLimit']['1']['buy_price'])
35200
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id',
@@ -136,6 +340,33 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_best_limit_by_name(self,contract_names : List[str])-> BestLimitResponse: def live_best_limit_by_name(self,contract_names : List[str])-> BestLimitResponse:
"""
Get the live best-limit order book of contracts identified by contract name.
Sends ``GET /data-engine/ime/live/data/best-limit/contract/name``.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract name to its order book, a dictionary with up to three
levels (``"1"`` best, ``"2"``, ``"3"``), each a ``BestLimitItem``
(``buy_quantity``, ``buy_price``, ``sell_quantity``, ``sell_price``).
Empty sides carry zero values, so check that a price is greater than
zero before using it.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_best_limit_by_name(["KASH05C170"])
>>> level = response['Data']['KASH05C170']['1']
>>> if level['buy_price'] > 0 and level['sell_price'] > 0:
... print(level['sell_price'] - level['buy_price'])
100
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name',
@@ -153,6 +384,29 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_best_limit_by_id(self,contract_ids : List[str | int])-> BestLimitResponse: def live_best_limit_by_id(self,contract_ids : List[str | int])-> BestLimitResponse:
"""
Get the live best-limit order book of contracts identified by contract ID.
Sends ``GET /data-engine/ime/live/data/best-limit/contract/id``. Same content
as ``live_best_limit_by_name`` but the keys of ``Data`` are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract ID to its order book levels (``"1"``, ``"2"``,
``"3"``), each a ``BestLimitItem``. Empty sides carry zero values.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_best_limit_by_id(["123456789"])
>>> response['Data']['123456789']['1']['sell_price']
35300
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id',
@@ -170,6 +424,32 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_aggregate_by_name(self,contract_names : List[str])-> AggregateResponse: def live_aggregate_by_name(self,contract_names : List[str])-> AggregateResponse:
"""
Get the live aggregate trading statistics of contracts identified by name.
Sends ``GET /data-engine/ime/live/data/aggregate/contract/name``.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract name to an ``Aggregate`` structure: ``date``,
``time``, ``trade_count``, ``total_volume``, ``total_value`` (IRR),
and the OHLC-style prices ``open_price``, ``high_price``,
``low_price``, ``last_price``, ``closing_price`` and
``previous_close``.
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_aggregate_by_name(["KASH05C170"])
>>> agg = response['Data']['KASH05C170']
>>> (agg['closing_price'] - agg['previous_close']) / agg['previous_close'] * 100
0.8
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name',
@@ -188,6 +468,29 @@ class DataEngine_Ime_SyncClient:
def live_aggregate_by_id(self,contract_ids : List[str | int])-> AggregateResponse : def live_aggregate_by_id(self,contract_ids : List[str | int])-> AggregateResponse :
"""
Get the live aggregate trading statistics of contracts identified by ID.
Sends ``GET /data-engine/ime/live/data/aggregate/contract/id``. Same content
as ``live_aggregate_by_name`` but the keys of ``Data`` are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract ID to an ``Aggregate`` structure (trade count, volume,
value and OHLC-style prices).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_aggregate_by_id(["123456789"])
>>> response['Data']['123456789']['last_price']
35250.0
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id',
@@ -205,6 +508,30 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_contract_info_by_name(self,contract_names : List[str])-> ContractInfoResponse: def live_contract_info_by_name(self,contract_names : List[str])-> ContractInfoResponse:
"""
Get the live contract information (open interest) of contracts by name.
Sends ``GET /data-engine/ime/live/data/contract-info/contract/name``.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract name to a ``ContractInfo`` structure with
``open_interest`` (number of open positions) and
``open_interest_changes`` (change versus the previous period;
positive = increase, negative = decrease).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_contract_info_by_name(["KASH05C170"])
>>> response['Data']['KASH05C170']['open_interest']
15000
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name',
@@ -223,6 +550,30 @@ class DataEngine_Ime_SyncClient:
def live_contract_info_by_id(self,contract_ids : List[str | int])-> ContractInfoResponse : def live_contract_info_by_id(self,contract_ids : List[str | int])-> ContractInfoResponse :
"""
Get the live contract information (open interest) of contracts by ID.
Sends ``GET /data-engine/ime/live/data/contract-info/contract/id``. Same
content as ``live_contract_info_by_name`` but the keys of ``Data`` are
contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
every contract ID to a ``ContractInfo`` structure (``open_interest``
and ``open_interest_changes``).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_contract_info_by_id(["123456789"])
>>> response['Data']['123456789']['open_interest_changes']
250
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id',
@@ -240,6 +591,32 @@ class DataEngine_Ime_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def live_allowed_price_range_by_name(self,contract_names : List[str])-> AllowedPriceRangeResponse: def live_allowed_price_range_by_name(self,contract_names : List[str])-> AllowedPriceRangeResponse:
"""
Get the live allowed (daily limit) price range of contracts by name.
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/name``.
Orders placed outside this range are rejected by the exchange, so it is
useful to clamp prices before sending an order.
Args:
contract_names (List[str]): Contract names to look up.
Returns:
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
maps every contract name to an ``AllowedPriceRange`` structure with
``minAllowedPrice`` (lower limit) and ``maxAllowedPrice`` (upper
limit).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_allowed_price_range_by_name(["KASH05C170"])
>>> limits = response['Data']['KASH05C170']
>>> limits['minAllowedPrice'], limits['maxAllowedPrice']
(23500.0, 26500.0)
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name', url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name',
@@ -258,6 +635,30 @@ class DataEngine_Ime_SyncClient:
def live_allowed_price_range_by_id(self,contract_ids : List[str | int])-> AllowedPriceRangeResponse : def live_allowed_price_range_by_id(self,contract_ids : List[str | int])-> AllowedPriceRangeResponse :
"""
Get the live allowed (daily limit) price range of contracts by ID.
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/id``.
Same content as ``live_allowed_price_range_by_name`` but the keys of ``Data``
are contract IDs.
Args:
contract_ids (List[str | int]): Contract IDs to look up.
Returns:
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
maps every contract ID to an ``AllowedPriceRange`` structure
(``minAllowedPrice`` and ``maxAllowedPrice``).
Raises:
ValueError: If the server answers with a non-success HTTP status. The
message is the server's ``detail`` field.
Example:
>>> response = client.live_allowed_price_range_by_id(["123456789"])
>>> response['Data']['123456789']['maxAllowedPrice']
26500.0
"""
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id', url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id',
@@ -283,6 +684,71 @@ class DataEngine_Ime_SyncClient:
None, None,
None None
]: ]:
"""
Stream live market data for contracts identified by contract name.
Opens a blocking WebSocket connection to
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name``
(one ``contract_name`` query parameter per name, authenticated with the
``AuthSyncClient`` token) and yields every message received as a decoded
``WebsocketBase_contractName`` dictionary.
Each message is a full snapshot for one contract::
{
"channel": "IME Stream",
"contractName": "KASH05C170",
"timestamp": "2025-01-15T14:30:00.123456",
"data": {"BestLimit": ..., "Aggregate": ...,
"AllowedPriceRange": ..., "ContractInfo": ...},
}
Messages for all requested contracts arrive on the same connection, so use
``message['contractName']`` to tell them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (typically
from another thread, since the iterating thread is blocked while
waiting) to stop it. The check happens each time a message arrives and
after a receive timeout (2 seconds without messages), so the stream
ends within about 2 seconds at most. The connection is closed
automatically when the generator finishes.
Args:
contract_names (List[str]): Contract names to subscribe to.
event (threading.Event | None): Optional ``threading.Event`` used as a
stop switch. It must be set for the stream to run. If ``None`` (or
not an ``Event``), an already-set internal event is created, which
means the stream runs until the connection ends.
Yields:
WebsocketBase_contractName: One live message per update, containing
``channel``, ``contractName``, ``timestamp`` and ``data``
(a ``Websocket_data`` snapshot).
Note:
* This generator blocks the calling thread while waiting for messages.
Run it in a dedicated thread if the rest of your program must keep
working.
* Any error after the connection is established (connection closed by
the server, invalid JSON, network error, ...) is swallowed: the
connection is closed and the generator simply ends without raising.
If you need a permanent stream, wrap the ``for`` loop in a reconnect
loop.
* Errors while connecting (for example authentication failure) are
raised by ``connect`` and are not caught here.
* A receive timeout is not an error; the generator just keeps waiting.
Example:
>>> stop = Event()
>>> stop.set()
>>> for message in client.websocket_by_name(["KASH05C170"], event=stop):
... best = message['data']['BestLimit']['1']
... print(message['contractName'], best['buy_price'], best['sell_price'])
... if best['buy_price'] >= 36000:
... stop.clear()
KASH05C170 35200 35300
"""
if not isinstance(event,Event): if not isinstance(event,Event):
event = Event() event = Event()
@@ -316,6 +782,69 @@ class DataEngine_Ime_SyncClient:
None, None,
None None
]: ]:
"""
Stream live market data for contracts identified by contract ID.
Opens a blocking WebSocket connection to
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id``
(one ``contract_id`` query parameter per ID, authenticated with the
``AuthSyncClient`` token) and yields every message received as a decoded
``WebsocketBase_contractId`` dictionary.
Each message is a full snapshot for one contract::
{
"channel": "IME Stream",
"contractId": "123456789",
"timestamp": "2025-01-15T14:30:00.123456",
"data": {"BestLimit": ..., "Aggregate": ...,
"AllowedPriceRange": ..., "ContractInfo": ...},
}
Messages for all requested contracts arrive on the same connection, so use
``message['contractId']`` to tell them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (typically
from another thread, since the iterating thread is blocked while
waiting) to stop it. The check happens each time a message arrives and
after a receive timeout (2 seconds without messages), so the stream
ends within about 2 seconds at most. The connection is closed
automatically when the generator finishes.
Args:
contract_ids (List[str | int]): Contract IDs to subscribe to.
event (threading.Event | None): Optional ``threading.Event`` used as a
stop switch. It must be set for the stream to run. If ``None`` (or
not an ``Event``), an already-set internal event is created, which
means the stream runs until the connection ends.
Yields:
WebsocketBase_contractId: One live message per update, containing
``channel``, ``contractId``, ``timestamp`` and ``data``
(a ``Websocket_data`` snapshot).
Note:
* This generator blocks the calling thread while waiting for messages.
Run it in a dedicated thread if the rest of your program must keep
working.
* Any error after the connection is established (connection closed by
the server, invalid JSON, network error, ...) is swallowed: the
connection is closed and the generator simply ends without raising.
If you need a permanent stream, wrap the ``for`` loop in a reconnect
loop.
* Errors while connecting (for example authentication failure) are
raised by ``connect`` and are not caught here.
* A receive timeout is not an error; the generator just keeps waiting.
Example:
>>> stop = Event()
>>> stop.set()
>>> for message in client.websocket_by_id(["123456789"], event=stop):
... print(message['contractId'], message['data']['Aggregate']['last_price'])
... stop.clear()
123456789 35250.0
"""
if not isinstance(event,Event): if not isinstance(event,Event):
event = Event() event = Event()
@@ -336,4 +865,3 @@ class DataEngine_Ime_SyncClient:
except Exception: except Exception:
ws.close() ws.close()
break break
@@ -17,11 +17,18 @@ from typing import (
class WebsocketBase_contractId(TypedDict): class WebsocketBase_contractId(TypedDict):
""" """
Base structure for websocket messages containing IME contract information Minimal base structure for websocket messages containing IME contract information
identified by Contract ID. identified by Contract ID.
This TypedDict defines the common structure of messages received over a websocket This TypedDict defines the common envelope of messages received over a websocket
where each message is linked to a specific IME Contract ID. where each message is linked to a specific IME Contract ID. It does NOT include the
live market payload (``data``).
Note:
A class with the same name is defined again later in this file, which also
includes the ``data`` field (the full live-stream message). Because Python
keeps the last definition, the later one is the one that takes effect at
runtime and for type checkers.
Attributes: Attributes:
channel (str): The name of the websocket channel through which the message is sent. channel (str): The name of the websocket channel through which the message is sent.
@@ -43,11 +50,18 @@ class WebsocketBase_contractId(TypedDict):
class WebsocketBase_contractName(TypedDict): class WebsocketBase_contractName(TypedDict):
""" """
Base structure for websocket messages containing IME contract information Minimal base structure for websocket messages containing IME contract information
identified by contract name. identified by contract name.
This TypedDict defines the common structure of messages received over a websocket This TypedDict defines the common envelope of messages received over a websocket
where each message is linked to a specific contract name. where each message is linked to a specific contract name. It does NOT include the
live market payload (``data``).
Note:
A class with the same name is defined again later in this file, which also
includes the ``data`` field (the full live-stream message). Because Python
keeps the last definition, the later one is the one that takes effect at
runtime and for type checkers.
Attributes: Attributes:
channel (str): The name of the websocket channel through which the message is sent. channel (str): The name of the websocket channel through which the message is sent.
@@ -96,12 +110,16 @@ class Status(TypedDict):
Attributes: Attributes:
State (bool): Indicates whether the operation or request was successful. State (bool): Indicates whether the operation or request was successful.
ServerTimeStamp (float): Server timestamp, typically a Unix timestamp. ServerTimeStamp (float): Server time as a Unix timestamp (seconds since epoch,
may include fractional seconds). Note that this is a
number, unlike the ISO-formatted string ``timestamp``
used in websocket messages.
Version (str): Version of the API or server sending the message. Version (str): Version of the API or server sending the message.
Author (str): Name of the author or owner of the API/server. Author (str): Name of the author or owner of the API/server.
Description (StatusDescription): A human-readable description of the status Description (StatusDescription): A human-readable description of the status
in multiple languages. in multiple languages.
StatusCode (int): Numeric status code returned by the server. StatusCode (int): Numeric status code returned by the server (HTTP-style,
e.g. 200 for success).
Example: Example:
>>> status: Status = { >>> status: Status = {
@@ -132,23 +150,27 @@ class IMEDepositCertificate(TypedDict):
traded on the Iran Mercantile Exchange (IME), including identification, trading rules, traded on the Iran Mercantile Exchange (IME), including identification, trading rules,
commission rates, volume limits, and storage costs. commission rates, volume limits, and storage costs.
Note:
Rates such as commissions are expressed as fractions, not percentages
(e.g. ``0.0025`` means 0.25%). Multiply by 100 to display a percentage.
Attributes: Attributes:
contractId (str): Unique contractId code identifying the certificate. contractId (str): Unique identifier of the certificate.
title (str): Full display name of the deposit certificate. title (str): Full display name of the deposit certificate.
contractName (str): Short name or ticker contract of the certificate. contractName (str): Short name / ticker of the certificate.
minPriceChangeRate (float): Minimum allowed price change rate (tick size). minPriceChangeRate (float): Minimum allowed price change rate (tick size).
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit). maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
owner (str): Market or organization that owns the certificate. owner (str): Market or organization that owns the certificate.
buyCommission (float): Commission rate applied when buying (as percentage or fixed). buyCommission (float): Commission rate applied when buying (fraction, e.g. 0.0025 = 0.25%).
sellCommission (float): Commission rate applied when selling (as percentage or fixed). sellCommission (float): Commission rate applied when selling (fraction, e.g. 0.0025 = 0.25%).
canBuy (bool): Indicates if the certificate can currently be bought. canBuy (bool): Indicates if the certificate can currently be bought.
canSell (bool): Indicates if the certificate can currently be sold. canSell (bool): Indicates if the certificate can currently be sold.
minValidBuyVolume (int): Minimum allowed buy order volume (lot size). minValidBuyVolume (int): Minimum allowed volume for a single buy order.
maxValidBuyVolume (int): Maximum allowed buy order volume (lot size). maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
minValidSellVolume (int): Minimum allowed sell order volume (lot size). minValidSellVolume (int): Minimum allowed volume for a single sell order.
maxValidSellVolume (int): Maximum allowed sell order volume (lot size). maxValidSellVolume (int): Maximum allowed volume for a single sell order.
minDealablePrice (float): Minimum price per trade (floor price). minDealablePrice (float): Minimum price at which a trade can be executed (floor price).
minDealableCount (int): Minimum quantity per trade (minimum lot size). minDealableCount (int): Minimum quantity that can be traded in a single deal.
StorageCost (float): Storage cost associated with the certificate (warehousing fee). StorageCost (float): Storage cost associated with the certificate (warehousing fee).
dataClass (str): Internal classification or source of the instrument data. dataClass (str): Internal classification or source of the instrument data.
@@ -208,35 +230,41 @@ class IMEFutures(TypedDict):
traded on the Iran Mercantile Exchange (IME), including identification, margin requirements, traded on the Iran Mercantile Exchange (IME), including identification, margin requirements,
trading rules, expiration details, exercise fees, and underlying asset information. trading rules, expiration details, exercise fees, and underlying asset information.
Note:
Margins, commissions and taxes are expressed as fractions, not percentages
(e.g. ``0.10`` means 10%). Multiply by 100 to display a percentage.
Attributes: Attributes:
contractId (str): Unique contractId code identifying the futures contract. contractId (str): Unique identifier of the futures contract.
title (str): Full display name of the futures contract. title (str): Full display name of the futures contract.
contractName (str): Short name or ticker contract of the futures instrument. contractName (str): Short name / ticker of the futures instrument.
initialMargin (float): Initial margin required to open a position (as percentage or fixed). initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.10 = 10%).
maintenanceMargin (float): Minimum maintenance margin required to keep position open. maintenanceMargin (float): Minimum maintenance margin required to keep a position open (fraction).
minPriceChangeRate (float): Minimum allowed price change rate (tick size). minPriceChangeRate (float): Minimum allowed price change rate (tick size).
maxPriceChangeRate (float): Maximum allowed price change rate (daily price limit). maxPriceChangeRate (float): Maximum allowed price change rate (daily price limit).
owner (str): Market or organization that owns the instrument. owner (str): Market or organization that owns the instrument.
ExpirationDate (str): Expiration date of the futures contract (YYYY-MM-DD format). ExpirationDate (str): Expiration date of the futures contract (YYYY-MM-DD format).
DaysToExpiration (int): Number of days remaining until expiration. DaysToExpiration (int): Number of days remaining until expiration.
buyCommission (float): Commission rate applied when buying (as percentage or fixed). buyCommission (float): Commission rate applied when buying (fraction, e.g. 0.0015 = 0.15%).
sellCommission (float): Commission rate applied when selling (as percentage or fixed). sellCommission (float): Commission rate applied when selling (fraction, e.g. 0.0015 = 0.15%).
canBuy (bool): Indicates if the instrument can currently be bought. canBuy (bool): Indicates if the instrument can currently be bought.
canSell (bool): Indicates if the instrument can currently be sold. canSell (bool): Indicates if the instrument can currently be sold.
csize (int): Contract size of the futures instrument (lot size multiplier). csize (int): Contract size of the futures instrument (multiplier applied to price to get contract value).
minValidBuyVolume (int): Minimum allowed buy order volume. minValidBuyVolume (int): Minimum allowed volume for a single buy order.
maxValidBuyVolume (int): Maximum allowed buy order volume. maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
minValidSellVolume (int): Minimum allowed sell order volume. minValidSellVolume (int): Minimum allowed volume for a single sell order.
maxValidSellVolume (int): Maximum allowed sell order volume. maxValidSellVolume (int): Maximum allowed volume for a single sell order.
minDealablePrice (float): Minimum price per trade (floor price). minDealablePrice (float): Minimum price at which a trade can be executed (floor price).
minDealableCount (int): Minimum quantity per trade (minimum lot size). minDealableCount (int): Minimum quantity that can be traded in a single deal.
ExerciseFeePhysical (float): Exercise fee for physical settlement. ExerciseFeePhysical (float): Exercise fee for physical settlement.
ExerciseFeeCash (float): Exercise fee for cash settlement. ExerciseFeeCash (float): Exercise fee for cash settlement.
ExerciseSellTax (float): Tax applied on exercise sell (as percentage). ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
dataClass (str): Internal classification or source of the instrument data. dataClass (str): Internal classification or source of the instrument data.
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of the underlying asset. UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
(for IME instruments) of the underlying asset.
UnderlyingAssets_title (str): Title/name of the underlying asset. UnderlyingAssets_title (str): Title/name of the underlying asset.
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of the underlying asset. UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
contractName (for IME instruments) of the underlying asset.
Example: Example:
>>> futures: IMEFuturesDict = { >>> futures: IMEFuturesDict = {
@@ -312,38 +340,44 @@ class IMEOption(TypedDict):
""" """
Static metadata structure for IME Option contracts. Static metadata structure for IME Option contracts.
Note:
Margins, commissions and taxes are expressed as fractions, not percentages
(e.g. ``0.05`` means 5%). Multiply by 100 to display a percentage.
Attributes: Attributes:
optionType (str): Type of the option - "Call" or "Put". optionType (str): Type of the option - "Call" or "Put".
contractId (str): Unique identifier of the option contract. contractId (str): Unique identifier of the option contract.
title (str): Full display name of the option contract. title (str): Full display name of the option contract.
contractName (str): Short name or ticker symbol. contractName (str): Short name / ticker of the option.
initialMargin (float): Initial margin required to open a position. initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.05 = 5%).
requiredMargin (float): Total required margin for the position. requiredMargin (float): Total required margin for the position (fraction).
maintenanceMargin (float): Minimum maintenance margin required. maintenanceMargin (float): Minimum maintenance margin required (fraction).
minPriceChangeRate (float): Minimum allowed price change rate (tick size). minPriceChangeRate (float): Minimum allowed price change rate (tick size).
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit). maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
strikePrice (float): Strike (exercise) price of the option. strikePrice (float): Strike (exercise) price of the option.
owner (str): Market or organization that owns the option. owner (str): Market or organization that owns the option.
ExpirationDate (str): Expiration date (YYYY-MM-DD). ExpirationDate (str): Expiration date (YYYY-MM-DD).
DaysToExpiration (int): Number of days remaining until expiration. DaysToExpiration (int): Number of days remaining until expiration.
buyCommission (float): Commission rate when buying. buyCommission (float): Commission rate when buying (fraction, e.g. 0.002 = 0.2%).
sellCommission (float): Commission rate when selling. sellCommission (float): Commission rate when selling (fraction, e.g. 0.002 = 0.2%).
canBuy (bool): Whether the option can currently be bought. canBuy (bool): Whether the option can currently be bought.
canSell (bool): Whether the option can currently be sold. canSell (bool): Whether the option can currently be sold.
csize (int): Contract size of the option. csize (int): Contract size of the option (number of underlying units per contract).
minValidBuyVolume (int): Minimum allowed buy order volume. minValidBuyVolume (int): Minimum allowed volume for a single buy order.
maxValidBuyVolume (int): Maximum allowed buy order volume. maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
minValidSellVolume (int): Minimum allowed sell order volume. minValidSellVolume (int): Minimum allowed volume for a single sell order.
maxValidSellVolume (int): Maximum allowed sell order volume. maxValidSellVolume (int): Maximum allowed volume for a single sell order.
minDealablePrice (float): Minimum price per trade. minDealablePrice (float): Minimum price at which a trade can be executed.
minDealableCount (int): Minimum quantity per trade. minDealableCount (int): Minimum quantity that can be traded in a single deal.
ExerciseFeePhysical (float): Exercise fee for physical settlement. ExerciseFeePhysical (float): Exercise fee for physical settlement.
ExerciseFeeCash (float): Exercise fee for cash settlement. ExerciseFeeCash (float): Exercise fee for cash settlement.
ExerciseSellTax (float): Tax applied on exercise sell. ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
dataClass (str): Internal classification of the instrument data. dataClass (str): Internal classification of the instrument data.
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of underlying asset. UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
(for IME instruments) of the underlying asset.
UnderlyingAssets_title (str): Title of the underlying asset. UnderlyingAssets_title (str): Title of the underlying asset.
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of underlying asset. UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
contractName (for IME instruments) of the underlying asset.
Example: Example:
>>> option: IMEOptionDict = { >>> option: IMEOptionDict = {
@@ -425,9 +459,15 @@ class Contracts(TypedDict):
This TypedDict defines the response format returned by instrument search endpoints. This TypedDict defines the response format returned by instrument search endpoints.
Contains a list of matching instruments along with status metadata. Contains a list of matching instruments along with status metadata.
The type of each item can be told apart by its fields: options have ``optionType``
and ``strikePrice``, futures have ``initialMargin`` but no ``optionType``, and
deposit certificates have ``StorageCost``.
Attributes: Attributes:
Data (list[IMEDepositCertificateDict | IMEFuturesDict | IMEOptionDict | None]): Data (list[IMEDepositCertificateDict | IMEFuturesDict | IMEOptionDict | None]):
List of matching instruments. Each item can be a Deposit Certificate, Futures, Option, or None if not found. List of matching instruments, in the same order as the requested
identifiers. Each item can be a Deposit Certificate, Futures, Option, or
None if no instrument was found for the corresponding identifier.
Status (StatusDict): Status metadata including execution state, timestamp, version, and status code. Status (StatusDict): Status metadata including execution state, timestamp, version, and status code.
Example: Example:
@@ -485,11 +525,16 @@ class BestLimitItem(TypedDict):
with their respective quantities and prices. It is used within the nested with their respective quantities and prices. It is used within the nested
structure of BestLimit response. structure of BestLimit response.
Note:
A level that has no orders on one side is expected to carry ``0`` for that
side's price and quantity. Check that a price is greater than zero before
using it in calculations (e.g. spread).
Attributes: Attributes:
buy_quantity (int): Total buy quantity available at this price level. buy_quantity (int): Total buy quantity available at this price level.
buy_price (int): Buy price (bid) at this level. buy_price (int): Buy price (bid) at this level, in IRR.
sell_quantity (int): Total sell quantity available at this price level. sell_quantity (int): Total sell quantity available at this price level.
sell_price (int): Sell price (ask) at this level. sell_price (int): Sell price (ask) at this level, in IRR.
Example: Example:
>>> level: BestLimitItem = { >>> level: BestLimitItem = {
@@ -516,8 +561,12 @@ class BestLimitResponse(TypedDict):
""" """
Response structure for best limit order book endpoints. Response structure for best limit order book endpoints.
The order book has up to 3 levels per contract: ``"1"`` is the best level
(highest bid / lowest ask), ``"2"`` the next, and ``"3"`` the third.
Attributes: Attributes:
Data (BestLimit): Nested dictionary mapping contract IDs/names to limit levels. Data (Dict[str, Dict[Literal['1','2','3'], BestLimitItem]]):
Dictionary mapping each contract ID/name to its order book levels.
Status (Status): Status metadata of the response. Status (Status): Status metadata of the response.
Example: Example:
@@ -559,13 +608,19 @@ class Aggregate(TypedDict):
This TypedDict contains comprehensive trading data including OHLC prices, This TypedDict contains comprehensive trading data including OHLC prices,
volume, value, trade count, and timestamps. volume, value, trade count, and timestamps.
Note:
Prices here are typed as ``float`` while prices in ``BestLimitItem`` are
``int``. If a contract has had no trades yet in the session, price/volume
fields may be ``0`` (and ``previous_close`` still holds the last session's
close).
Attributes: Attributes:
date (str): Trading date in YYYY-MM-DD format. date (str): Trading date in YYYY-MM-DD format.
time (str): Time of last trade update in HH:MM:SS format. time (str): Time of last trade update in HH:MM:SS format.
trade_count (int): Number of trades executed. trade_count (int): Number of trades executed.
total_volume (int): Total volume traded. total_volume (int): Total volume traded.
total_value (int): Total value of trades in IRR. total_value (int): Total value of trades in IRR.
closing_price (float): Closing price of the contract. closing_price (float): Closing price of the contract (final settlement-style price of the session).
last_price (float): Last traded price. last_price (float): Last traded price.
low_price (float): Lowest traded price during the session. low_price (float): Lowest traded price during the session.
high_price (float): Highest traded price during the session. high_price (float): Highest traded price during the session.
@@ -657,6 +712,7 @@ class AllowedPriceRange(TypedDict):
This TypedDict defines the minimum and maximum allowed prices for a contract This TypedDict defines the minimum and maximum allowed prices for a contract
on a given trading day, typically based on a percentage of the previous day's closing price. on a given trading day, typically based on a percentage of the previous day's closing price.
Orders outside this range are rejected by the exchange.
Attributes: Attributes:
minAllowedPrice (float): Minimum allowed price for the contract (lower price limit). minAllowedPrice (float): Minimum allowed price for the contract (lower price limit).
@@ -724,7 +780,8 @@ class ContractInfo(TypedDict):
Attributes: Attributes:
open_interest (int): Open interest for the contract (number of open positions). open_interest (int): Open interest for the contract (number of open positions).
open_interest_changes (int): Change in open interest compared to the previous period. open_interest_changes (int): Change in open interest compared to the previous period
(positive = increase, negative = decrease).
Example: Example:
>>> info: ContractInfo = { >>> info: ContractInfo = {
@@ -780,26 +837,27 @@ class OverviewIMEDepositCertificate(TypedDict):
""" """
Live market overview for IME Deposit Certificate instruments. Live market overview for IME Deposit Certificate instruments.
This combines static metadata with real-time market data including best limits, This combines static metadata (same fields as ``IMEDepositCertificate``) with
aggregate statistics, price ranges, and contract information. real-time market data including best limits, aggregate statistics, price ranges,
and contract information.
Attributes: Attributes:
contractId (str): Unique contractId code identifying the certificate. contractId (str): Unique identifier of the certificate.
title (str): Full display name of the deposit certificate. title (str): Full display name of the deposit certificate.
contractName (str): Short name or ticker contract of the certificate. contractName (str): Short name / ticker of the certificate.
minPriceChangeRate (float): Minimum allowed price change rate. minPriceChangeRate (float): Minimum allowed price change rate (tick size).
maxPriceChangeRate (float): Maximum allowed price change rate. maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
owner (str): Market or organization that owns the certificate. owner (str): Market or organization that owns the certificate.
buyCommission (float): Commission rate applied when buying. buyCommission (float): Commission rate applied when buying (fraction, e.g. 0.0025 = 0.25%).
sellCommission (float): Commission rate applied when selling. sellCommission (float): Commission rate applied when selling (fraction, e.g. 0.0025 = 0.25%).
canBuy (bool): Indicates if the certificate can currently be bought. canBuy (bool): Indicates if the certificate can currently be bought.
canSell (bool): Indicates if the certificate can currently be sold. canSell (bool): Indicates if the certificate can currently be sold.
minValidBuyVolume (int): Minimum allowed buy order volume. minValidBuyVolume (int): Minimum allowed volume for a single buy order.
maxValidBuyVolume (int): Maximum allowed buy order volume. maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
minValidSellVolume (int): Minimum allowed sell order volume. minValidSellVolume (int): Minimum allowed volume for a single sell order.
maxValidSellVolume (int): Maximum allowed sell order volume. maxValidSellVolume (int): Maximum allowed volume for a single sell order.
minDealablePrice (float): Minimum price per trade. minDealablePrice (float): Minimum price at which a trade can be executed (floor price).
minDealableCount (int): Minimum quantity per trade. minDealableCount (int): Minimum quantity that can be traded in a single deal.
StorageCost (float): Storage cost associated with the certificate. StorageCost (float): Storage cost associated with the certificate.
dataClass (str): Internal classification or source of the instrument data. dataClass (str): Internal classification or source of the instrument data.
BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3"). BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3").
@@ -871,38 +929,41 @@ class OverviewIMEFutures(TypedDict):
""" """
Live market overview for IME Futures contracts. Live market overview for IME Futures contracts.
This combines static futures metadata with real-time market data including best limits, This combines static futures metadata (same fields as ``IMEFutures``) with
aggregate statistics, price ranges, and contract information. real-time market data including best limits, aggregate statistics, price ranges,
and contract information.
Attributes: Attributes:
contractId (str): Unique contractId code identifying the futures contract. contractId (str): Unique identifier of the futures contract.
title (str): Full display name of the futures contract. title (str): Full display name of the futures contract.
contractName (str): Short name or ticker contract. contractName (str): Short name / ticker of the futures instrument.
initialMargin (float): Initial margin required to open a position. initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.10 = 10%).
maintenanceMargin (float): Minimum maintenance margin required. maintenanceMargin (float): Minimum maintenance margin required (fraction).
minPriceChangeRate (float): Minimum allowed price change rate. minPriceChangeRate (float): Minimum allowed price change rate (tick size).
maxPriceChangeRate (float): Maximum allowed price change rate. maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
owner (str): Market or organization that owns the instrument. owner (str): Market or organization that owns the instrument.
ExpirationDate (str): Expiration date of the futures contract. ExpirationDate (str): Expiration date of the futures contract (YYYY-MM-DD).
DaysToExpiration (int): Number of days remaining until expiration. DaysToExpiration (int): Number of days remaining until expiration.
buyCommission (float): Commission rate applied when buying. buyCommission (float): Commission rate applied when buying (fraction).
sellCommission (float): Commission rate applied when selling. sellCommission (float): Commission rate applied when selling (fraction).
canBuy (bool): Indicates if the instrument can currently be bought. canBuy (bool): Indicates if the instrument can currently be bought.
canSell (bool): Indicates if the instrument can currently be sold. canSell (bool): Indicates if the instrument can currently be sold.
csize (int): Contract size of the futures instrument. csize (int): Contract size of the futures instrument.
minValidBuyVolume (int): Minimum allowed buy order volume. minValidBuyVolume (int): Minimum allowed volume for a single buy order.
maxValidBuyVolume (int): Maximum allowed buy order volume. maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
minValidSellVolume (int): Minimum allowed sell order volume. minValidSellVolume (int): Minimum allowed volume for a single sell order.
maxValidSellVolume (int): Maximum allowed sell order volume. maxValidSellVolume (int): Maximum allowed volume for a single sell order.
minDealablePrice (float): Minimum price per trade. minDealablePrice (float): Minimum price at which a trade can be executed.
minDealableCount (int): Minimum quantity per trade. minDealableCount (int): Minimum quantity that can be traded in a single deal.
ExerciseFeePhysical (float): Exercise fee for physical settlement. ExerciseFeePhysical (float): Exercise fee for physical settlement.
ExerciseFeeCash (float): Exercise fee for cash settlement. ExerciseFeeCash (float): Exercise fee for cash settlement.
ExerciseSellTax (float): Tax applied on exercise sell. ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
dataClass (str): Internal classification or source of the instrument data. dataClass (str): Internal classification or source of the instrument data.
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of underlying asset. UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
(for IME instruments) of the underlying asset.
UnderlyingAssets_title (str): Title of the underlying asset. UnderlyingAssets_title (str): Title of the underlying asset.
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of underlying asset. UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
contractName (for IME instruments) of the underlying asset.
BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3"). BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3").
Aggregate (Aggregate): Aggregate trading statistics. Aggregate (Aggregate): Aggregate trading statistics.
AllowedPriceRange (AllowedPriceRange): Daily price limits. AllowedPriceRange (AllowedPriceRange): Daily price limits.
@@ -949,41 +1010,44 @@ class OverviewIMEOption(TypedDict):
""" """
Live market overview for IME Option contracts. Live market overview for IME Option contracts.
This combines static option metadata with real-time market data including best limits, This combines static option metadata (same fields as ``IMEOption``) with
aggregate statistics, price ranges, and contract information. real-time market data including best limits, aggregate statistics, price ranges,
and contract information.
Attributes: Attributes:
optionType (str): Type of the option - "Call" or "Put". optionType (str): Type of the option - "Call" or "Put".
contractId (str): Unique contractId code identifying the option. contractId (str): Unique identifier of the option.
title (str): Full display name of the option contract. title (str): Full display name of the option contract.
contractName (str): Short name or ticker contract. contractName (str): Short name / ticker of the option.
initialMargin (float): Initial margin required to open a position. initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.05 = 5%).
requiredMargin (float): Total required margin for the position. requiredMargin (float): Total required margin for the position (fraction).
maintenanceMargin (float): Minimum maintenance margin required. maintenanceMargin (float): Minimum maintenance margin required (fraction).
minPriceChangeRate (float): Minimum allowed price change rate. minPriceChangeRate (float): Minimum allowed price change rate (tick size).
maxPriceChangeRate (float): Maximum allowed price change rate. maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
strikePrice (float): Strike price of the option. strikePrice (float): Strike price of the option.
owner (str): Market or organization that owns the option. owner (str): Market or organization that owns the option.
ExpirationDate (str): Expiration date of the option contract. ExpirationDate (str): Expiration date of the option contract (YYYY-MM-DD).
DaysToExpiration (int): Number of days remaining until expiration. DaysToExpiration (int): Number of days remaining until expiration.
buyCommission (float): Commission rate applied when buying. buyCommission (float): Commission rate applied when buying (fraction).
sellCommission (float): Commission rate applied when selling. sellCommission (float): Commission rate applied when selling (fraction).
canBuy (bool): Indicates if the option can currently be bought. canBuy (bool): Indicates if the option can currently be bought.
canSell (bool): Indicates if the option can currently be sold. canSell (bool): Indicates if the option can currently be sold.
csize (int): Contract size of the option. csize (int): Contract size of the option.
minValidBuyVolume (int): Minimum allowed buy order volume. minValidBuyVolume (int): Minimum allowed volume for a single buy order.
maxValidBuyVolume (int): Maximum allowed buy order volume. maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
minValidSellVolume (int): Minimum allowed sell order volume. minValidSellVolume (int): Minimum allowed volume for a single sell order.
maxValidSellVolume (int): Maximum allowed sell order volume. maxValidSellVolume (int): Maximum allowed volume for a single sell order.
minDealablePrice (float): Minimum price per trade. minDealablePrice (float): Minimum price at which a trade can be executed.
minDealableCount (int): Minimum quantity per trade. minDealableCount (int): Minimum quantity that can be traded in a single deal.
ExerciseFeePhysical (float): Exercise fee for physical settlement. ExerciseFeePhysical (float): Exercise fee for physical settlement.
ExerciseFeeCash (float): Exercise fee for cash settlement. ExerciseFeeCash (float): Exercise fee for cash settlement.
ExerciseSellTax (float): Tax applied on exercise sell. ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
dataClass (str): Internal classification of the instrument data. dataClass (str): Internal classification of the instrument data.
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of underlying asset. UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
(for IME instruments) of the underlying asset.
UnderlyingAssets_title (str): Title of the underlying asset. UnderlyingAssets_title (str): Title of the underlying asset.
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of underlying asset. UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
contractName (for IME instruments) of the underlying asset.
BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3"). BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3").
Aggregate (Aggregate): Aggregate trading statistics. Aggregate (Aggregate): Aggregate trading statistics.
AllowedPriceRange (AllowedPriceRange): Daily price limits. AllowedPriceRange (AllowedPriceRange): Daily price limits.
@@ -1036,9 +1100,14 @@ class OverviewResponse(TypedDict):
This endpoint returns a dictionary mapping contract identifiers to their complete This endpoint returns a dictionary mapping contract identifiers to their complete
overview data (static + live) or None if the contract is not found. overview data (static + live) or None if the contract is not found.
The type of each overview can be told apart by its fields: options have
``optionType`` and ``strikePrice``, futures have ``initialMargin`` but no
``optionType``, and deposit certificates have ``StorageCost``.
Attributes: Attributes:
Data (dict[str, OverviewIMEDepositCertificate | OverviewIMEFutures | OverviewIMEOption | None]): Data (dict[str, OverviewIMEDepositCertificate | OverviewIMEFutures | OverviewIMEOption | None]):
Dictionary mapping contract IDs or names to overview objects or None. Dictionary mapping each requested contract ID or name to its overview
object, or to None if no contract was found for that key.
Status (Status): Status metadata of the response. Status (Status): Status metadata of the response.
Example: Example:
@@ -1113,17 +1182,19 @@ class OverviewResponse(TypedDict):
class Websocket_data(TypedDict): class Websocket_data(TypedDict):
""" """
Live market data payload for IME WebSocket streams. Live market data payload for IME WebSocket streams.
This TypedDict represents the complete real-time market data for a single contract, This TypedDict represents the complete real-time market data for a single contract,
including order book, trading statistics, price limits, and contract information. including order book, trading statistics, price limits, and contract information.
It is the value of the ``data`` field in the WebSocket messages below, and each
new message carries a fresh full snapshot of these four sections.
Attributes: Attributes:
BestLimit (Dict[Literal['1','2','3'], BestLimitItem]): BestLimit (Dict[Literal['1','2','3'], BestLimitItem]):
Best limit order book with 3 levels. Keys "1" (best), "2", "3" (worst). Best limit order book with 3 levels. Keys "1" (best), "2", "3" (worst).
Each level contains buy/sell quantities and prices. Each level contains buy/sell quantities and prices. Empty levels carry
zero values.
Aggregate (Aggregate): Aggregate (Aggregate):
Aggregate trading statistics including OHLC, volume, trade count, Aggregate trading statistics including OHLC, volume, trade count,
@@ -1202,6 +1273,11 @@ class WebsocketBase_contractId(TypedDict):
This TypedDict defines the standard format of all real-time messages received This TypedDict defines the standard format of all real-time messages received
when subscribing to the `/contract/id` WebSocket endpoint. when subscribing to the `/contract/id` WebSocket endpoint.
Note:
This is the full message type and it replaces the earlier, smaller
``WebsocketBase_contractId`` defined at the top of this file (the one without
``data``), since the last definition wins.
Attributes: Attributes:
channel (Literal["IME Stream"]): channel (Literal["IME Stream"]):
Fixed channel name for IME live market data streams. Fixed channel name for IME live market data streams.
@@ -1211,7 +1287,10 @@ class WebsocketBase_contractId(TypedDict):
timestamp (str): timestamp (str):
ISO-formatted timestamp when the message was generated ISO-formatted timestamp when the message was generated
(e.g., "2025-01-15T14:30:00.123456"). (e.g., "2025-01-15T14:30:00.123456"). This is a string, unlike the
numeric ``ServerTimeStamp`` in ``Status``. It may or may not carry a
timezone suffix (such as "Z"), so don't assume it is UTC unless you
have confirmed it.
data (Websocket_data): data (Websocket_data):
Live market data payload containing BestLimit, Aggregate, Live market data payload containing BestLimit, Aggregate,
@@ -1239,7 +1318,7 @@ class WebsocketBase_contractId(TypedDict):
>>> print(f"Channel: {message['channel']}") >>> print(f"Channel: {message['channel']}")
Channel: IME Stream Channel: IME Stream
>>> print(f"Contract ID: {message['contractId']}") >>> print(f"Contract ID: {message['contractId']}")
Contract ID: IME0012345 Contract ID: 012345
>>> print(f"Timestamp: {message['timestamp']}") >>> print(f"Timestamp: {message['timestamp']}")
Timestamp: 2025-01-15T14:30:00.123456 Timestamp: 2025-01-15T14:30:00.123456
>>> print(f"Last price: {message['data']['Aggregate']['last_price']}") >>> print(f"Last price: {message['data']['Aggregate']['last_price']}")
@@ -1258,6 +1337,11 @@ class WebsocketBase_contractName(TypedDict):
This TypedDict defines the standard format of all real-time messages received This TypedDict defines the standard format of all real-time messages received
when subscribing to the `/contract/name` WebSocket endpoint. when subscribing to the `/contract/name` WebSocket endpoint.
Note:
This is the full message type and it replaces the earlier, smaller
``WebsocketBase_contractName`` defined at the top of this file (the one
without ``data``), since the last definition wins.
Attributes: Attributes:
channel (Literal["IME Stream"]): channel (Literal["IME Stream"]):
Fixed channel name for IME live market data streams. Fixed channel name for IME live market data streams.
@@ -1267,7 +1351,10 @@ class WebsocketBase_contractName(TypedDict):
timestamp (str): timestamp (str):
ISO-formatted timestamp when the message was generated ISO-formatted timestamp when the message was generated
(e.g., "2025-01-15T14:30:00.123456"). (e.g., "2025-01-15T14:30:00.123456"). This is a string, unlike the
numeric ``ServerTimeStamp`` in ``Status``. It may or may not carry a
timezone suffix (such as "Z"), so don't assume it is UTC unless you
have confirmed it.
data (Websocket_data): data (Websocket_data):
Live market data payload containing BestLimit, Aggregate, Live market data payload containing BestLimit, Aggregate,
+125 -57
View File
@@ -54,7 +54,7 @@ from .__io_types import (
class DataEngine_TseIfb_AsyncClient: class DataEngine_TseIfb_AsyncClient:
""" """
Asynchronous client for interacting with the TSE-IFB (Iranian Securities Exchange) Data Engine API. Asynchronous client for the TSE-IFB Data Engine API (Tehran Stock Exchange and Iran Fara Bourse).
This class provides high-level asynchronous methods to retrieve live and historical market data, This class provides high-level asynchronous methods to retrieve live and historical market data,
order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other
@@ -71,14 +71,14 @@ class DataEngine_TseIfb_AsyncClient:
__AuthAsyncClient (AuthAsyncClient): An instance of `AuthAsyncClient` used to perform __AuthAsyncClient (AuthAsyncClient): An instance of `AuthAsyncClient` used to perform
authorized HTTP requests and WebSocket connections. authorized HTTP requests and WebSocket connections.
Examples: Example:
>>> auth_client = await AuthAsyncClient.login( >>> auth_client = await AuthAsyncClient.login(
... UserName_or_Email="user@example.com", ... UserName_or_Email="user@example.com",
... Password="secure_password" ... Password="secure_password"
... ) ... )
>>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth_client) >>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth_client)
>>> instruments = await data_client.instruments_static_info_by_name(["فملی", "خودرو"]) >>> instruments = await data_client.instruments_static_info_by_name(["فملی", "خودرو"])
>>> print(instruments["Data"]["فملی"]["symbolName"]) >>> print(instruments["Data"][0]["symbolName"])
>>> async for update in data_client.websocket_by_name( >>> async for update in data_client.websocket_by_name(
... channels=["best-limit", "order-book"], ... channels=["best-limit", "order-book"],
... symbol_names=["فملی"] ... symbol_names=["فملی"]
@@ -87,8 +87,14 @@ class DataEngine_TseIfb_AsyncClient:
Notes: Notes:
- All network requests are asynchronous and should be awaited. - All network requests are asynchronous and should be awaited.
- Most methods exist in two variants: ``*_by_name`` (symbol name, e.g. "فملی") and
``*_by_isin`` (ISIN code).
- REST methods raise ``ValueError`` (carrying the server's ``detail`` message) when the
API returns an error.
- WebSocket methods yield streaming updates and should be used with `async for`. - WebSocket methods yield streaming updates and should be used with `async for`.
- Exceptions (ValueError) are raised when the API returns an error or request fails. Once the connection is established, errors do not raise: the stream simply ends
(see ``websocket_by_name``).
- Prices are in IRR; commission rates are fractions (``0.001`` means 0.1%).
""" """
def __init__( def __init__(
@@ -134,7 +140,8 @@ class DataEngine_TseIfb_AsyncClient:
Returns: Returns:
Instruments: Instruments:
A dictionary containing: A dictionary containing:
- Data: A list of matched instruments. Each item is one of: - Data: A list of matched instruments (the type of each item can be
recognized from its fields, see ``Instruments``). Each item is one of:
* SecuritiesAndFunds * SecuritiesAndFunds
* TreasuryBonds * TreasuryBonds
* StockOptions * StockOptions
@@ -190,8 +197,9 @@ class DataEngine_TseIfb_AsyncClient:
Returns: Returns:
Instruments: Instruments:
A dictionary containing: A dictionary containing:
- Data: A mapping of symbol_name → Instrument info. - Data: A list of instruments matching the provided symbol names.
Instrument info is one of: Identify each item by its ``symbolName`` field (do not rely on the order).
Each item is one of:
* SecuritiesAndFunds * SecuritiesAndFunds
* TreasuryBonds * TreasuryBonds
* StockOptions * StockOptions
@@ -208,7 +216,7 @@ class DataEngine_TseIfb_AsyncClient:
>>> result = await client.instruments_static_info_by_name( >>> result = await client.instruments_static_info_by_name(
... ["فملی", "خودرو"] ... ["فملی", "خودرو"]
... ) ... )
>>> print(result["Data"]["فملی"]["symbolIsin"]) >>> print(result["Data"][0]["symbolIsin"])
""" """
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name', url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name',
@@ -239,7 +247,8 @@ class DataEngine_TseIfb_AsyncClient:
Instruments: Instruments:
A dictionary containing: A dictionary containing:
- Data: A list of instruments matching the provided ISINs. - Data: A list of instruments matching the provided ISINs.
Each item can be SecuritiesAndFunds, TreasuryBonds, Identify each item by its ``symbolIsin`` field (do not rely on
the order). Each item can be SecuritiesAndFunds, TreasuryBonds,
StockOptions, StockFutures, or None if not found. StockOptions, StockFutures, or None if not found.
- Status: Status information returned by the API. - Status: Status information returned by the API.
@@ -399,7 +408,8 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names. Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names.
This endpoint returns the top-of-the-book order data, including: This endpoint returns the best limit levels of the order book (up to 6 levels per
instrument), each including:
- Best bid price, quantity, and order count - Best bid price, quantity, and order count
- Best ask price, quantity, and order count - Best ask price, quantity, and order count
@@ -412,8 +422,9 @@ class DataEngine_TseIfb_AsyncClient:
BestLimitResponse: BestLimitResponse:
An object containing: An object containing:
- **Data**: - **Data**:
Mapping of symbol_name → BestLimitItem Mapping of symbol_name → best limit levels: a dictionary with up to 6
Each BestLimitItem includes: levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count * buy_order_count
* buy_quantity * buy_quantity
* buy_price * buy_price
@@ -429,7 +440,7 @@ class DataEngine_TseIfb_AsyncClient:
Example: Example:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client) >>> client = DataEngine_TseIfb_AsyncClient(auth_client)
>>> bl = await client.live_best_limit_by_name(["فملی"]) >>> bl = await client.live_best_limit_by_name(["فملی"])
>>> print(bl["Data"]["فملی"]["buy_price"]) >>> print(bl["Data"]["فملی"]["1"]["buy_price"])
""" """
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
@@ -453,7 +464,7 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes. Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes.
This endpoint returns the top-of-book order metrics for each ISIN instrument. This endpoint returns the best limit levels (up to 6 per instrument) for each ISIN instrument.
Args: Args:
symbol_isins (List[str]): symbol_isins (List[str]):
@@ -463,8 +474,9 @@ class DataEngine_TseIfb_AsyncClient:
BestLimitResponse: BestLimitResponse:
An object containing: An object containing:
- **Data**: - **Data**:
Mapping of symbol_isin → BestLimitItem Mapping of symbol_isin → best limit levels: a dictionary with up to 6
Each BestLimitItem includes: levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count * buy_order_count
* buy_quantity * buy_quantity
* buy_price * buy_price
@@ -480,7 +492,7 @@ class DataEngine_TseIfb_AsyncClient:
Example: Example:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client) >>> client = DataEngine_TseIfb_AsyncClient(auth_client)
>>> bl = await client.live_best_limit_by_isin(["IRO1XYZ12345"]) >>> bl = await client.live_best_limit_by_isin(["IRO1XYZ12345"])
>>> print(bl["Data"]["IRO1XYZ12345"]["sell_quantity"]) >>> print(bl["Data"]["IRO1XYZ12345"]["1"]["sell_quantity"])
""" """
data = await self.__AuthAsyncClient.httpx_Client.get( data = await self.__AuthAsyncClient.httpx_Client.get(
@@ -924,7 +936,7 @@ class DataEngine_TseIfb_AsyncClient:
"nav": float, "nav": float,
"units": int, "units": int,
"marketCap": int, "marketCap": int,
"as_of": datetime "as_of": datetime # typically an ISO-formatted string in the decoded JSON
}, },
... ...
}, },
@@ -972,7 +984,7 @@ class DataEngine_TseIfb_AsyncClient:
"nav": float, "nav": float,
"units": int, "units": int,
"marketCap": int, "marketCap": int,
"as_of": datetime "as_of": datetime # typically an ISO-formatted string in the decoded JSON
}, },
... ...
}, },
@@ -1115,10 +1127,14 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by symbol name. Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by symbol name.
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
Args: Args:
symbol_name (str): Trading symbol name (e.g., "فملی"). symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp for the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False). AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
Resolution (Literal): Data resolution. Options: Resolution (Literal): Data resolution. Options:
- "1m", "5m", "15m", "30m", "1h" for intraday - "1m", "5m", "15m", "30m", "1h" for intraday
@@ -1193,10 +1209,14 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by ISIN code. Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by ISIN code.
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
Args: Args:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001"). symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp for the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False). AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
Resolution (Literal): Data resolution. Options: Resolution (Literal): Data resolution. Options:
- "1m", "5m", "15m", "30m", "1h" for intraday - "1m", "5m", "15m", "30m", "1h" for intraday
@@ -1267,10 +1287,12 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name. Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name.
All parameters are keyword-only.
Args: Args:
symbol_name (str): Trading symbol name (e.g., "فملی"). symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp marking the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns: Returns:
CorporateActionResponse: TypedDict with structure: CorporateActionResponse: TypedDict with structure:
@@ -1278,7 +1300,8 @@ class DataEngine_TseIfb_AsyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]], "Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"Status": Status "Status": Status
} }
Each item in Data includes fields such as: Each item in Data includes fields such as (use ``corporateAction`` to tell the two
kinds of items apart):
- Date_timestamp: int - Date_timestamp: int
- corporateAction: str - corporateAction: str
- symbolName: str - symbolName: str
@@ -1332,10 +1355,12 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code. Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code.
All parameters are keyword-only.
Args: Args:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001"). symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp marking the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns: Returns:
CorporateActionResponse: TypedDict with structure: CorporateActionResponse: TypedDict with structure:
@@ -1343,7 +1368,8 @@ class DataEngine_TseIfb_AsyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]], "Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"Status": Status "Status": Status
} }
Each item in Data includes fields such as: Each item in Data includes fields such as (use ``corporateAction`` to tell the two
kinds of items apart):
- Date_timestamp: int - Date_timestamp: int
- corporateAction: str - corporateAction: str
- symbolName: str - symbolName: str
@@ -1419,6 +1445,16 @@ class DataEngine_TseIfb_AsyncClient:
best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs individual trades, best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs individual trades,
contract information, and fund information. contract information, and fund information.
All requested channels and instruments share a single connection. Every message belongs to
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolName"]`` to tell
them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (for example from another
task) to stop it. The check happens each time a message arrives and after a receive
timeout (2 seconds without messages), so the stream ends within about 2 seconds at most.
The connection is closed automatically when the generator finishes.
Args: Args:
channels (List[str]): channels (List[str]):
List of channels to subscribe to. Possible values: List of channels to subscribe to. Possible values:
@@ -1432,13 +1468,15 @@ class DataEngine_TseIfb_AsyncClient:
symbol_names (List[str]): symbol_names (List[str]):
List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]). List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]).
event (Event | None, optional): event (Event | None, optional):
Optional asyncio.Event to control the WebSocket loop. Optional asyncio.Event used as a stop switch. It must be set for the stream to run:
If provided, the loop will continue while `event.is_set()` is True. the loop continues while `event.is_set()` is True.
Defaults to a new set Event. Defaults to a new, already-set Event (the stream then runs until the connection ends).
Returns: Yields:
AsyncGenerator: Union[BestLimit_WS_symbolName, OrderBook_WS_symbolName, Aggregate_WS_symbolName,
Yields TypedDict objects depending on the channel subscribed: institutional_vs_individual_WS_symbolName, ContractInfo_WS_symbolName, FundInfo_WS_symbolName,
OHLCV_WS_symbolName]:
One message per update, as a TypedDict that depends on the channel:
- **BestLimit_WS_symbolName** for 'best-limit' - **BestLimit_WS_symbolName** for 'best-limit'
- **OrderBook_WS_symbolName** for 'order-book' - **OrderBook_WS_symbolName** for 'order-book'
- **OHLCV_WS_symbolName** for 'ohlcv-last-1m' - **OHLCV_WS_symbolName** for 'ohlcv-last-1m'
@@ -1448,14 +1486,22 @@ class DataEngine_TseIfb_AsyncClient:
- **FundInfo_WS_symbolName** for 'fund-info' - **FundInfo_WS_symbolName** for 'fund-info'
Each yielded object contains: Each yielded object contains:
- `channel`: str — name of the channel - `channel`: Literal — name of the channel (one of the values above)
- `symbolName`: str — instrument symbol - `symbolName`: str — instrument symbol name
- `timestamp`: str — server timestamp - `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
- `data`: Dict[...] — channel-specific real-time data. numeric ``ServerTimeStamp`` in ``Status``)
- `data`: channel-specific real-time data.
Raises: Raises:
WebSocketException or ValueError: websockets.exceptions.WebSocketException or OSError:
If the WebSocket connection fails or an exception occurs while receiving data. Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
or ``OSError`` on a network failure).
Note:
Once the connection is established, errors do not raise: a closed connection, invalid JSON
or a network error closes the connection and the generator simply ends. If you need a
permanent stream, wrap the ``async for`` loop in a reconnect loop. A receive timeout is
not an error; the generator just keeps waiting.
Example: Example:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client) >>> client = DataEngine_TseIfb_AsyncClient(auth_client)
@@ -1463,7 +1509,8 @@ class DataEngine_TseIfb_AsyncClient:
... channels=["best-limit", "order-book"], ... channels=["best-limit", "order-book"],
... symbol_names=["فملی"] ... symbol_names=["فملی"]
... ): ... ):
... print(update["data"]) ... if update["channel"] == "best-limit":
... print(update["symbolName"], update["data"]["1"]["buy_price"])
""" """
if not isinstance(event,Event): if not isinstance(event,Event):
@@ -1524,9 +1571,19 @@ class DataEngine_TseIfb_AsyncClient:
""" """
Subscribe to **real-time WebSocket updates** for a list of instruments using their ISIN codes. Subscribe to **real-time WebSocket updates** for a list of instruments using their ISIN codes.
This function streams live updates for multiple market channels such as best-limit, order book, This function streams continuous updates for multiple market channels such as
last 1-minute OHLCV, aggregate data, institutional vs individual trades, contract information, best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs individual trades,
and fund information. contract information, and fund information.
All requested channels and instruments share a single connection. Every message belongs to
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolIsin"]`` to tell
them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (for example from another
task) to stop it. The check happens each time a message arrives and after a receive
timeout (2 seconds without messages), so the stream ends within about 2 seconds at most.
The connection is closed automatically when the generator finishes.
Args: Args:
channels (List[str]): channels (List[str]):
@@ -1541,13 +1598,15 @@ class DataEngine_TseIfb_AsyncClient:
symbol_isins (List[str]): symbol_isins (List[str]):
List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]). List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]).
event (Event | None, optional): event (Event | None, optional):
Optional asyncio.Event to control the WebSocket loop. Optional asyncio.Event used as a stop switch. It must be set for the stream to run:
If provided, the loop continues while `event.is_set()` is True. the loop continues while `event.is_set()` is True.
Defaults to a new set Event. Defaults to a new, already-set Event (the stream then runs until the connection ends).
Returns: Yields:
AsyncGenerator: Union[BestLimit_WS_symbolIsin, OrderBook_WS_symbolIsin, Aggregate_WS_symbolIsin,
Yields TypedDict objects depending on the channel subscribed: institutional_vs_individual_WS_symbolIsin, ContractInfo_WS_symbolIsin, FundInfo_WS_symbolIsin,
OHLCV_WS_symbolIsin]:
One message per update, as a TypedDict that depends on the channel:
- **BestLimit_WS_symbolIsin** for 'best-limit' - **BestLimit_WS_symbolIsin** for 'best-limit'
- **OrderBook_WS_symbolIsin** for 'order-book' - **OrderBook_WS_symbolIsin** for 'order-book'
- **OHLCV_WS_symbolIsin** for 'ohlcv-last-1m' - **OHLCV_WS_symbolIsin** for 'ohlcv-last-1m'
@@ -1557,14 +1616,22 @@ class DataEngine_TseIfb_AsyncClient:
- **FundInfo_WS_symbolIsin** for 'fund-info' - **FundInfo_WS_symbolIsin** for 'fund-info'
Each yielded object contains: Each yielded object contains:
- `channel`: str — channel name - `channel`: Literal — name of the channel (one of the values above)
- `symbolIsin`: str — instrument ISIN - `symbolIsin`: str — instrument ISIN
- `timestamp`: str — server timestamp - `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
- `data`: Dict[...] — channel-specific real-time data. numeric ``ServerTimeStamp`` in ``Status``)
- `data`: channel-specific real-time data.
Raises: Raises:
WebSocketException or ValueError: websockets.exceptions.WebSocketException or OSError:
If the WebSocket connection fails or an exception occurs during data reception. Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
or ``OSError`` on a network failure).
Note:
Once the connection is established, errors do not raise: a closed connection, invalid JSON
or a network error closes the connection and the generator simply ends. If you need a
permanent stream, wrap the ``async for`` loop in a reconnect loop. A receive timeout is
not an error; the generator just keeps waiting.
Example: Example:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client) >>> client = DataEngine_TseIfb_AsyncClient(auth_client)
@@ -1572,7 +1639,8 @@ class DataEngine_TseIfb_AsyncClient:
... channels=["best-limit", "order-book"], ... channels=["best-limit", "order-book"],
... symbol_isins=["IR1234567890"] ... symbol_isins=["IR1234567890"]
... ): ... ):
... print(update["data"]) ... if update["channel"] == "best-limit":
... print(update["symbolIsin"], update["data"]["1"]["buy_price"])
""" """
if not isinstance(event,Event): if not isinstance(event,Event):
+167 -64
View File
@@ -49,7 +49,7 @@ from .__io_types import (
class DataEngine_TseIfb_SyncClient: class DataEngine_TseIfb_SyncClient:
""" """
Synchronous client for interacting with the TSE-IFB (Iranian Securities Exchange) Data Engine API. Synchronous (blocking) client for the TSE-IFB Data Engine API (Tehran Stock Exchange and Iran Fara Bourse).
This class provides high-level synchronous methods to retrieve live and historical market data, This class provides high-level synchronous methods to retrieve live and historical market data,
order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other
@@ -66,14 +66,14 @@ class DataEngine_TseIfb_SyncClient:
__AuthSyncClient (AuthSyncClient): An instance of `AuthSyncClient` used to perform __AuthSyncClient (AuthSyncClient): An instance of `AuthSyncClient` used to perform
authorized synchronous HTTP requests and WebSocket connections. authorized synchronous HTTP requests and WebSocket connections.
Examples: Example:
>>> auth_client = AuthSyncClient.login( >>> auth_client = AuthSyncClient.login(
... UserName_or_Email="user@example.com", ... UserName_or_Email="user@example.com",
... Password="secure_password" ... Password="secure_password"
... ) ... )
>>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth_client) >>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth_client)
>>> instruments = data_client.instruments_static_info_by_name(["فملی", "خودرو"]) >>> instruments = data_client.instruments_static_info_by_name(["فملی", "خودرو"])
>>> print(instruments["Data"]["فملی"]["symbolName"]) >>> print(instruments["Data"][0]["symbolName"])
>>> for update in data_client.websocket_by_name( >>> for update in data_client.websocket_by_name(
... channels=["best-limit", "order-book"], ... channels=["best-limit", "order-book"],
... symbol_names=["فملی"] ... symbol_names=["فملی"]
@@ -81,9 +81,19 @@ class DataEngine_TseIfb_SyncClient:
... print(update) ... print(update)
Notes: Notes:
- This is the blocking twin of ``DataEngine_TseIfb_AsyncClient``: the endpoints, arguments and
return types are identical; only the calling style differs (plain calls instead of ``await``,
``threading.Event`` instead of ``asyncio.Event``, a normal generator instead of an async
generator).
- All network requests are synchronous and return after the server responds. - All network requests are synchronous and return after the server responds.
- WebSocket methods yield streaming updates and should be used with `for` loops. - Most methods exist in two variants: ``*_by_name`` (symbol name, e.g. "فملی") and
- Exceptions (ValueError) are raised when the API returns an error or request fails. ``*_by_isin`` (ISIN code).
- REST methods raise ``ValueError`` (carrying the server's ``detail`` message) when the
API returns an error.
- WebSocket methods ARE supported: they are blocking generators and should be used with `for`
loops (ideally in a dedicated thread). Once the connection is established, errors do not
raise: the stream simply ends (see ``websocket_by_name``).
- Prices are in IRR; commission rates are fractions (``0.001`` means 0.1%).
""" """
def __init__( def __init__(
@@ -118,6 +128,8 @@ class DataEngine_TseIfb_SyncClient:
""" """
Search for instruments in a specific market by name, title, or partial text (synchronous). Search for instruments in a specific market by name, title, or partial text (synchronous).
Both parameters are keyword-only.
Args: Args:
market (Literal["SecuritiesAndFunds", "TreasuryBonds", "StockOptions", "StockFutures"]): market (Literal["SecuritiesAndFunds", "TreasuryBonds", "StockOptions", "StockFutures"]):
Determines which market group to search in. Determines which market group to search in.
@@ -130,7 +142,8 @@ class DataEngine_TseIfb_SyncClient:
Returns: Returns:
Instruments: Instruments:
A dictionary containing: A dictionary containing:
- Data: A list of matched instruments. Each item is one of: - Data: A list of matched instruments (the type of each item can be
recognized from its fields, see ``Instruments``). Each item is one of:
* SecuritiesAndFunds * SecuritiesAndFunds
* TreasuryBonds * TreasuryBonds
* StockOptions * StockOptions
@@ -187,8 +200,9 @@ class DataEngine_TseIfb_SyncClient:
Returns: Returns:
Instruments: Instruments:
A dictionary containing: A dictionary containing:
- Data: A mapping of symbol_name → Instrument info. - Data: A list of instruments matching the provided symbol names.
Instrument info is one of: Identify each item by its ``symbolName`` field (do not rely on the order).
Each item is one of:
* SecuritiesAndFunds * SecuritiesAndFunds
* TreasuryBonds * TreasuryBonds
* StockOptions * StockOptions
@@ -205,7 +219,7 @@ class DataEngine_TseIfb_SyncClient:
>>> result = client.instruments_static_info_by_name( >>> result = client.instruments_static_info_by_name(
... ["فملی", "خودرو"] ... ["فملی", "خودرو"]
... ) ... )
>>> print(result["Data"]["فملی"]["symbolIsin"]) >>> print(result["Data"][0]["symbolIsin"])
""" """
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name', url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name',
@@ -236,7 +250,8 @@ class DataEngine_TseIfb_SyncClient:
Instruments: Instruments:
A dictionary containing: A dictionary containing:
- Data: A list of instruments matching the provided ISINs. - Data: A list of instruments matching the provided ISINs.
Each item can be SecuritiesAndFunds, TreasuryBonds, Identify each item by its ``symbolIsin`` field (do not rely on
the order). Each item can be SecuritiesAndFunds, TreasuryBonds,
StockOptions, StockFutures, or None if not found. StockOptions, StockFutures, or None if not found.
- Status: Status information returned by the API. - Status: Status information returned by the API.
@@ -393,7 +408,8 @@ class DataEngine_TseIfb_SyncClient:
""" """
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names (synchronous). Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names (synchronous).
This endpoint returns the top-of-the-book order data, including: This endpoint returns the best limit levels of the order book (up to 6 levels per
instrument), each including:
- Best bid price, quantity, and order count - Best bid price, quantity, and order count
- Best ask price, quantity, and order count - Best ask price, quantity, and order count
@@ -406,8 +422,9 @@ class DataEngine_TseIfb_SyncClient:
BestLimitResponse: BestLimitResponse:
An object containing: An object containing:
- **Data**: - **Data**:
Mapping of symbol_name → BestLimitItem Mapping of symbol_name → best limit levels: a dictionary with up to 6
Each BestLimitItem includes: levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count * buy_order_count
* buy_quantity * buy_quantity
* buy_price * buy_price
@@ -423,7 +440,7 @@ class DataEngine_TseIfb_SyncClient:
Example: Example:
>>> client = DataEngine_TseIfb_SyncClient(auth_client) >>> client = DataEngine_TseIfb_SyncClient(auth_client)
>>> bl = client.live_best_limit_by_name(["فملی"]) >>> bl = client.live_best_limit_by_name(["فملی"])
>>> print(bl["Data"]["فملی"]["buy_price"]) >>> print(bl["Data"]["فملی"]["1"]["buy_price"])
""" """
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/tse-ifb/live/data/instruments/best-limit/symbol/name', url='https://core.hedgetech.ir/data-engine/tse-ifb/live/data/instruments/best-limit/symbol/name',
@@ -446,7 +463,7 @@ class DataEngine_TseIfb_SyncClient:
""" """
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes (synchronous). Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes (synchronous).
This endpoint returns the top-of-book order metrics for each ISIN instrument. This endpoint returns the best limit levels (up to 6 per instrument) for each ISIN instrument.
Args: Args:
symbol_isins (List[str]): symbol_isins (List[str]):
@@ -456,8 +473,9 @@ class DataEngine_TseIfb_SyncClient:
BestLimitResponse: BestLimitResponse:
An object containing: An object containing:
- **Data**: - **Data**:
Mapping of symbol_isin → BestLimitItem Mapping of symbol_isin → best limit levels: a dictionary with up to 6
Each BestLimitItem includes: levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count * buy_order_count
* buy_quantity * buy_quantity
* buy_price * buy_price
@@ -473,7 +491,7 @@ class DataEngine_TseIfb_SyncClient:
Example: Example:
>>> client = DataEngine_TseIfb_SyncClient(auth_client) >>> client = DataEngine_TseIfb_SyncClient(auth_client)
>>> bl = client.live_best_limit_by_isin(["IRO1XYZ12345"]) >>> bl = client.live_best_limit_by_isin(["IRO1XYZ12345"])
>>> print(bl["Data"]["IRO1XYZ12345"]["sell_quantity"]) >>> print(bl["Data"]["IRO1XYZ12345"]["1"]["sell_quantity"])
""" """
data = self.__AuthSyncClient.httpx_Client.get( data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/tse-ifb/live/data/instruments/best-limit/symbol/isin', url='https://core.hedgetech.ir/data-engine/tse-ifb/live/data/instruments/best-limit/symbol/isin',
@@ -903,7 +921,7 @@ class DataEngine_TseIfb_SyncClient:
"nav": float, "nav": float,
"units": int, "units": int,
"marketCap": int, "marketCap": int,
"as_of": datetime "as_of": datetime # typically an ISO-formatted string in the decoded JSON
}, },
... ...
}, },
@@ -950,7 +968,7 @@ class DataEngine_TseIfb_SyncClient:
"nav": float, "nav": float,
"units": int, "units": int,
"marketCap": int, "marketCap": int,
"as_of": datetime "as_of": datetime # typically an ISO-formatted string in the decoded JSON
}, },
... ...
}, },
@@ -1087,10 +1105,14 @@ class DataEngine_TseIfb_SyncClient:
""" """
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by symbol name (synchronous). Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by symbol name (synchronous).
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
Args: Args:
symbol_name (str): Trading symbol name (e.g., "فملی"). symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp for the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False). AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
Resolution (Literal): Data resolution. Options: Resolution (Literal): Data resolution. Options:
- "1m", "5m", "15m", "30m", "1h" for intraday - "1m", "5m", "15m", "30m", "1h" for intraday
@@ -1164,10 +1186,14 @@ class DataEngine_TseIfb_SyncClient:
""" """
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by ISIN code (synchronous). Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by ISIN code (synchronous).
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
Args: Args:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001"). symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp for the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False). AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
Resolution (Literal): Data resolution. Options: Resolution (Literal): Data resolution. Options:
- "1m", "5m", "15m", "30m", "1h" for intraday - "1m", "5m", "15m", "30m", "1h" for intraday
@@ -1237,10 +1263,12 @@ class DataEngine_TseIfb_SyncClient:
""" """
Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name (synchronous). Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name (synchronous).
All parameters are keyword-only.
Args: Args:
symbol_name (str): Trading symbol name (e.g., "فملی"). symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp marking the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns: Returns:
CorporateActionResponse: TypedDict with structure: CorporateActionResponse: TypedDict with structure:
@@ -1248,7 +1276,8 @@ class DataEngine_TseIfb_SyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]], "Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"Status": Status "Status": Status
} }
Each item in Data includes fields such as: Each item in Data includes fields such as (use ``corporateAction`` to tell the two
kinds of items apart):
- Date_timestamp: int - Date_timestamp: int
- corporateAction: str - corporateAction: str
- symbolName: str - symbolName: str
@@ -1302,10 +1331,12 @@ class DataEngine_TseIfb_SyncClient:
""" """
Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code (synchronous). Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code (synchronous).
All parameters are keyword-only.
Args: Args:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001"). symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp marking the start of the requested period. start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period. end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns: Returns:
CorporateActionResponse: TypedDict with structure: CorporateActionResponse: TypedDict with structure:
@@ -1313,7 +1344,8 @@ class DataEngine_TseIfb_SyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]], "Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"Status": Status "Status": Status
} }
Each item in Data includes fields such as: Each item in Data includes fields such as (use ``corporateAction`` to tell the two
kinds of items apart):
- Date_timestamp: int - Date_timestamp: int
- corporateAction: str - corporateAction: str
- symbolName: str - symbolName: str
@@ -1384,15 +1416,26 @@ class DataEngine_TseIfb_SyncClient:
]: ]:
""" """
WebSocket streaming is not available in the synchronous version. Subscribe to **real-time WebSocket updates** for a list of instruments by symbol name (synchronous).
The synchronous client does not support real-time WebSocket subscriptions. Opens a blocking WebSocket connection and yields continuous updates for multiple market
Although the method signature exists to maintain interface compatibility, channels such as best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs
it cannot provide live updates like the asynchronous client. individual trades, contract information, and fund information.
All requested channels and instruments share a single connection. Every message belongs to
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolName"]`` to tell
them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (typically from another thread,
since the iterating thread is blocked while waiting) to stop it. The check happens each
time a message arrives and after a receive timeout (2 seconds without messages), so the
stream ends within about 2 seconds at most. The connection is closed automatically when
the generator finishes.
Args: Args:
channels (List[str]): channels (List[str]):
List of channels to subscribe to. Possible values are: List of channels to subscribe to. Possible values:
- 'best-limit' - 'best-limit'
- 'order-book' - 'order-book'
- 'ohlcv-last-1m' - 'ohlcv-last-1m'
@@ -1402,19 +1445,43 @@ class DataEngine_TseIfb_SyncClient:
- 'fund-info' - 'fund-info'
symbol_names (List[str]): symbol_names (List[str]):
List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]). List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]).
event (Event | None, optional): event (threading.Event | None, optional):
Optional event object to mimic the async interface. Optional ``threading.Event`` used as a stop switch. It must be set for the stream to run:
It has no effect in the synchronous client. the loop continues while `event.is_set()` is True.
Defaults to a new, already-set Event (the stream then runs until the connection ends).
Returns: Yields:
Generator: Union[BestLimit_WS_symbolName, OrderBook_WS_symbolName, Aggregate_WS_symbolName,
This generator does not yield any data in the synchronous client. institutional_vs_individual_WS_symbolName, ContractInfo_WS_symbolName, FundInfo_WS_symbolName,
Use `DataEngine_TseIfb_AsyncClient.websocket_by_name` for streaming data. OHLCV_WS_symbolName]:
One message per update, as a TypedDict that depends on the channel:
- **BestLimit_WS_symbolName** for 'best-limit'
- **OrderBook_WS_symbolName** for 'order-book'
- **OHLCV_WS_symbolName** for 'ohlcv-last-1m'
- **Aggregate_WS_symbolName** for 'aggregate'
- **institutional_vs_individual_WS_symbolName** for 'institutional-vs-individual'
- **ContractInfo_WS_symbolName** for 'contract-info'
- **FundInfo_WS_symbolName** for 'fund-info'
Each yielded object contains:
- `channel`: Literal — name of the channel (one of the values above)
- `symbolName`: str — instrument symbol name
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
numeric ``ServerTimeStamp`` in ``Status``)
- `data`: channel-specific real-time data.
Raises: Raises:
NotImplementedError: websockets.exceptions.WebSocketException or OSError:
Always raised to indicate that real-time WebSocket streaming Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
is not supported in the synchronous version. or ``OSError`` on a network failure).
Note:
* This generator blocks the calling thread while waiting for messages. Run it in a
dedicated thread if the rest of your program must keep working.
* Once the connection is established, errors do not raise: a closed connection, invalid
JSON or a network error closes the connection and the generator simply ends. If you need
a permanent stream, wrap the ``for`` loop in a reconnect loop.
* A receive timeout is not an error; the generator just keeps waiting.
Example: Example:
>>> client = DataEngine_TseIfb_SyncClient(auth_client) >>> client = DataEngine_TseIfb_SyncClient(auth_client)
@@ -1422,7 +1489,8 @@ class DataEngine_TseIfb_SyncClient:
... channels=["best-limit", "order-book"], ... channels=["best-limit", "order-book"],
... symbol_names=["فملی"] ... symbol_names=["فملی"]
... ): ... ):
... print(update) # This will not run; method is not implemented ... if update["channel"] == "best-limit":
... print(update["symbolName"], update["data"]["1"]["buy_price"])
""" """
if not isinstance(event,Event): if not isinstance(event,Event):
@@ -1477,15 +1545,26 @@ class DataEngine_TseIfb_SyncClient:
None None
]: ]:
""" """
WebSocket streaming is not available in the synchronous version. Subscribe to **real-time WebSocket updates** for a list of instruments using their ISIN codes (synchronous).
The synchronous client does not support real-time WebSocket subscriptions Opens a blocking WebSocket connection and yields continuous updates for multiple market
by ISIN codes. This method exists to maintain interface consistency with channels such as best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs
the asynchronous client but does not yield any live updates. individual trades, contract information, and fund information.
All requested channels and instruments share a single connection. Every message belongs to
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolIsin"]`` to tell
them apart.
Stopping the stream:
The loop runs while ``event`` is set. Call ``event.clear()`` (typically from another thread,
since the iterating thread is blocked while waiting) to stop it. The check happens each
time a message arrives and after a receive timeout (2 seconds without messages), so the
stream ends within about 2 seconds at most. The connection is closed automatically when
the generator finishes.
Args: Args:
channels (List[str]): channels (List[str]):
List of channels to subscribe to. Possible values are: List of channels to subscribe to. Possible values:
- 'best-limit' - 'best-limit'
- 'order-book' - 'order-book'
- 'ohlcv-last-1m' - 'ohlcv-last-1m'
@@ -1494,21 +1573,44 @@ class DataEngine_TseIfb_SyncClient:
- 'contract-info' - 'contract-info'
- 'fund-info' - 'fund-info'
symbol_isins (List[str]): symbol_isins (List[str]):
List of instrument ISIN codes to receive updates for List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]).
(e.g., ["IR1234567890", "IR0987654321"]). event (threading.Event | None, optional):
event (Event | None, optional): Optional ``threading.Event`` used as a stop switch. It must be set for the stream to run:
Optional event object to mimic the async interface. the loop continues while `event.is_set()` is True.
It has no effect in the synchronous client. Defaults to a new, already-set Event (the stream then runs until the connection ends).
Returns: Yields:
Generator: Union[BestLimit_WS_symbolIsin, OrderBook_WS_symbolIsin, Aggregate_WS_symbolIsin,
This generator does not yield any data in the synchronous client. institutional_vs_individual_WS_symbolIsin, ContractInfo_WS_symbolIsin, FundInfo_WS_symbolIsin,
Use `DataEngine_TseIfb_AsyncClient.websocket_by_isin` for real-time streaming. OHLCV_WS_symbolIsin]:
One message per update, as a TypedDict that depends on the channel:
- **BestLimit_WS_symbolIsin** for 'best-limit'
- **OrderBook_WS_symbolIsin** for 'order-book'
- **OHLCV_WS_symbolIsin** for 'ohlcv-last-1m'
- **Aggregate_WS_symbolIsin** for 'aggregate'
- **institutional_vs_individual_WS_symbolIsin** for 'institutional-vs-individual'
- **ContractInfo_WS_symbolIsin** for 'contract-info'
- **FundInfo_WS_symbolIsin** for 'fund-info'
Each yielded object contains:
- `channel`: Literal — name of the channel (one of the values above)
- `symbolIsin`: str — instrument ISIN
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
numeric ``ServerTimeStamp`` in ``Status``)
- `data`: channel-specific real-time data.
Raises: Raises:
NotImplementedError: websockets.exceptions.WebSocketException or OSError:
Always raised to indicate that WebSocket streaming is not supported Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
in the synchronous client. or ``OSError`` on a network failure).
Note:
* This generator blocks the calling thread while waiting for messages. Run it in a
dedicated thread if the rest of your program must keep working.
* Once the connection is established, errors do not raise: a closed connection, invalid
JSON or a network error closes the connection and the generator simply ends. If you need
a permanent stream, wrap the ``for`` loop in a reconnect loop.
* A receive timeout is not an error; the generator just keeps waiting.
Example: Example:
>>> client = DataEngine_TseIfb_SyncClient(auth_client) >>> client = DataEngine_TseIfb_SyncClient(auth_client)
@@ -1516,7 +1618,8 @@ class DataEngine_TseIfb_SyncClient:
... channels=["best-limit", "order-book"], ... channels=["best-limit", "order-book"],
... symbol_isins=["IR1234567890"] ... symbol_isins=["IR1234567890"]
... ): ... ):
... print(update) # This will not run; method is not implemented ... if update["channel"] == "best-limit":
... print(update["symbolIsin"], update["data"]["1"]["buy_price"])
""" """
if not isinstance(event,Event): if not isinstance(event,Event):
@@ -21,17 +21,34 @@ class WebsocketBase_symbolIsin(TypedDict):
Base structure for websocket messages containing fund or instrument information Base structure for websocket messages containing fund or instrument information
identified by ISIN (International Securities Identification Number). identified by ISIN (International Securities Identification Number).
This TypedDict defines the common structure of messages received over a websocket This TypedDict defines the common envelope of messages received over a websocket
where each message is linked to a specific ISIN. where each message is linked to a specific ISIN. It does NOT include the
market payload (``data``): every channel-specific message type below
(``BestLimit_WS_symbolIsin``, ``OrderBook_WS_symbolIsin``, ...) extends this class and
adds its own ``data`` field.
Attributes: Attributes:
channel (str): The name of the websocket channel through which the message is sent. channel (Literal["best-limit", "order-book", "ohlcv-last-1m", "aggregate",
"institutional-vs-individual", "contract-info", "fund-info"]):
The name of the websocket channel through which the message is sent.
It identifies the kind of payload carried in ``data``:
- ``best-limit``: best limit order book levels (``BestLimit_WS_*``).
- ``order-book``: full order book (``OrderBook_WS_*``).
- ``ohlcv-last-1m``: live 1-minute OHLCV data (``OHLCV_WS_*``).
- ``aggregate``: aggregate trading statistics (``Aggregate_WS_*``).
- ``institutional-vs-individual``: individual vs institutional breakdown
(``institutional_vs_individual_WS_*``).
- ``contract-info``: open interest and margins (``ContractInfo_WS_*``).
- ``fund-info``: NAV, units and market cap (``FundInfo_WS_*``).
symbolIsin (str): The ISIN code of the instrument or fund. symbolIsin (str): The ISIN code of the instrument or fund.
timestamp (str): ISO-formatted timestamp indicating when the message was generated. timestamp (str): ISO-formatted timestamp indicating when the message was generated.
It is a string, unlike the numeric ``ServerTimeStamp`` in ``Status``, and it
may or may not carry a timezone suffix.
Example: Example:
>>> message: WebsocketBase_symbolIsin = { >>> message: WebsocketBase_symbolIsin = {
... "channel": "fund_live_updates", ... "channel": "best-limit",
... "symbolIsin": "IR0001234567", ... "symbolIsin": "IR0001234567",
... "timestamp": "2025-11-19T10:30:00Z" ... "timestamp": "2025-11-19T10:30:00Z"
... } ... }
@@ -56,17 +73,34 @@ class WebsocketBase_symbolName(TypedDict):
Base structure for websocket messages containing fund or instrument information Base structure for websocket messages containing fund or instrument information
identified by symbol name. identified by symbol name.
This TypedDict defines the common structure of messages received over a websocket This TypedDict defines the common envelope of messages received over a websocket
where each message is linked to a specific symbol name. where each message is linked to a specific symbol name. It does NOT include the
market payload (``data``): every channel-specific message type below
(``BestLimit_WS_symbolName``, ``OrderBook_WS_symbolName``, ...) extends this class and
adds its own ``data`` field.
Attributes: Attributes:
channel (str): The name of the websocket channel through which the message is sent. channel (Literal["best-limit", "order-book", "ohlcv-last-1m", "aggregate",
"institutional-vs-individual", "contract-info", "fund-info"]):
The name of the websocket channel through which the message is sent.
It identifies the kind of payload carried in ``data``:
- ``best-limit``: best limit order book levels (``BestLimit_WS_*``).
- ``order-book``: full order book (``OrderBook_WS_*``).
- ``ohlcv-last-1m``: live 1-minute OHLCV data (``OHLCV_WS_*``).
- ``aggregate``: aggregate trading statistics (``Aggregate_WS_*``).
- ``institutional-vs-individual``: individual vs institutional breakdown
(``institutional_vs_individual_WS_*``).
- ``contract-info``: open interest and margins (``ContractInfo_WS_*``).
- ``fund-info``: NAV, units and market cap (``FundInfo_WS_*``).
symbolName (str): The symbol name of the instrument or fund. symbolName (str): The symbol name of the instrument or fund.
timestamp (str): ISO-formatted timestamp indicating when the message was generated. timestamp (str): ISO-formatted timestamp indicating when the message was generated.
It is a string, unlike the numeric ``ServerTimeStamp`` in ``Status``, and it
may or may not carry a timezone suffix.
Example: Example:
>>> message: WebsocketBase_symbolName = { >>> message: WebsocketBase_symbolName = {
... "channel": "fund_live_updates", ... "channel": "best-limit",
... "symbolName": "ETF001", ... "symbolName": "ETF001",
... "timestamp": "2025-11-19T10:30:00Z" ... "timestamp": "2025-11-19T10:30:00Z"
... } ... }
@@ -115,12 +149,15 @@ class Status(TypedDict):
Attributes: Attributes:
State (bool): Indicates whether the operation or request was successful. State (bool): Indicates whether the operation or request was successful.
ServerTimeStamp (float): Server timestamp, typically a Unix timestamp. ServerTimeStamp (float): Server time as a Unix timestamp (seconds since epoch,
may include fractional seconds). Note that this is a number, unlike the
ISO-formatted string ``timestamp`` used in websocket messages.
Version (str): Version of the API or server sending the message. Version (str): Version of the API or server sending the message.
Author (str): Name of the author or owner of the API/server. Author (str): Name of the author or owner of the API/server.
Description (StatusDescription): A human-readable description of the status Description (StatusDescription): A human-readable description of the status
in multiple languages. in multiple languages.
StatusCode (int): Numeric status code returned by the server. StatusCode (int): Numeric status code returned by the server (HTTP-style,
e.g. 200 for success).
Example: Example:
>>> status: Status = { >>> status: Status = {
@@ -153,13 +190,19 @@ class SecuritiesAndFunds(TypedDict):
traded instruments, providing all necessary details for order validation, traded instruments, providing all necessary details for order validation,
display, and transaction execution. display, and transaction execution.
Note:
Commission rates are fractions, not percentages (``0.0015`` means 0.15%).
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this is the type
that has ``baseVolume`` (``TreasuryBonds`` has ``baseVol``) and has no
``optionType`` or ``firstMargin``.
Attributes: Attributes:
symbolIsin (str): International Securities Identification Number (ISIN) of the instrument. symbolIsin (str): International Securities Identification Number (ISIN) of the instrument.
symbolName (str): Trading symbol of the instrument. symbolName (str): Trading symbol of the instrument.
title (str): Human-readable name or title of the security/fund. title (str): Human-readable name or title of the security/fund.
buyCommission (float): Commission rate applied when buying this security/fund. buyCommission (float): Commission rate applied when buying this security/fund (fraction, e.g. 0.0015 = 0.15%).
sellCommission (float): Commission rate applied when selling this security/fund. sellCommission (float): Commission rate applied when selling this security/fund (fraction, e.g. 0.0015 = 0.15%).
minValidBuyVolume (int): Minimum allowable buy volume per order. minValidBuyVolume (int): Minimum allowable buy volume per order.
maxValidBuyVolume (int): Maximum allowable buy volume per order. maxValidBuyVolume (int): Maximum allowable buy volume per order.
@@ -169,11 +212,11 @@ class SecuritiesAndFunds(TypedDict):
canBuy (bool): Indicates whether buying is currently permitted. canBuy (bool): Indicates whether buying is currently permitted.
canSell (bool): Indicates whether selling is currently permitted. canSell (bool): Indicates whether selling is currently permitted.
minAllowedPrice (float): Minimum price allowed for placing an order. minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
maxAllowedPrice (float): Maximum price allowed for placing an order. maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
is_ETF (bool): Indicates if the security/fund is an Exchange-Traded Fund (ETF). is_ETF (bool): Indicates if the security/fund is an Exchange-Traded Fund (ETF).
baseVolume (float): The base trading volume unit of the instrument. baseVolume (float): Base volume (حجم مبنا) of the instrument, as defined by the exchange.
minDealablePrice (float): Minimum price at which a deal can be executed. minDealablePrice (float): Minimum price at which a deal can be executed.
minDealableCount (int): Minimum number of units that can be traded per deal. minDealableCount (int): Minimum number of units that can be traded per deal.
@@ -251,6 +294,11 @@ class StockFutures(TypedDict):
ETFs, or other underlying instruments, providing all necessary details for order ETFs, or other underlying instruments, providing all necessary details for order
validation, execution, and reporting. validation, execution, and reporting.
Note:
Commission rates are fractions, not percentages (``0.001`` means 0.1%).
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this type is
recognized by ``firstMargin`` / ``minimumMargin``.
Attributes: Attributes:
symbolIsin (str): ISIN code of the futures contract. symbolIsin (str): ISIN code of the futures contract.
title (str): Human-readable name or title of the futures contract. title (str): Human-readable name or title of the futures contract.
@@ -269,8 +317,8 @@ class StockFutures(TypedDict):
ExpirationDate (str): Expiration date of the contract in ISO format (YYYY-MM-DD). ExpirationDate (str): Expiration date of the contract in ISO format (YYYY-MM-DD).
DaysToExpiration (int): Number of days remaining until the contract expires. DaysToExpiration (int): Number of days remaining until the contract expires.
buyCommission (float): Commission rate applied when buying the contract. buyCommission (float): Commission rate applied when buying the contract (fraction, e.g. 0.001 = 0.1%).
sellCommission (float): Commission rate applied when selling the contract. sellCommission (float): Commission rate applied when selling the contract (fraction, e.g. 0.001 = 0.1%).
minValidBuyVolume (int): Minimum valid buy volume per order. minValidBuyVolume (int): Minimum valid buy volume per order.
maxValidBuyVolume (int): Maximum valid buy volume per order. maxValidBuyVolume (int): Maximum valid buy volume per order.
@@ -280,8 +328,8 @@ class StockFutures(TypedDict):
canBuy (bool): Indicates whether buying is currently allowed. canBuy (bool): Indicates whether buying is currently allowed.
canSell (bool): Indicates whether selling is currently allowed. canSell (bool): Indicates whether selling is currently allowed.
minAllowedPrice (float): Minimum price allowed for placing an order. minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
maxAllowedPrice (float): Maximum price allowed for placing an order. maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
minDealableCount (int): Minimum number of contracts per deal. minDealableCount (int): Minimum number of contracts per deal.
minDealablePrice (float): Minimum price at which a deal can be executed. minDealablePrice (float): Minimum price at which a deal can be executed.
@@ -399,13 +447,18 @@ class StockOptions(TypedDict):
This TypedDict is typically used in systems that handle equity options, providing This TypedDict is typically used in systems that handle equity options, providing
all necessary details for order validation, execution, reporting, and margin calculations. all necessary details for order validation, execution, reporting, and margin calculations.
Note:
Commission rates are fractions, not percentages (``0.001`` means 0.1%).
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this type is
recognized by ``optionType`` / ``strikePrice``.
Attributes: Attributes:
symbolIsin (str): ISIN code of the options contract. symbolIsin (str): ISIN code of the options contract.
symbolName (str): Trading symbol of the options contract. symbolName (str): Trading symbol of the options contract.
title (str): Human-readable name or title of the options contract. title (str): Human-readable name or title of the options contract.
buyCommission (float): Commission rate applied when buying the option. buyCommission (float): Commission rate applied when buying the option (fraction, e.g. 0.001 = 0.1%).
sellCommission (float): Commission rate applied when selling the option. sellCommission (float): Commission rate applied when selling the option (fraction, e.g. 0.001 = 0.1%).
minValidBuyVolume (int): Minimum valid buy volume per order. minValidBuyVolume (int): Minimum valid buy volume per order.
maxValidBuyVolume (int): Maximum valid buy volume per order. maxValidBuyVolume (int): Maximum valid buy volume per order.
@@ -415,17 +468,17 @@ class StockOptions(TypedDict):
canBuy (bool): Indicates whether buying is currently allowed. canBuy (bool): Indicates whether buying is currently allowed.
canSell (bool): Indicates whether selling is currently allowed. canSell (bool): Indicates whether selling is currently allowed.
minAllowedPrice (float): Minimum price allowed for placing an order. minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
maxAllowedPrice (float): Maximum price allowed for placing an order. maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
minDealablePrice (float): Minimum price at which a deal can be executed. minDealablePrice (float): Minimum price at which a deal can be executed.
minDealableCount (int): Minimum number of contracts per deal. minDealableCount (int): Minimum number of contracts per deal.
owner (str): Name of the contract owner or issuing entity. owner (str): Name of the contract owner or issuing entity.
strikePrice (float): Strike price of the option. strikePrice (float): Strike (exercise) price of the option, in IRR.
csize (int): Contract size (number of underlying units per option contract). csize (int): Contract size (number of underlying units per option contract).
optionType (str): Type of the option, e.g., "Call" or "Put". optionType (str): Type of the option: "Call" or "Put".
ExpirationDate (str): Expiration date of the option in ISO format (YYYY-MM-DD). ExpirationDate (str): Expiration date of the option in ISO format (YYYY-MM-DD).
DaysToExpiration (int): Number of days remaining until expiration. DaysToExpiration (int): Number of days remaining until expiration.
@@ -543,13 +596,19 @@ class TreasuryBonds(TypedDict):
ETFs, or similar instruments, providing all necessary details for order validation, ETFs, or similar instruments, providing all necessary details for order validation,
execution, reporting, and risk management. execution, reporting, and risk management.
Note:
Commission rates are fractions, not percentages (``0.001`` means 0.1%).
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this type is
recognized by ``baseVol`` (``SecuritiesAndFunds`` calls the same concept
``baseVolume``).
Attributes: Attributes:
symbolIsin (str): ISIN code of the treasury bond. symbolIsin (str): ISIN code of the treasury bond.
symbolName (str): Trading symbol of the bond. symbolName (str): Trading symbol of the bond.
title (str): Human-readable name or title of the bond. title (str): Human-readable name or title of the bond.
buyCommission (float): Commission rate applied when buying the bond. buyCommission (float): Commission rate applied when buying the bond (fraction, e.g. 0.001 = 0.1%).
sellCommission (float): Commission rate applied when selling the bond. sellCommission (float): Commission rate applied when selling the bond (fraction, e.g. 0.001 = 0.1%).
minValidBuyVolume (int): Minimum valid buy volume per order. minValidBuyVolume (int): Minimum valid buy volume per order.
maxValidBuyVolume (int): Maximum valid buy volume per order. maxValidBuyVolume (int): Maximum valid buy volume per order.
@@ -559,10 +618,10 @@ class TreasuryBonds(TypedDict):
canBuy (bool): Indicates whether buying is currently allowed. canBuy (bool): Indicates whether buying is currently allowed.
canSell (bool): Indicates whether selling is currently allowed. canSell (bool): Indicates whether selling is currently allowed.
minAllowedPrice (float): Minimum price allowed for placing an order. minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
maxAllowedPrice (float): Maximum price allowed for placing an order. maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
baseVol (float): Base trading volume unit of the bond. baseVol (float): Base volume (حجم مبنا) of the bond, as defined by the exchange.
minDealablePrice (float): Minimum price at which a deal can be executed. minDealablePrice (float): Minimum price at which a deal can be executed.
minDealableCount (int): Minimum number of bonds per deal. minDealableCount (int): Minimum number of bonds per deal.
@@ -646,14 +705,22 @@ class Instruments(TypedDict):
Represents a complete response containing a list of various financial instruments Represents a complete response containing a list of various financial instruments
along with the server status metadata. along with the server status metadata.
This TypedDict is commonly used to fetch or store all instruments data from an API, This TypedDict is commonly used to fetch or store instruments data from an API,
including equities, ETFs, stock futures, stock options, and treasury bonds. Each including equities, ETFs, stock futures, stock options, and treasury bonds. Each
instrument in the `Data` list can be one of several TypedDict types, providing instrument in the `Data` list can be one of several TypedDict types, providing
a unified structure for heterogeneous financial instruments. a unified structure for heterogeneous financial instruments.
The type of an item can be recognized from its fields:
- ``optionType`` / ``strikePrice`` present -> ``StockOptions``
- ``firstMargin`` / ``minimumMargin`` present -> ``StockFutures``
- ``baseVol`` present -> ``TreasuryBonds``
- ``baseVolume`` present -> ``SecuritiesAndFunds``
Attributes: Attributes:
Data (List[Union[SecuritiesAndFunds, StockFutures, StockOptions, TreasuryBonds, None]]): Data (List[Union[SecuritiesAndFunds, StockFutures, StockOptions, TreasuryBonds, None]]):
A list containing individual instrument data. Each item can be: A list containing individual instrument data. Each item can be:
- SecuritiesAndFunds: For standard securities and ETFs - SecuritiesAndFunds: For standard securities and ETFs
- StockFutures: For futures contracts on equities or ETFs - StockFutures: For futures contracts on equities or ETFs
- StockOptions: For options contracts - StockOptions: For options contracts
@@ -755,13 +822,18 @@ class BestLimitItem(TypedDict):
""" """
Represents the best limit order information at a given price level for a financial instrument. Represents the best limit order information at a given price level for a financial instrument.
Note:
A level that has no orders on one side is expected to carry ``0`` for that
side's count, quantity and price. Check that a price is greater than zero
before using it in calculations (e.g. spread). Prices are in IRR.
Attributes: Attributes:
buy_order_count (int): Number of active buy orders at this price level. buy_order_count (int): Number of active buy orders at this price level.
buy_quantity (int): Total quantity available for buying at this price level. buy_quantity (int): Total quantity available for buying at this price level.
buy_price (int): Price level for buy orders. buy_price (int): Price level for buy orders (bid).
sell_order_count (int): Number of active sell orders at this price level. sell_order_count (int): Number of active sell orders at this price level.
sell_quantity (int): Total quantity available for selling at this price level. sell_quantity (int): Total quantity available for selling at this price level.
sell_price (int): Price level for sell orders. sell_price (int): Price level for sell orders (ask).
Example: Example:
>>> item: BestLimitItem = { >>> item: BestLimitItem = {
@@ -786,8 +858,13 @@ class BestLimitResponse(TypedDict):
""" """
Response structure for best limit orders from a REST API call. Response structure for best limit orders from a REST API call.
The depth is up to 6 levels per instrument: ``"1"`` is the best level (highest bid /
lowest ask) and ``"6"`` the deepest.
Attributes: Attributes:
Data (BestLimit): Aggregated best limit order data. Data (Dict[str, Dict[Literal['1','2','3','4','5','6'], BestLimitItem]]):
Dictionary mapping each instrument identifier (ISIN or symbolName) to its
best limit levels.
Status (Status): Metadata about the server response, including success state, Status (Status): Metadata about the server response, including success state,
timestamp, version, author, description, and status code. timestamp, version, author, description, and status code.
@@ -836,13 +913,15 @@ class BestLimit_WS_symbolIsin(WebsocketBase_symbolIsin):
This TypedDict extends `WebsocketBase_symbolIsin` and represents real-time best This TypedDict extends `WebsocketBase_symbolIsin` and represents real-time best
limit order updates for a specific instrument identified by its ISIN. limit order updates for a specific instrument identified by its ISIN.
The ``channel`` of these messages is ``"best-limit"``.
Attributes: Attributes:
data (Dict[str, BestLimitItem]): Dictionary mapping price levels or order priorities data (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit levels of
to BestLimitItem objects for the instrument. the instrument. Key ``"1"`` is the best level and ``"6"`` the deepest.
Example: Example:
>>> ws_data: BestLimit_WS_symbolIsin = { >>> ws_data: BestLimit_WS_symbolIsin = {
... "channel": "best_limit_updates", ... "channel": "best-limit",
... "symbolIsin": "IR0001234567", ... "symbolIsin": "IR0001234567",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": { ... "data": {
@@ -880,13 +959,15 @@ class BestLimit_WS_symbolName(WebsocketBase_symbolName):
This TypedDict extends `WebsocketBase_symbolName` and represents real-time best This TypedDict extends `WebsocketBase_symbolName` and represents real-time best
limit order updates for a specific instrument identified by its trading symbol. limit order updates for a specific instrument identified by its trading symbol.
The ``channel`` of these messages is ``"best-limit"``.
Attributes: Attributes:
data (Dict[str, BestLimitItem]): Dictionary mapping price levels or order priorities data (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit levels of
to BestLimitItem objects for the instrument. the instrument. Key ``"1"`` is the best level and ``"6"`` the deepest.
Example: Example:
>>> ws_data: BestLimit_WS_symbolName = { >>> ws_data: BestLimit_WS_symbolName = {
... "channel": "best_limit_updates", ... "channel": "best-limit",
... "symbolName": "ETF001", ... "symbolName": "ETF001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": { ... "data": {
@@ -924,7 +1005,7 @@ class OrderItem(TypedDict):
Represents a single order entry in the order book. Represents a single order entry in the order book.
Attributes: Attributes:
price (float): Price level of the order. price (float): Price level of the order, in IRR.
quantity (int): Total quantity available at this price level. quantity (int): Total quantity available at this price level.
count (int): Number of orders at this price level. count (int): Number of orders at this price level.
@@ -1002,12 +1083,14 @@ class OrderBook_WS_symbolIsin(WebsocketBase_symbolIsin):
""" """
Websocket message structure for order book updates identified by ISIN. Websocket message structure for order book updates identified by ISIN.
The ``channel`` of these messages is ``"order-book"``.
Attributes: Attributes:
data (OrderBook): Real-time order book for the specified instrument. data (OrderBook): Real-time order book for the specified instrument.
Example: Example:
>>> ws_data: OrderBook_WS_symbolIsin = { >>> ws_data: OrderBook_WS_symbolIsin = {
... "channel": "order_book_updates", ... "channel": "order-book",
... "symbolIsin": "IR0001234567", ... "symbolIsin": "IR0001234567",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": { ... "data": {
@@ -1025,12 +1108,14 @@ class OrderBook_WS_symbolName(WebsocketBase_symbolName):
""" """
Websocket message structure for order book updates identified by symbol name. Websocket message structure for order book updates identified by symbol name.
The ``channel`` of these messages is ``"order-book"``.
Attributes: Attributes:
data (OrderBook): Real-time order book for the specified instrument. data (OrderBook): Real-time order book for the specified instrument.
Example: Example:
>>> ws_data: OrderBook_WS_symbolName = { >>> ws_data: OrderBook_WS_symbolName = {
... "channel": "order_book_updates", ... "channel": "order-book",
... "symbolName": "ETF001", ... "symbolName": "ETF001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": { ... "data": {
@@ -1053,13 +1138,18 @@ class Aggregate(TypedDict):
This includes trade statistics, volume, value, and price information. This includes trade statistics, volume, value, and price information.
Note:
Prices and ``total_value`` are in IRR. Before the first trade of a session the
price / volume fields may be ``0``, while ``previous_close`` still holds the
last close.
Attributes: Attributes:
date (str): Date of the aggregation in ISO format (YYYY-MM-DD). date (str): Date of the aggregation in ISO format (YYYY-MM-DD).
time (str): Time of the aggregation in HH:MM:SS format. time (str): Time of the aggregation in HH:MM:SS format.
trade_count (int): Number of trades executed during this period. trade_count (int): Number of trades executed during this period.
total_volume (int): Total traded volume. total_volume (int): Total traded volume.
total_value (int): Total traded value (sum of price * quantity). total_value (int): Total traded value (sum of price * quantity), in IRR.
closing_price (float): Closing price at the end of the period. closing_price (float): Closing price as computed by the exchange (it can differ from ``last_price``).
last_price (float): Last traded price. last_price (float): Last traded price.
low_price (float): Lowest price during the period. low_price (float): Lowest price during the period.
high_price (float): Highest price during the period. high_price (float): Highest price during the period.
@@ -1107,6 +1197,7 @@ class AggregateResponse(TypedDict):
timestamp, version, author, description, and status code. timestamp, version, author, description, and status code.
Example: Example:
>>> # ``agg`` is the ``Aggregate`` object from the example above.
>>> response: AggregateResponse = { >>> response: AggregateResponse = {
... "Data": { ... "Data": {
... "IR0001234567": agg ... "IR0001234567": agg
@@ -1133,12 +1224,15 @@ class Aggregate_WS_symbolIsin(WebsocketBase_symbolIsin):
""" """
Websocket message structure for aggregated market data identified by ISIN. Websocket message structure for aggregated market data identified by ISIN.
The ``channel`` of these messages is ``"aggregate"``.
Attributes: Attributes:
data (Aggregate): Real-time aggregated data for the specified instrument. data (Aggregate): Real-time aggregated data for the specified instrument.
Example: Example:
>>> # ``agg`` is the ``Aggregate`` object from the example above.
>>> ws_data: Aggregate_WS_symbolIsin = { >>> ws_data: Aggregate_WS_symbolIsin = {
... "channel": "aggregate_updates", ... "channel": "aggregate",
... "symbolIsin": "IR0001234567", ... "symbolIsin": "IR0001234567",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": agg ... "data": agg
@@ -1153,12 +1247,15 @@ class Aggregate_WS_symbolName(WebsocketBase_symbolName):
""" """
Websocket message structure for aggregated market data identified by symbol name. Websocket message structure for aggregated market data identified by symbol name.
The ``channel`` of these messages is ``"aggregate"``.
Attributes: Attributes:
data (Aggregate): Real-time aggregated data for the specified instrument. data (Aggregate): Real-time aggregated data for the specified instrument.
Example: Example:
>>> # ``agg`` is the ``Aggregate`` object from the example above.
>>> ws_data: Aggregate_WS_symbolName = { >>> ws_data: Aggregate_WS_symbolName = {
... "channel": "aggregate_updates", ... "channel": "aggregate",
... "symbolName": "ETF001", ... "symbolName": "ETF001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": agg ... "data": agg
@@ -1221,6 +1318,7 @@ class Institutional_vs_IndividualItemResponse(TypedDict):
timestamp, version, author, description, and status code. timestamp, version, author, description, and status code.
Example: Example:
>>> # ``trades`` is the ``institutional_vs_individual`` object from the example above.
>>> response: Institutional_vs_IndividualItemResponse = { >>> response: Institutional_vs_IndividualItemResponse = {
... "Data": {"IR0001234567": trades}, ... "Data": {"IR0001234567": trades},
... "Status": { ... "Status": {
@@ -1245,13 +1343,16 @@ class institutional_vs_individual_WS_symbolIsin(WebsocketBase_symbolIsin):
""" """
Websocket message structure for institutional vs individual trading data identified by ISIN. Websocket message structure for institutional vs individual trading data identified by ISIN.
The ``channel`` of these messages is ``"institutional-vs-individual"``.
Attributes: Attributes:
data (institutional_vs_individual): Real-time breakdown of buy/sell activity for data (institutional_vs_individual): Real-time breakdown of buy/sell activity for
individual and institutional traders. individual and institutional traders.
Example: Example:
>>> # ``trades`` is the ``institutional_vs_individual`` object from the example above.
>>> ws_data: institutional_vs_individual_WS_symbolIsin = { >>> ws_data: institutional_vs_individual_WS_symbolIsin = {
... "channel": "inst_vs_ind_updates", ... "channel": "institutional-vs-individual",
... "symbolIsin": "IR0001234567", ... "symbolIsin": "IR0001234567",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": trades ... "data": trades
@@ -1266,13 +1367,16 @@ class institutional_vs_individual_WS_symbolName(WebsocketBase_symbolName):
""" """
Websocket message structure for institutional vs individual trading data identified by symbol name. Websocket message structure for institutional vs individual trading data identified by symbol name.
The ``channel`` of these messages is ``"institutional-vs-individual"``.
Attributes: Attributes:
data (institutional_vs_individual): Real-time breakdown of buy/sell activity for data (institutional_vs_individual): Real-time breakdown of buy/sell activity for
individual and institutional traders. individual and institutional traders.
Example: Example:
>>> # ``trades`` is the ``institutional_vs_individual`` object from the example above.
>>> ws_data: institutional_vs_individual_WS_symbolName = { >>> ws_data: institutional_vs_individual_WS_symbolName = {
... "channel": "inst_vs_ind_updates", ... "channel": "institutional-vs-individual",
... "symbolName": "ETF001", ... "symbolName": "ETF001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": trades ... "data": trades
@@ -1289,6 +1393,10 @@ class ContractInfo(TypedDict):
""" """
Represents key contract information for derivatives, including open interest and margin requirements. Represents key contract information for derivatives, including open interest and margin requirements.
Note:
Present in every overview, but intended for derivatives (stock futures and
options). For other instrument types check the values before relying on them.
Attributes: Attributes:
open_interest (int): Total number of outstanding contracts that have not been settled. open_interest (int): Total number of outstanding contracts that have not been settled.
initial_margin (int): Margin required to open a new position. initial_margin (int): Margin required to open a new position.
@@ -1319,6 +1427,7 @@ class ContractInfoResponse(TypedDict):
timestamp, version, author, description, and status code. timestamp, version, author, description, and status code.
Example: Example:
>>> # ``contract`` is the ``ContractInfo`` object from the example above.
>>> response: ContractInfoResponse = { >>> response: ContractInfoResponse = {
... "Data": {"IRFUT123456": contract}, ... "Data": {"IRFUT123456": contract},
... "Status": { ... "Status": {
@@ -1343,12 +1452,15 @@ class ContractInfo_WS_symbolIsin(WebsocketBase_symbolIsin):
""" """
Websocket message structure for contract information updates identified by ISIN. Websocket message structure for contract information updates identified by ISIN.
The ``channel`` of these messages is ``"contract-info"``.
Attributes: Attributes:
data (ContractInfo): Real-time contract information for the specified instrument. data (ContractInfo): Real-time contract information for the specified instrument.
Example: Example:
>>> # ``contract`` is the ``ContractInfo`` object from the example above.
>>> ws_data: ContractInfo_WS_symbolIsin = { >>> ws_data: ContractInfo_WS_symbolIsin = {
... "channel": "contract_info_updates", ... "channel": "contract-info",
... "symbolIsin": "IRFUT123456", ... "symbolIsin": "IRFUT123456",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": contract ... "data": contract
@@ -1363,12 +1475,15 @@ class ContractInfo_WS_symbolName(WebsocketBase_symbolName):
""" """
Websocket message structure for contract information updates identified by symbol name. Websocket message structure for contract information updates identified by symbol name.
The ``channel`` of these messages is ``"contract-info"``.
Attributes: Attributes:
data (ContractInfo): Real-time contract information for the specified instrument. data (ContractInfo): Real-time contract information for the specified instrument.
Example: Example:
>>> # ``contract`` is the ``ContractInfo`` object from the example above.
>>> ws_data: ContractInfo_WS_symbolName = { >>> ws_data: ContractInfo_WS_symbolName = {
... "channel": "contract_info_updates", ... "channel": "contract-info",
... "symbolName": "FUT001", ... "symbolName": "FUT001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": contract ... "data": contract
@@ -1386,10 +1501,15 @@ class FundInfo(TypedDict):
Represents key information about a fund, including its net asset value, total units, Represents key information about a fund, including its net asset value, total units,
market capitalization, and the timestamp of the data. market capitalization, and the timestamp of the data.
Note:
``as_of`` is annotated as ``datetime``, but a response decoded directly from JSON
carries it as a plain JSON value (typically an ISO-formatted string). Convert it
yourself if you need a ``datetime`` object.
Attributes: Attributes:
nav (float): Net Asset Value of the fund per unit. nav (float): Net Asset Value of the fund per unit, in IRR.
units (int): Total number of fund units outstanding. units (int): Total number of fund units outstanding.
marketCap (int): Total market capitalization of the fund. marketCap (int): Total market capitalization of the fund, in IRR.
as_of (datetime): Timestamp indicating when the data was recorded. as_of (datetime): Timestamp indicating when the data was recorded.
Example: Example:
@@ -1419,6 +1539,7 @@ class FundInfoResponse(TypedDict):
timestamp, version, author, description, and status code. timestamp, version, author, description, and status code.
Example: Example:
>>> # ``fund`` is the ``FundInfo`` object from the example above.
>>> response: FundInfoResponse = { >>> response: FundInfoResponse = {
... "Data": {"IRFND123456": fund}, ... "Data": {"IRFND123456": fund},
... "Status": { ... "Status": {
@@ -1443,12 +1564,15 @@ class FundInfo_WS_symbolIsin(WebsocketBase_symbolIsin):
""" """
Websocket message structure for fund information updates identified by ISIN. Websocket message structure for fund information updates identified by ISIN.
The ``channel`` of these messages is ``"fund-info"``.
Attributes: Attributes:
data (FundInfo): Real-time fund information for the specified fund. data (FundInfo): Real-time fund information for the specified fund.
Example: Example:
>>> # ``fund`` is the ``FundInfo`` object from the example above.
>>> ws_data: FundInfo_WS_symbolIsin = { >>> ws_data: FundInfo_WS_symbolIsin = {
... "channel": "fund_info_updates", ... "channel": "fund-info",
... "symbolIsin": "IRFND123456", ... "symbolIsin": "IRFND123456",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": fund ... "data": fund
@@ -1463,12 +1587,15 @@ class FundInfo_WS_symbolName(WebsocketBase_symbolName):
""" """
Websocket message structure for fund information updates identified by symbol name. Websocket message structure for fund information updates identified by symbol name.
The ``channel`` of these messages is ``"fund-info"``.
Attributes: Attributes:
data (FundInfo): Real-time fund information for the specified fund. data (FundInfo): Real-time fund information for the specified fund.
Example: Example:
>>> # ``fund`` is the ``FundInfo`` object from the example above.
>>> ws_data: FundInfo_WS_symbolName = { >>> ws_data: FundInfo_WS_symbolName = {
... "channel": "fund_info_updates", ... "channel": "fund-info",
... "symbolName": "FND001", ... "symbolName": "FND001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": fund ... "data": fund
@@ -1485,6 +1612,9 @@ class OHLCV_live(TypedDict):
""" """
Represents live OHLCV (Open, High, Low, Close, Volume) data for a financial instrument. Represents live OHLCV (Open, High, Low, Close, Volume) data for a financial instrument.
The data covers the last 1-minute interval (see the ``ohlcv-last-1m`` channel and
``OHLCVLast1mResponse``). Prices are in IRR.
Attributes: Attributes:
open (float): Opening price of the instrument for the current interval. open (float): Opening price of the instrument for the current interval.
high (float): Highest price reached during the interval. high (float): Highest price reached during the interval.
@@ -1521,6 +1651,7 @@ class OHLCVLast1mResponse(TypedDict):
timestamp, version, author, description, and status code. timestamp, version, author, description, and status code.
Example: Example:
>>> # ``ohlcv`` is the ``OHLCV_live`` object from the example above.
>>> response: OHLCVLast1mResponse = { >>> response: OHLCVLast1mResponse = {
... "Data": {"IR0001234567": ohlcv}, ... "Data": {"IR0001234567": ohlcv},
... "Status": { ... "Status": {
@@ -1545,12 +1676,15 @@ class OHLCV_WS_symbolIsin(WebsocketBase_symbolIsin):
""" """
Websocket message structure for live OHLCV updates identified by ISIN. Websocket message structure for live OHLCV updates identified by ISIN.
The ``channel`` of these messages is ``"ohlcv-last-1m"``.
Attributes: Attributes:
data (OHLCV_live): Real-time OHLCV data for the specified instrument. data (OHLCV_live): Real-time OHLCV data for the specified instrument.
Example: Example:
>>> # ``ohlcv`` is the ``OHLCV_live`` object from the example above.
>>> ws_data: OHLCV_WS_symbolIsin = { >>> ws_data: OHLCV_WS_symbolIsin = {
... "channel": "ohlcv_updates", ... "channel": "ohlcv-last-1m",
... "symbolIsin": "IR0001234567", ... "symbolIsin": "IR0001234567",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": ohlcv ... "data": ohlcv
@@ -1565,12 +1699,15 @@ class OHLCV_WS_symbolName(WebsocketBase_symbolName):
""" """
Websocket message structure for live OHLCV updates identified by symbol name. Websocket message structure for live OHLCV updates identified by symbol name.
The ``channel`` of these messages is ``"ohlcv-last-1m"``.
Attributes: Attributes:
data (OHLCV_live): Real-time OHLCV data for the specified instrument. data (OHLCV_live): Real-time OHLCV data for the specified instrument.
Example: Example:
>>> # ``ohlcv`` is the ``OHLCV_live`` object from the example above.
>>> ws_data: OHLCV_WS_symbolName = { >>> ws_data: OHLCV_WS_symbolName = {
... "channel": "ohlcv_updates", ... "channel": "ohlcv-last-1m",
... "symbolName": "ETF001", ... "symbolName": "ETF001",
... "timestamp": "2025-11-19T10:30:00Z", ... "timestamp": "2025-11-19T10:30:00Z",
... "data": ohlcv ... "data": ohlcv
@@ -1592,12 +1729,14 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
Inherits from `SecuritiesAndFunds` and extends it with additional real-time and aggregated metrics. Inherits from `SecuritiesAndFunds` and extends it with additional real-time and aggregated metrics.
Attributes: Attributes:
BestLimit (Dict[str, BestLimitItem]): Best limit orders for this instrument by price level. BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
for this instrument by price level ("1" best ... "6" deepest).
Aggregate (Aggregate): Aggregated trading statistics for this instrument. Aggregate (Aggregate): Aggregated trading statistics for this instrument.
institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
between individual and institutional traders. between individual and institutional traders.
FundInfo (FundInfo): Net asset value, total units, and market capitalization. FundInfo (FundInfo): Net asset value, total units, and market capitalization
ContractInfo (ContractInfo): Derivatives contract data (if applicable). (intended for funds / ETFs).
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
Example: Example:
>>> overview: OverviewSecuritiesAndFunds = { >>> overview: OverviewSecuritiesAndFunds = {
@@ -1630,7 +1769,7 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
>>> overview["BestLimit"]["1"]["buy_price"] >>> overview["BestLimit"]["1"]["buy_price"]
12000 12000
>>> overview["Aggregate"]["high_price"] >>> overview["Aggregate"]["high_price"]
12150 12150.0
>>> overview["FundInfo"]["nav"] >>> overview["FundInfo"]["nav"]
12500.0 12500.0
""" """
@@ -1646,17 +1785,22 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
class OverviewTreasuryBonds(TreasuryBonds): class OverviewTreasuryBonds(TreasuryBonds):
""" """
Overview of a treasury bond instrument including best limit orders, aggregated market data, Overview of a treasury bond instrument: its static metadata (inherited from ``TreasuryBonds``) combined with
trading breakdown, fund info, and contract info. live market data in a single object.
Inherits from `TreasuryBonds` and extends it with additional metrics. Inherits from `TreasuryBonds` and extends it with additional real-time and aggregated metrics.
Attributes: Attributes:
BestLimit (Dict[str, BestLimitItem]) BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
Aggregate (Aggregate) by price level ("1" best ... "6" deepest).
institutional_vs_individual (institutional_vs_individual) Aggregate (Aggregate): Aggregated trading statistics.
FundInfo (FundInfo) institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
ContractInfo (ContractInfo) between individual and institutional traders.
FundInfo (FundInfo): Net asset value, total units, and market capitalization
(intended for funds / ETFs).
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
See ``OverviewSecuritiesAndFunds`` for a complete example.
""" """
BestLimit: Dict[ BestLimit: Dict[
Literal['1','2','3','4','5','6',], Literal['1','2','3','4','5','6',],
@@ -1670,17 +1814,22 @@ class OverviewTreasuryBonds(TreasuryBonds):
class OverviewStockOptions(StockOptions): class OverviewStockOptions(StockOptions):
""" """
Overview of a stock option instrument including best limit orders, aggregated market data, Overview of a stock option instrument: its static metadata (inherited from ``StockOptions``) combined with
trading breakdown, fund info, and contract info. live market data in a single object.
Inherits from `StockOptions` and extends it with additional metrics. Inherits from `StockOptions` and extends it with additional real-time and aggregated metrics.
Attributes: Attributes:
BestLimit (Dict[str, BestLimitItem]) BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
Aggregate (Aggregate) by price level ("1" best ... "6" deepest).
institutional_vs_individual (institutional_vs_individual) Aggregate (Aggregate): Aggregated trading statistics.
FundInfo (FundInfo) institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
ContractInfo (ContractInfo) between individual and institutional traders.
FundInfo (FundInfo): Net asset value, total units, and market capitalization
(intended for funds / ETFs).
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
See ``OverviewSecuritiesAndFunds`` for a complete example.
""" """
BestLimit: Dict[ BestLimit: Dict[
Literal['1','2','3','4','5','6',], Literal['1','2','3','4','5','6',],
@@ -1694,17 +1843,22 @@ class OverviewStockOptions(StockOptions):
class OverviewStockFuturess(StockFutures): class OverviewStockFuturess(StockFutures):
""" """
Overview of a stock futures instrument including best limit orders, aggregated market data, Overview of a stock futures instrument: its static metadata (inherited from ``StockFutures``) combined with
trading breakdown, fund info, and contract info. live market data in a single object.
Inherits from `StockFutures` and extends it with additional metrics. Inherits from `StockFutures` and extends it with additional real-time and aggregated metrics.
Attributes: Attributes:
BestLimit (Dict[str, BestLimitItem]) BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
Aggregate (Aggregate) by price level ("1" best ... "6" deepest).
institutional_vs_individual (institutional_vs_individual) Aggregate (Aggregate): Aggregated trading statistics.
FundInfo (FundInfo) institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
ContractInfo (ContractInfo) between individual and institutional traders.
FundInfo (FundInfo): Net asset value, total units, and market capitalization
(intended for funds / ETFs).
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
See ``OverviewSecuritiesAndFunds`` for a complete example.
""" """
BestLimit: Dict[ BestLimit: Dict[
Literal['1','2','3','4','5','6',], Literal['1','2','3','4','5','6',],
@@ -1720,6 +1874,10 @@ class OverviewResponse:
""" """
Response structure for the comprehensive overview of multiple financial instruments. Response structure for the comprehensive overview of multiple financial instruments.
The type of each entry can be recognized from its fields in the same way as for
``Instruments`` (``optionType`` -> options, ``firstMargin`` -> futures,
``baseVol`` -> bonds, ``baseVolume`` -> securities and funds).
Attributes: Attributes:
Data (Dict[str, Optional[Union[OverviewSecuritiesAndFunds, OverviewTreasuryBonds, Data (Dict[str, Optional[Union[OverviewSecuritiesAndFunds, OverviewTreasuryBonds,
OverviewStockOptions, OverviewStockFuturess]]]): Dictionary mapping instrument OverviewStockOptions, OverviewStockFuturess]]]): Dictionary mapping instrument
@@ -1729,6 +1887,7 @@ class OverviewResponse:
version, author, description, and status code. version, author, description, and status code.
Example: Example:
>>> # ``overview`` is the ``OverviewSecuritiesAndFunds`` object from the example above.
>>> overview_response: OverviewResponse = { >>> overview_response: OverviewResponse = {
... "Data": {"IR0001234567": overview}, ... "Data": {"IR0001234567": overview},
... "Status": { ... "Status": {
@@ -1766,8 +1925,12 @@ class OHLCV_historical(TypedDict):
Represents historical OHLCV (Open, High, Low, Close, Volume) data for a financial instrument Represents historical OHLCV (Open, High, Low, Close, Volume) data for a financial instrument
over multiple timestamps. over multiple timestamps.
Note:
All lists have the same length and are index-aligned: element ``i`` of every
list belongs to the same record. Prices are in IRR.
Attributes: Attributes:
Date_timestamp (List[int]): List of timestamps (in UNIX epoch format) for each OHLCV record. Date_timestamp (List[int]): List of timestamps (UNIX epoch, in seconds) for each OHLCV record.
Open (List[Union[float, int]]): Opening prices corresponding to each timestamp. Open (List[Union[float, int]]): Opening prices corresponding to each timestamp.
High (List[Union[float, int]]): Highest prices for each timestamp. High (List[Union[float, int]]): Highest prices for each timestamp.
Low (List[Union[float, int]]): Lowest prices for each timestamp. Low (List[Union[float, int]]): Lowest prices for each timestamp.
@@ -1807,12 +1970,17 @@ class OHLCVResponse(TypedDict):
""" """
Response structure for historical OHLCV data from a REST API call. Response structure for historical OHLCV data from a REST API call.
Note:
Unlike most other responses, ``Data`` is a single ``OHLCV_historical`` object for
the requested instrument, not a dictionary keyed by instrument identifier.
Attributes: Attributes:
Data (OHLCV_historical): Historical OHLCV data for the specified instrument. Data (OHLCV_historical): Historical OHLCV data for the specified instrument.
Status (Status): Metadata about the server response, including success state, timestamp, Status (Status): Metadata about the server response, including success state, timestamp,
version, author, description, and status code. version, author, description, and status code.
Example: Example:
>>> # ``ohlcv_hist`` is the ``OHLCV_historical`` object from the example above.
>>> response: OHLCVResponse = { >>> response: OHLCVResponse = {
... "Data": ohlcv_hist, ... "Data": ohlcv_hist,
... "Status": { ... "Status": {
@@ -1840,13 +2008,20 @@ class DividendAction(TypedDict):
""" """
Represents a dividend distribution action for a financial instrument. Represents a dividend distribution action for a financial instrument.
Note:
Some field names are in Persian. In a dict literal they are written as normal
string keys. Their values are strings as returned by the server, not numbers.
Attributes: Attributes:
Date_timestamp (int): Timestamp of the dividend action in UNIX epoch format. Date_timestamp (int): Timestamp of the dividend action in UNIX epoch format.
corporateAction (str): Type of corporate action (e.g., "Dividend"). corporateAction (str): Type of corporate action (e.g., "Dividend"). Use it to tell
``DividendAction`` and ``CapitalIncreaseAction`` apart.
symbolName (str): Symbol name of the instrument. symbolName (str): Symbol name of the instrument.
symbolIsin (str): ISIN identifier of the instrument. symbolIsin (str): ISIN identifier of the instrument.
سود_تقسیم_شده (Optional[str]): Distributed dividend amount (may be None if not available). سود_تقسیم_شده (Optional[str]): Distributed dividend ("سود تقسیم شده") as a string;
تاریخ (str): Human-readable date of the dividend action. None if not available.
تاریخ (str): Human-readable date ("تاریخ") of the dividend action, as a string
(format and calendar as provided by the server).
Example: Example:
>>> dividend: DividendAction = { >>> dividend: DividendAction = {
@@ -1872,15 +2047,24 @@ class CapitalIncreaseAction(TypedDict):
""" """
Represents a capital increase action for a financial instrument. Represents a capital increase action for a financial instrument.
Note:
Some field names are in Persian. In a dict literal they are written as normal
string keys. Their values are strings as returned by the server, not numbers.
Attributes: Attributes:
Date_timestamp (int): Timestamp of the capital increase action in UNIX epoch format. Date_timestamp (int): Timestamp of the capital increase action in UNIX epoch format.
corporateAction (str): Type of corporate action (e.g., "Capital Increase"). corporateAction (str): Type of corporate action (e.g., "Capital Increase"). Use it to
tell ``DividendAction`` and ``CapitalIncreaseAction`` apart.
symbolName (str): Symbol name of the instrument. symbolName (str): Symbol name of the instrument.
symbolIsin (str): ISIN identifier of the instrument. symbolIsin (str): ISIN identifier of the instrument.
سرمایه_قبلی (Optional[str]): Previous capital amount (may be None if not available). سرمایه_قبلی (Optional[str]): Previous capital ("سرمایه قبلی") as a string; None if
سرمایه_جدید (Optional[str]): New capital amount after increase (may be None if not available). not available.
درصد_افزایش (Optional[str]): Percentage of capital increase (may be None if not available). سرمایه_جدید (Optional[str]): New capital after the increase ("سرمایه جدید") as a
تاریخ (str): Human-readable date of the capital increase action. string; None if not available.
درصد_افزایش (Optional[str]): Percentage of the capital increase ("درصد افزایش") as a
string (it may include a "%" sign); None if not available.
تاریخ (str): Human-readable date ("تاریخ") of the capital increase action, as a string
(format and calendar as provided by the server).
Example: Example:
>>> capital_inc: CapitalIncreaseAction = { >>> capital_inc: CapitalIncreaseAction = {
@@ -1914,10 +2098,12 @@ class CorporateActionResponse(TypedDict):
Attributes: Attributes:
Data (List[Union[DividendAction, CapitalIncreaseAction, None]]): List of corporate action records. Data (List[Union[DividendAction, CapitalIncreaseAction, None]]): List of corporate action records.
Each item may represent a dividend action, a capital increase action, or None if unavailable. Each item may represent a dividend action, a capital increase action, or None if unavailable.
Use ``corporateAction`` to tell them apart.
Status (Status): Metadata about the server response, including success state, timestamp, Status (Status): Metadata about the server response, including success state, timestamp,
version, author, description, and status code. version, author, description, and status code.
Example: Example:
>>> # ``dividend`` and ``capital_inc`` are the objects from the examples above.
>>> response: CorporateActionResponse = { >>> response: CorporateActionResponse = {
... "Data": [dividend, capital_inc, None], ... "Data": [dividend, capital_inc, None],
... "Status": { ... "Status": {
+855
View File
@@ -0,0 +1,855 @@
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from typing import (
Literal,
)
from .__io_types import (
HexUUID,
OrderStatus,
)
from HedgeTech.Auth import AuthAsyncClient
from PIL.Image import open as image_open
from PIL.ImageFile import ImageFile
from io import BytesIO
from asyncio import sleep
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,
*,
SendOrder_RequestInfo : dict,
AuthASyncClient : AuthAsyncClient,
ContractNameOrId : str | int ,
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
self.ContractNameOrId : str = ContractNameOrId
self.Price : int = Price
self.Volume : int = Volume
self.is_deleted : bool = False
self.OrderStatus : Literal[
'Unknown',
'InQueue',
'PartiallyFilled',
'Cancelled',
'Broken',
'Settled',
] = 'Unknown'
self.OrderId : HexUUID | None = None
self.OrderOmsId : str | None = None
# +--------------------------------------------------------------------------------------+ #
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 :
if self.OrderId is None :
SendOrder_Response = await self.__AuthASyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
match SendOrder_Response.status_code :
case 200 :
data = SendOrder_Response.json()
self.OrderId = data['Data']['order_uuid']
self.OrderOmsId = data['Data']['order_oms_id']
return None
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
async def Edit(
self,
*,
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 :
if self.OrderId is not None:
Edit_response = await self.__AuthASyncClient.httpx_Client.patch(
url='https://core.hedgetech.ir/ems-engine/ime/order/edit',
data={
'order_uuid' : self.OrderId,
'Price' : Price,
'Volume' : Volume
}
)
match Edit_response.status_code:
case 200:
Edit_response = Edit_response.json()
self.ValidityType = Edit_response['Data']['order_validity_type']
self.Price = Edit_response['Data']['order_price']
self.Volume = Edit_response['Data']['order_volume']
return None
case _ :
status_respnse = await self.Status()
if status_respnse and (
status_respnse['order_status'] in ('PartiallyFilled' , 'InQueue')
and status_respnse['Volume'] == Volume
and status_respnse['Price'] == Price
):
self.Price = status_respnse['Price']
self.Volume = status_respnse['Volume']
self.OrderStatus = status_respnse['order_status']
return None
elif status_respnse and status_respnse['order_status'] not in ('PartiallyFilled' , 'InQueue'):
self.OrderStatus = status_respnse['order_status']
return None
else : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
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 :
if self.OrderId is not None:
status_respnse = await self.__AuthASyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/ems-engine/ime/order/status',
params={'order_uuid' : self.OrderId}
)
match status_respnse.status_code :
case 200:
status_respnse = status_respnse.json()['Data']
self.OrderStatus = status_respnse['order_status']
return status_respnse
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
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 :
if self.OrderId is not None:
Delete_respnse = await self.__AuthASyncClient.httpx_Client.delete(
url= 'https://core.hedgetech.ir/ems-engine/ime/order/delete',
params={'order_uuid' : self.OrderId}
)
match Delete_respnse.status_code :
case 200:
self.is_deleted = True
self.OrderStatus = 'Cancelled'
return None
case _ :
status_respnse = await self.Status()
if status_respnse and status_respnse['order_status'] == 'Cancelled':
self.is_deleted = True
self.OrderStatus = 'Cancelled'
return None
elif status_respnse and status_respnse['order_status'] != 'Cancelled' :
self.OrderStatus = status_respnse['order_status']
return None
else : return None
else : return None
except : return None
# ================================================================================= #
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
self.Customer_FullName : str | None = None
self.Customer_IMEBourseCode : str | None = None
self.oms_session : HexUUID | None = None
# +--------------------------------------------------------------------------------------+ #
async def Get_Captcha(
self,
OMS : Literal[
'Sahra | Karamad',
'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',
params={'oms' : OMS }
)
if Captcha.status_code == 200: return image_open(BytesIO(Captcha.content))
else : raise ValueError(Captcha.json()['detail']['Status']['Description']['en'])
# +--------------------------------------------------------------------------------------+ #
async def oms_login(
self,
*,
username: str,
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(
url='https://core.hedgetech.ir/ems-engine/ime/oms/login',
data={
'username' : username,
'Password' : password,
'Captcha_Value' : captcha_value
},
)
match response.status_code :
case 200 :
data = response.json()
self.Customer_FullName = data['Data']['Customer_FullName']
self.Customer_IMEBourseCode = data['Data']['Customer_IMEBourseCode']
self.oms_session = data['Data']['oms_session']
return None
case 400 :
raise ValueError(response.json()['detail']['Status']['Description']['en'])
case _ :
raise ValueError(response.text)
# +--------------------------------------------------------------------------------------+ #
async def Buy_by_ContractName(
self,
*,
contractName : str,
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)
if self.oms_session is not None:
return Order(
AuthASyncClient=self.__AuthASyncClient,
ContractNameOrId = contractName,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/buy/contract/name',
'data' : {
'oms_session' : self.oms_session,
'contractName' : contractName,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
# +--------------------------------------------------------------------------------------+ #
async def Sell_by_ContractName(
self,
*,
contractName : str,
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)
if self.oms_session is not None:
return Order(
AuthASyncClient=self.__AuthASyncClient,
ContractNameOrId = contractName,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/sell/contract/name',
'data' : {
'oms_session' : self.oms_session,
'contractName' : contractName,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
# +--------------------------------------------------------------------------------------+ #
async def Buy_by_ContractId(
self,
*,
contractId : int | str,
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)
if self.oms_session is not None:
return Order(
AuthASyncClient=self.__AuthASyncClient,
ContractNameOrId = contractId,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/buy/contract/id',
'data' : {
'oms_session' : self.oms_session,
'contractId' : contractId,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
# +--------------------------------------------------------------------------------------+ #
async def Sell_by_ContractId(
self,
*,
contractId : int | str,
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)
if self.oms_session is not None:
return Order(
AuthASyncClient=self.__AuthASyncClient,
ContractNameOrId = contractId,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/sell/contract/id',
'data' : {
'oms_session' : self.oms_session,
'contractId' : contractId,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
+846
View File
@@ -0,0 +1,846 @@
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from typing import (
Literal,
)
from .__io_types import (
HexUUID,
OrderStatus,
)
from HedgeTech.Auth import AuthSyncClient
from PIL.Image import open as image_open
from PIL.ImageFile import ImageFile
from io import BytesIO
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,
*,
SendOrder_RequestInfo : dict,
AuthSyncClient : AuthSyncClient,
ContractNameOrId : str | int ,
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
self.ContractNameOrId : str = ContractNameOrId
self.Price : int = Price
self.Volume : int = Volume
self.is_deleted : bool = False
self.OrderStatus : Literal[
'Unknown',
'InQueue',
'PartiallyFilled',
'Cancelled',
'Broken',
'Settled',
] = 'Unknown'
self.OrderId : HexUUID | None = None
self.OrderOmsId : str | None = None
# +--------------------------------------------------------------------------------------+ #
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 :
if self.OrderId is None :
SendOrder_Response = self.__AuthSyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
match SendOrder_Response.status_code :
case 200 :
data = SendOrder_Response.json()
self.OrderId = data['Data']['order_uuid']
self.OrderOmsId = data['Data']['order_oms_id']
return None
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
def Edit(
self,
*,
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 :
if self.OrderId is not None:
Edit_response = self.__AuthSyncClient.httpx_Client.patch(
url='https://core.hedgetech.ir/ems-engine/ime/order/edit',
data={
'order_uuid' : self.OrderId,
'Price' : Price,
'Volume' : Volume
}
)
match Edit_response.status_code:
case 200:
Edit_response = Edit_response.json()
self.ValidityType = Edit_response['Data']['order_validity_type']
self.Price = Edit_response['Data']['order_price']
self.Volume = Edit_response['Data']['order_volume']
return None
case _ :
status_respnse = self.Status()
if status_respnse and (
status_respnse['order_status'] in ('PartiallyFilled' , 'InQueue')
and status_respnse['Volume'] == Volume
and status_respnse['Price'] == Price
):
self.Price = status_respnse['Price']
self.Volume = status_respnse['Volume']
self.OrderStatus = status_respnse['order_status']
return None
elif status_respnse and status_respnse['order_status'] not in ('PartiallyFilled' , 'InQueue'):
self.OrderStatus = status_respnse['order_status']
return None
else : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
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 :
if self.OrderId is not None:
status_respnse = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/ems-engine/ime/order/status',
params={'order_uuid' : self.OrderId}
)
match status_respnse.status_code :
case 200:
status_respnse = status_respnse.json()['Data']
self.OrderStatus = status_respnse['order_status']
return status_respnse
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
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 :
if self.OrderId is not None:
Delete_respnse = self.__AuthSyncClient.httpx_Client.delete(
url= 'https://core.hedgetech.ir/ems-engine/ime/order/delete',
params={'order_uuid' : self.OrderId}
)
match Delete_respnse.status_code :
case 200:
self.is_deleted = True
self.OrderStatus = 'Cancelled'
return None
case _ :
status_respnse = self.Status()
if status_respnse and status_respnse['order_status'] == 'Cancelled':
self.is_deleted = True
self.OrderStatus = 'Cancelled'
return None
elif status_respnse and status_respnse['order_status'] != 'Cancelled' :
self.OrderStatus = status_respnse['order_status']
return None
else : return None
else : return None
except : return None
# ================================================================================= #
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
self.Customer_FullName : str | None = None
self.Customer_IMEBourseCode : str | None = None
self.oms_session : HexUUID | None = None
# +--------------------------------------------------------------------------------------+ #
def Get_Captcha(
self,
OMS : Literal[
'Sahra | Karamad',
'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',
params={'oms' : OMS }
)
if Captcha.status_code == 200: return image_open(BytesIO(Captcha.content))
else : raise ValueError(Captcha.json()['detail']['Status']['Description']['en'])
# +--------------------------------------------------------------------------------------+ #
def oms_login(
self,
*,
username: str,
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(
url='https://core.hedgetech.ir/ems-engine/ime/oms/login',
data={
'username' : username,
'Password' : password,
'Captcha_Value' : captcha_value
},
)
match response.status_code :
case 200 :
data = response.json()
self.Customer_FullName = data['Data']['Customer_FullName']
self.Customer_IMEBourseCode = data['Data']['Customer_IMEBourseCode']
self.oms_session = data['Data']['oms_session']
return None
case 400 :
raise ValueError(response.json()['detail']['Status']['Description']['en'])
case _ :
raise ValueError(response.text)
# +--------------------------------------------------------------------------------------+ #
def Buy_by_ContractName(
self,
*,
contractName : str,
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:
return Order(
AuthSyncClient=self.__AuthSyncClient,
ContractNameOrId = contractName,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/buy/contract/name',
'data' : {
'oms_session' : self.oms_session,
'contractName' : contractName,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
# +--------------------------------------------------------------------------------------+ #
def Sell_by_ContractName(
self,
*,
contractName : str,
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:
return Order(
AuthSyncClient=self.__AuthSyncClient,
ContractNameOrId = contractName,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/sell/contract/name',
'data' : {
'oms_session' : self.oms_session,
'contractName' : contractName,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
# +--------------------------------------------------------------------------------------+ #
def Buy_by_ContractId(
self,
*,
contractId : int | str,
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:
return Order(
AuthSyncClient=self.__AuthSyncClient,
ContractNameOrId = contractId,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/buy/contract/id',
'data' : {
'oms_session' : self.oms_session,
'contractId' : contractId,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
# +--------------------------------------------------------------------------------------+ #
def Sell_by_ContractId(
self,
*,
contractId : int | str,
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:
return Order(
AuthSyncClient=self.__AuthSyncClient,
ContractNameOrId = contractId,
Price=Price,
Volume=Volume,
SendOrder_RequestInfo = {
'url' : 'https://core.hedgetech.ir/ems-engine/ime/order/new/sell/contract/id',
'data' : {
'oms_session' : self.oms_session,
'contractId' : contractId,
'Price' : Price,
'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
}
}
)
else : return None
+2
View File
@@ -0,0 +1,2 @@
from .__SyncClient import EmsEngine_Ime_SyncClient
from .__AsyncClient import EmsEngine_Ime_AsyncClient
@@ -0,0 +1,4 @@
from .__response import (
OrderStatus,
HexUUID,
)
@@ -0,0 +1,72 @@
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from typing import (
NewType,
TypedDict,
Literal,
)
# ========================================|======================================== #
# Class Definitions #
# ========================================|======================================== #
HexUUID = NewType("HexUUID", str)
# +--------------------------------------------------------------------------------------+ #
class OrderStatus(TypedDict):
"""
Represents the current status and execution details of an order.
Attributes:
order_uuid (HexUUID): Unique identifier of the order.
order_status (Literal['InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled', 'Unknown']):
Current lifecycle status of the order.
Possible values:
- ``InQueue``: The order has been accepted and is waiting to be matched.
- ``PartiallyFilled``: Part of the order has been executed, while the remaining volume is still active.
- ``Cancelled``: The order has been cancelled and will no longer be executed.
- ``Broken``: The order has been rejected or terminated due to an error or exchange-side condition.
- ``Settled``: The order has been completely executed.
- ``Unknown``: The order status is unknown or could not be determined.
``InQueue`` and ``PartiallyFilled`` are active states (the order can still
be executed or cancelled). ``Cancelled``, ``Broken`` and ``Settled`` are
final states.
Price (int): Order price, in IRR.
Volume (int): Total requested order volume.
ExecutedVolume (int): Total executed volume so far. The remaining volume is
``Volume - ExecutedVolume``.
OrderSide (Literal['Buy', 'Sell']): Side of the order.
Possible values:
- ``Buy``: Buy order.
- ``Sell``: Sell order.
Example:
>>> status: OrderStatus = {
... "order_uuid": "3f2b8c1e9a4d4e6f8b7a1c2d3e4f5a6b",
... "order_status": "PartiallyFilled",
... "Price": 35200,
... "Volume": 100,
... "ExecutedVolume": 40,
... "OrderSide": "Buy"
... }
>>> status['Volume'] - status['ExecutedVolume']
60
>>> status['order_status'] in ('InQueue', 'PartiallyFilled')
True
"""
order_uuid : HexUUID
order_status : Literal['InQueue','PartiallyFilled','Cancelled','Broken','Settled','Unknown']
Price : int
Volume : int
ExecutedVolume : int
OrderSide : Literal['Buy','Sell']
+4
View File
@@ -2,3 +2,7 @@ from .__tse_ifb import (
EmsEngine_TseIfb_SyncClient, EmsEngine_TseIfb_SyncClient,
EmsEngine_TseIfb_AsyncClient EmsEngine_TseIfb_AsyncClient
) )
from .__ime import (
EmsEngine_Ime_AsyncClient,
EmsEngine_Ime_SyncClient
)
+393 -270
View File
@@ -14,6 +14,7 @@ from PIL.Image import open as image_open
from PIL.ImageFile import ImageFile from PIL.ImageFile import ImageFile
from io import BytesIO from io import BytesIO
from asyncio import sleep from asyncio import sleep
from uuid import uuid4
# ========================================|======================================== # # ========================================|======================================== #
# Class Definitions # # Class Definitions #
@@ -26,8 +27,54 @@ class Order:
This class provides methods to send, edit, check status, This class provides methods to send, edit, check status,
and delete an order after creation. and delete an order after creation.
An Order instance is usually created via An Order instance is usually created via the ``Buy_by_Name``, ``Sell_by_Name``,
`EmsEngine_TseIfb_AsyncClient` methods. ``Buy_by_isin`` and ``Sell_by_isin`` methods of `EmsEngine_TseIfb_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_Name(...)``: 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`` without changing the order (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:
ValidityType (str): Validity type of the order: ``'DAY'`` (valid only for the current
trading session), ``'GTC'`` (Good Till Cancelled) or ``'GTD'`` (Good Till Date, valid
until ``ValidityDate``). ``'FAK'`` and ``'FOK'`` appear only in the type hint of
``Edit``. Updated by ``Edit``.
ValidityDate (int): Expiration date of the order. Only meaningful for ``'GTD'``; ``0``
otherwise. The format is the one expected by the server (the examples use YYYYMMDD,
e.g. ``20271206``).
SymbolNameOrIsin (str): Symbol name or ISIN code of the security, 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``.
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_Name(symbolName="اطلس", Price=100000, Volume=10)
>>> if order is not None:
... await order.send()
... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
""" """
def __init__( def __init__(
@@ -42,47 +89,33 @@ class Order:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
): ):
""" """
Represents a stock order in the EMS Engine for TSE IFB. Create an Order object. Nothing is sent to the exchange.
This class allows sending, editing, deleting, and checking the status All arguments are keyword-only. You normally do not call this directly: the ``Buy_*`` /
of a stock order using an asynchronous client. ``Sell_*`` methods of ``EmsEngine_TseIfb_AsyncClient`` build the order and its request for you.
Attributes Args:
---------- SendOrder_RequestInfo (dict): Keyword arguments for the ``httpx_Client.post`` call that
ValidityType : str submits the order, prepared by the client: ``{'url': <new-order endpoint>, 'data':
Type of order validity ('DAY', 'GTC', 'GTD', 'FAK', 'FOK'). {oms_session, Order_ValidityType, ValidityDate, symbolName | symbolIsin, Price, Volume,
ValidityDate : int InitialOrderId}}``. What is actually sent by ``send`` is this dictionary; ``Price`` and
Expiration date of the order (for 'GTD' type). ``Volume`` below are only stored on the object for reference. ``InitialOrderId`` is a
SymbolNameOrIsin : str random hex id generated once when the order is created and reused if ``send`` is called
Symbol name or ISIN code of the security. again.
Price : int AuthASyncClient (AuthAsyncClient): Authenticated client used for all the requests of this
Order price. order.
Volume : int SymbolNameOrIsin (str): Symbol name or ISIN code of the security.
Order volume. Price (int): Order price, in IRR.
is_deleted : bool Volume (int): Total order volume.
True if the order has been deleted. Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to
OrderId : HexUUID | None ``'DAY'``. Stored as the ``ValidityType`` attribute.
Unique identifier of the order after submission. ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
OrderStatus : 'Unknown' | 'InQueue' | 'PartiallyFilled' | 'Cancelled' | 'Broken' | 'Settled' ``0``.
Current lifecycle status of the order. The value is 'Unknown' until a status is received from the server.
Methods
-------
send()
Sends the order asynchronously to the EMS engine.
Edit(Order_ValidityType, ValidityDate, Price, Volume)
Edits the existing order asynchronously.
Status()
Retrieves the current status of the order asynchronously.
Delete()
Deletes the order asynchronously.
""" """
@@ -105,6 +138,7 @@ class Order:
] = 'Unknown' ] = 'Unknown'
self.OrderId : HexUUID | None = None self.OrderId : HexUUID | None = None
self.OrderOmsId : str | None = None
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
@@ -113,19 +147,30 @@ class Order:
""" """
Sends the order to the EMS engine asynchronously. Sends the order to the EMS engine asynchronously.
If the order has not been sent before, it posts the request Posts ``SendOrder_RequestInfo`` through ``httpx_Client.post``, but only if the order has not
using the provided AuthAsyncClient. been sent yet (``OrderId is None``). If ``OrderId`` is already set nothing happens, so calling
``send()`` again never submits the same ``Order`` object twice.
Returns 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
None not changed; call ``Status()`` to get it.
Example 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:
If a failed ``send()`` is tried 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_Name(symbolName="اطلس", Price=100000, Volume=10) >>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
>>> await order.send() >>> await order.send()
>>> print(order.OrderId) >>> if order.OrderId is not None:
'953097ac6ced45ca8ef205b76ca6faf2' ... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
""" """
try : try :
@@ -138,7 +183,9 @@ class Order:
case 200 : case 200 :
self.OrderId = SendOrder_Response.json()['Data']['order_uuid'] data = SendOrder_Response.json()
self.OrderId = data['Data']['order_uuid']
self.OrderOmsId = data['Data']['order_oms_id']
return None return None
case _ : return None case _ : return None
@@ -166,29 +213,49 @@ class Order:
""" """
Edits an existing order asynchronously. Edits an existing order asynchronously.
Parameters Sends ``PATCH https://core.hedgetech.ir/ems-engine/tse-ifb/order/edit`` (form data:
---------- ``order_uuid``, ``Order_ValidityType``, ``ValidityDate``, ``Price``, ``Volume``). Nothing happens
Order_ValidityType : str if the order has not been sent yet (``OrderId is None``). All arguments are keyword-only and all
The new order validity type. of them are always sent: pass the current value of whatever you do not want to change (note that
ValidityDate : int ``Order_ValidityType`` defaults to ``'DAY'``, so an edit without it turns a GTC/GTD order into a
New expiration date if validity type is 'GTD'. DAY order).
Price : int
New order price.
Volume : int
New order volume.
Returns How the result is applied:
------- * Status ``200``: ``ValidityType``, ``Price`` and ``Volume`` are updated from the server's
None reply (``order_validity_type``, ``order_price``, ``order_volume``) and ``ValidityDate``
from the ``ValidityDate`` argument.
* 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 values (``Price``, ``ValidityType``, ``ValidityDate`` and
``ExecutedVolume + RemainedVolume == Volume``), the edit is considered applied and the
attributes are updated. If the order is no longer active (``Cancelled``, ``Broken`` or
``Settled``), only ``OrderStatus`` is updated. Otherwise nothing changes.
Example 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 ``ExecutedVolume + RemainedVolume``), it is not the
remaining volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD', 'FAK', 'FOK']): The new order validity type.
Defaults to ``'DAY'``. ``'FAK'`` (Fill And Kill) and ``'FOK'`` (Fill Or Kill) are listed
only here; the order creation methods accept ``'DAY'``, ``'GTC'`` and ``'GTD'``.
ValidityDate (int): New expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Returns:
None: Always. Errors are swallowed. Compare ``Price``, ``Volume``, ``ValidityType`` and
``ValidityDate`` with what you requested (or call ``Status()``) to know whether the edit
was applied.
Example:
>>> await order.Edit( >>> await order.Edit(
Price = 105, ... Price=105,
Volume = 15, ... Volume=15,
Order_ValidityType = 'GTD', ... Order_ValidityType='GTD',
ValidityDate = 20271206 ... ValidityDate=20271206,
) ... )
>>> order.Price, order.Volume
(105, 15)
""" """
try : try :
@@ -213,7 +280,6 @@ class Order:
Edit_response = Edit_response.json() Edit_response = Edit_response.json()
self.OrderId = Edit_response['Data']['order_uuid']
self.ValidityType = Edit_response['Data']['order_validity_type'] self.ValidityType = Edit_response['Data']['order_validity_type']
self.ValidityDate = ValidityDate self.ValidityDate = ValidityDate
self.Price = Edit_response['Data']['order_price'] self.Price = Edit_response['Data']['order_price']
@@ -258,22 +324,29 @@ class Order:
""" """
Retrieves the current status of the order asynchronously. Retrieves the current status of the order asynchronously.
Returns Sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/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
OrderStatus | None successful call updates ``self.OrderStatus`` from the response (the other attributes, such as
A dictionary containing the current order status with the following keys: ``Price`` and ``Volume``, are not touched).
- order_uuid: HexUUID, unique identifier of the order.
- order_status: 'InQueue' | 'PartiallyFilled' | 'Cancelled' | 'Broken' | 'Settled'
- Price: int, the order price.
- Volume: int, the original order volume.
- RemainedVolume: int, volume remaining unexecuted.
- ExecutedVolume: int, executed volume.
- OrderSide: 'Buy' | 'Sell', the order side.
- ValidityType: 'DAY' | 'GTC' | 'GTD', the type of order validity.
- ValidityDate: int, expiration date if applicable.
Example Returns:
------- OrderStatus | None: The ``Data`` part of the server's reply when the HTTP status is ``200``,
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() >>> status = await order.Status()
>>> print(status) >>> print(status)
{ {
@@ -287,6 +360,8 @@ class Order:
'ValidityType': 'DAY', 'ValidityType': 'DAY',
'ValidityDate': 0 'ValidityDate': 0
} }
>>> order.OrderStatus
'InQueue'
""" """
try : try :
@@ -317,16 +392,25 @@ class Order:
async def Delete(self)-> None: async def Delete(self)-> None:
""" """
Deletes the order asynchronously. Deletes (cancels) the order asynchronously.
Sets `is_deleted` to True if successful. Sends ``DELETE https://core.hedgetech.ir/ems-engine/tse-ifb/order/delete`` with the
``order_uuid``. Nothing is sent if the order has not been sent yet (``OrderId is None``).
Returns How the result is applied:
------- * Status ``200``: ``is_deleted`` is set to ``True`` and ``OrderStatus`` to ``'Cancelled'``.
None * 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.
Example ``OrderId`` is kept after deletion.
-------
Returns:
None: Always. Errors are swallowed. Check ``is_deleted`` (and ``OrderStatus``) to know the
outcome.
Example:
>>> await order.Delete() >>> await order.Delete()
>>> print(order.is_deleted) >>> print(order.is_deleted)
True True
@@ -378,6 +462,36 @@ class EmsEngine_TseIfb_AsyncClient:
This client manages authentication, OMS login, This client manages authentication, OMS login,
and order creation. 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_Name(...)`` (or ``Sell_by_Name``, ``Buy_by_isin``,
``Sell_by_isin``): 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_TSEBourseCode (str | None): TSE 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_TseIfb_AsyncClient(AuthASyncClient=auth_client)
>>> captcha = await client.Get_Captcha('Omex | Parsian')
>>> captcha.show()
>>> await client.oms_login(
... username="user123",
... password="pass123",
... captcha_value="abcd",
... )
>>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
>>> await order.send()
>>> print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
""" """
def __init__( def __init__(
@@ -386,39 +500,15 @@ class EmsEngine_TseIfb_AsyncClient:
): ):
""" """
Asynchronous client for interacting with the EMS Engine (TSE IFB). Create the EMS Engine client. Nothing is sent to the server.
Provides methods for logging in, retrieving CAPTCHA, and creating buy/sell orders Provides methods for logging in (CAPTCHA + OMS login) and for creating buy/sell orders
by symbol name or ISIN. by symbol name or ISIN. See the class docstring for the workflow.
Attributes Args:
---------- AuthASyncClient (AuthAsyncClient): An already authenticated ``AuthAsyncClient``. Its
Customer_FullName : str | None ``httpx_Client`` is used for every request (it also keeps the cookies of the CAPTCHA /
Full name of the logged-in customer. OMS login session, so use the same client for ``Get_Captcha`` and ``oms_login``).
Customer_TSEBourseCode : str | None
TSE bourse code of the customer.
oms_session : HexUUID | None
Session token obtained after login.
Methods
-------
Get_Captcha(OMS)
Retrieves the login CAPTCHA image asynchronously.
oms_login(username, password, captcha_value)
Logs into the OMS asynchronously.
Buy_by_Name(Order_ValidityType, ValidityDate, symbolName, Price, Volume)
Creates a new buy order by symbol name asynchronously.
Sell_by_Name(Order_ValidityType, ValidityDate, symbolName, Price, Volume)
Creates a new sell order by symbol name asynchronously.
Buy_by_isin(Order_ValidityType, ValidityDate, symbolIsin, Price, Volume)
Creates a new buy order by ISIN asynchronously.
Sell_by_isin(Order_ValidityType, ValidityDate, symbolIsin, Price, Volume)
Creates a new sell order by ISIN asynchronously.
""" """
self.__AuthASyncClient = AuthASyncClient self.__AuthASyncClient = AuthASyncClient
@@ -434,31 +524,34 @@ class EmsEngine_TseIfb_AsyncClient:
self, self,
OMS : Literal[ OMS : Literal[
'Omex | Parsian', 'Omex | Parsian',
'Omex | Khobregan',
'Sahra | Karamad', 'Sahra | Karamad',
'Sahra | NIBB', 'Sahra | NIBB',
'Sahra | Charisma',
] ]
)-> ImageFile: )-> ImageFile:
""" """
Retrieves the CAPTCHA image for the specified OMS asynchronously. Retrieves the CAPTCHA image for the specified OMS asynchronously.
Parameters Sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` with the ``oms`` parameter.
---------- The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
OMS : str established by this call: call it with the same client right after ``Get_Captcha``.
OMS identifier ('Omex | Parsian' or 'Sahra | Karamad').
Returns Args:
------- OMS (Literal['Omex | Parsian', 'Omex | Khobregan', 'Sahra | Karamad', 'Sahra | NIBB', 'Sahra | Charisma']):
ImageFile The OMS (broker system) to log into. The format is ``'<provider> | <broker>'``.
The CAPTCHA image object.
Raises Returns:
------ ImageFile: The CAPTCHA image (a ``PIL`` image opened from the response bytes). Show or save it
ValueError and pass the value you read to ``oms_login``.
If the request fails or returns an error.
Example 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('Omex | Parsian') >>> captcha = await client.Get_Captcha('Omex | Parsian')
>>> captcha.show() >>> captcha.show()
""" """
@@ -486,33 +579,36 @@ class EmsEngine_TseIfb_AsyncClient:
""" """
Logs into the OMS asynchronously with provided credentials and CAPTCHA. Logs into the OMS asynchronously with provided credentials and CAPTCHA.
Parameters Sends ``POST https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` (form data: ``username``,
---------- ``Password``, ``Captcha_Value``). Call ``Get_Captcha`` first, with the same client. All arguments
username : str are keyword-only.
OMS username.
password : str
OMS password.
captcha_value : str
Solved CAPTCHA value.
Returns On success (HTTP ``200``) ``Customer_FullName``, ``Customer_TSEBourseCode`` 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 None
Raises Raises:
------ ValueError: If the login fails. For HTTP ``400`` (for example a wrong CAPTCHA or wrong
ValueError credentials) the message is the server's ``detail.Status.Description.en``; for any other
If login fails or CAPTCHA is invalid. non-``200`` status it is the raw response text.
Example Example:
-------
>>> await client.oms_login( >>> await client.oms_login(
username = "user123", ... username="user123",
password = "pass123", ... password="pass123",
captcha_value = "abcd" ... captcha_value="abcd",
) ... )
>>> print(client.oms_session) >>> print(client.oms_session)
'session_token_here' 953097ac6ced45ca8ef205b76ca6faf2
""" """
response = await self.__AuthASyncClient.httpx_Client.post( response = await self.__AuthASyncClient.httpx_Client.post(
@@ -557,8 +653,6 @@ class EmsEngine_TseIfb_AsyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
@@ -566,34 +660,42 @@ class EmsEngine_TseIfb_AsyncClient:
""" """
Creates a new buy order by symbol name asynchronously. Creates a new buy order by symbol name asynchronously.
Parameters 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;
Order_ValidityType : str check the limits yourself if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Order validity type. ``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
ValidityDate : int
Expiration date if validity type is 'GTD'.
symbolName : str
Symbol name of the security.
Price : int
Order price.
Volume : int
Order volume.
Returns 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
Order | None this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
A new Order instance if OMS session exists, else None. order's request.
Example All arguments are keyword-only.
-------
Args:
symbolName (str): Symbol name of the security (e.g., "اطلس").
Price (int): Order price, in IRR.
Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Buy_by_Name( >>> order = await client.Buy_by_Name(
symbolName="اطلس", ... symbolName="اطلس",
Price=100000, ... Price=100000,
Volume=10, ... Volume=10,
Order_ValidityType = 'DAY', ... Order_ValidityType='DAY',
ValidityDate = 0 ... ValidityDate=0,
) ... )
>>> await order.send() >>> if order is not None:
... await order.send()
""" """
await sleep(0) await sleep(0)
@@ -615,7 +717,8 @@ class EmsEngine_TseIfb_AsyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolName' : symbolName, 'symbolName' : symbolName,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -635,8 +738,6 @@ class EmsEngine_TseIfb_AsyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
@@ -644,34 +745,42 @@ class EmsEngine_TseIfb_AsyncClient:
""" """
Creates a new sell order by symbol name asynchronously. Creates a new sell order by symbol name asynchronously.
Parameters 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;
Order_ValidityType : str check the limits yourself if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Order validity type. ``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
ValidityDate : int
Expiration date if validity type is 'GTD'.
symbolName : str
Symbol name of the security.
Price : int
Order price.
Volume : int
Order volume.
Returns 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
Order | None this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
A new Order instance if OMS session exists, else None. order's request.
Example All arguments are keyword-only.
-------
Args:
symbolName (str): Symbol name of the security (e.g., "اطلس").
Price (int): Order price, in IRR.
Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Sell_by_Name( >>> order = await client.Sell_by_Name(
symbolName="اطلس", ... symbolName="اطلس",
Price=100000, ... Price=100000,
Volume=10, ... Volume=10,
Order_ValidityType = 'DAY', ... Order_ValidityType='DAY',
ValidityDate = 0 ... ValidityDate=0,
) ... )
>>> await order.send() >>> if order is not None:
... await order.send()
""" """
await sleep(0) await sleep(0)
@@ -693,7 +802,8 @@ class EmsEngine_TseIfb_AsyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolName' : symbolName, 'symbolName' : symbolName,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -712,43 +822,49 @@ class EmsEngine_TseIfb_AsyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
""" """
Creates a new buy order by symbol isin asynchronously. Creates a new buy order by ISIN code asynchronously.
Parameters 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;
Order_ValidityType : str check the limits yourself if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Order validity type. ``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
ValidityDate : int
Expiration date if validity type is 'GTD'.
symbolIsin : str
Symbol name of the security.
Price : int
Order price.
Volume : int
Order volume.
Returns 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
Order | None this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
A new Order instance if OMS session exists, else None. order's request.
Example All arguments are keyword-only.
-------
Args:
symbolIsin (str): ISIN code of the security (e.g., "IRO1FOLD0001").
Price (int): Order price, in IRR.
Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Buy_by_isin( >>> order = await client.Buy_by_isin(
symbolName="اطلس", ... symbolIsin="IRO1FOLD0001",
Price=100000, ... Price=100000,
Volume=10, ... Volume=10,
Order_ValidityType = 'DAY', ... Order_ValidityType='DAY',
ValidityDate = 0 ... ValidityDate=0,
) ... )
>>> await order.send() >>> if order is not None:
... await order.send()
""" """
await sleep(0) await sleep(0)
@@ -770,7 +886,8 @@ class EmsEngine_TseIfb_AsyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolIsin' : symbolIsin, 'symbolIsin' : symbolIsin,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -789,43 +906,49 @@ class EmsEngine_TseIfb_AsyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
""" """
Creates a new sell order by symbol isin asynchronously. Creates a new sell order by ISIN code asynchronously.
Parameters 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;
Order_ValidityType : str check the limits yourself if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Order validity type. ``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
ValidityDate : int
Expiration date if validity type is 'GTD'.
symbolIsin : str
Symbol name of the security.
Price : int
Order price.
Volume : int
Order volume.
Returns 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
Order | None this moment. A random ``InitialOrderId`` is also generated for every call and stored in the
A new Order instance if OMS session exists, else None. order's request.
Example All arguments are keyword-only.
-------
Args:
symbolIsin (str): ISIN code of the security (e.g., "IRO1FOLD0001").
Price (int): Order price, in IRR.
Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Returns:
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
Example:
>>> order = await client.Sell_by_isin( >>> order = await client.Sell_by_isin(
symbolName="اطلس", ... symbolIsin="IRO1FOLD0001",
Price=100000, ... Price=100000,
Volume=10, ... Volume=10,
Order_ValidityType = 'DAY', ... Order_ValidityType='DAY',
ValidityDate = 0 ... ValidityDate=0,
) ... )
>>> await order.send() >>> if order is not None:
... await order.send()
""" """
await sleep(0) await sleep(0)
@@ -847,7 +970,8 @@ class EmsEngine_TseIfb_AsyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolIsin' : symbolIsin, 'symbolIsin' : symbolIsin,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -855,4 +979,3 @@ class EmsEngine_TseIfb_AsyncClient:
else : return None else : return None
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
+376 -258
View File
@@ -13,6 +13,7 @@ from HedgeTech.Auth import AuthSyncClient
from PIL.Image import open as image_open from PIL.Image import open as image_open
from PIL.ImageFile import ImageFile from PIL.ImageFile import ImageFile
from io import BytesIO from io import BytesIO
from uuid import uuid4
# ========================================|======================================== # # ========================================|======================================== #
# Class Definitions # # Class Definitions #
@@ -24,10 +25,56 @@ class Order:
Represents a single trading order in EMS Engine. Represents a single trading order in EMS Engine.
This class provides methods to send, edit, check status, This class provides methods to send, edit, check status,
and delete an order after creation. and delete an order after creation. All of them are blocking calls.
An Order instance is usually created via An Order instance is usually created via the ``Buy_by_Name``, ``Sell_by_Name``,
`EmsEngine_TseIfb_SyncClient` methods. ``Buy_by_isin`` and ``Sell_by_isin`` methods of `EmsEngine_TseIfb_SyncClient`.
Creating an ``Order`` does NOT send anything to the exchange: you must call
``order.send()``.
Typical life cycle:
1. ``order = client.Buy_by_Name(...)``: 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`` without changing the order (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:
ValidityType (str): Validity type of the order: ``'DAY'`` (valid only for the current
trading session), ``'GTC'`` (Good Till Cancelled) or ``'GTD'`` (Good Till Date, valid
until ``ValidityDate``). ``'FAK'`` and ``'FOK'`` appear only in the type hint of
``Edit``. Updated by ``Edit``.
ValidityDate (int): Expiration date of the order. Only meaningful for ``'GTD'``; ``0``
otherwise. The format is the one expected by the server (the examples use YYYYMMDD,
e.g. ``20271206``).
SymbolNameOrIsin (str): Symbol name or ISIN code of the security, 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``.
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_Name(symbolName="اهرم", Price=12000, Volume=1000)
>>> if order is not None:
... order.send()
... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
""" """
def __init__( def __init__(
@@ -43,42 +90,34 @@ class Order:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
): ):
""" """
Initialize a new Order object. Create an Order object. Nothing is sent to the exchange.
Parameters All arguments are keyword-only. You normally do not call this directly: the ``Buy_*`` /
---------- ``Sell_*`` methods of ``EmsEngine_TseIfb_SyncClient`` build the order and its request for you.
SendOrder_RequestInfo : dict
HTTP request configuration for sending the order.
AuthSyncClient : AuthSyncClient Args:
Authenticated HTTP client. 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, Order_ValidityType, ValidityDate, symbolName | symbolIsin, 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.
SymbolNameOrIsin (str): Symbol name or ISIN code of the security.
Price (int): Order price, in IRR.
Volume (int): Total order volume.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to
``'DAY'``. Stored as the ``ValidityType`` attribute.
Order_ValidityType : Literal Example:
Order validity type.
ValidityDate : int
Expiration date (for GTD orders).
SymbolNameOrIsin : str
Symbol name or ISIN code.
Price : int
Order price.
Volume : int
Order volume.
OrderStatus : 'Unknown' | 'InQueue' | 'PartiallyFilled' | 'Cancelled' | 'Broken' | 'Settled'
Current lifecycle status of the order. The value is 'Unknown' until a status is received from the server.
Examples
--------
>>> order = client.Buy_by_Name( >>> order = client.Buy_by_Name(
... symbolName="اهرم", ... symbolName="اهرم",
... Price=12000, ... Price=12000,
@@ -105,6 +144,7 @@ class Order:
] = 'Unknown' ] = 'Unknown'
self.OrderId : HexUUID | None = None self.OrderId : HexUUID | None = None
self.OrderOmsId : str | None = None
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
@@ -113,23 +153,30 @@ class Order:
""" """
Send the order to the trading engine. Send the order to the trading engine.
This method submits the order to EMS Engine Posts ``SendOrder_RequestInfo`` through ``httpx_Client.post``, but only if the order has not
and assigns OrderId on success. been sent yet (``OrderId is None``). Once it was sent successfully, calling ``send()`` again has
no effect, so the same ``Order`` object is never submitted twice. If a call fails, the order stays
unsent and ``send()`` can be called again.
Returns 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
None not changed; call ``Status()`` to get it.
Notes Returns:
----- None: Always, whether it succeeded or not. Any other status or error is swallowed and the
- Can be called only once. order stays unsent (``OrderId`` remains ``None``). Check ``order.OrderId is not None``
- Subsequent calls have no effect. to know if the order was sent.
Examples Note:
-------- If a failed ``send()`` is tried 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.send() >>> order.send()
>>> print(order.OrderId) >>> if order.OrderId is not None:
'0xA23F...' ... print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
""" """
try : try :
@@ -142,7 +189,9 @@ class Order:
case 200 : case 200 :
self.OrderId = SendOrder_Response.json()['Data']['order_uuid'] data = SendOrder_Response.json()
self.OrderId = data['Data']['order_uuid']
self.OrderOmsId = data['Data']['order_oms_id']
return None return None
case _ : return None case _ : return None
@@ -171,36 +220,49 @@ class Order:
""" """
Edit an existing order. Edit an existing order.
Parameters Sends ``PATCH https://core.hedgetech.ir/ems-engine/tse-ifb/order/edit`` (form data:
---------- ``order_uuid``, ``Order_ValidityType``, ``ValidityDate``, ``Price``, ``Volume``). Nothing happens
Order_ValidityType : Literal if the order has not been sent yet (``OrderId is None``). All arguments are keyword-only and all
New validity type. of them are always sent: pass the current value of whatever you do not want to change (note that
``Order_ValidityType`` defaults to ``'DAY'``, so an edit without it turns a GTC/GTD order into a
DAY order).
ValidityDate : int How the result is applied:
New expiration date. * Status ``200``: ``ValidityType``, ``Price`` and ``Volume`` are updated from the server's
reply (``order_validity_type``, ``order_price``, ``order_volume``) and ``ValidityDate``
from the ``ValidityDate`` argument.
* 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 values (``Price``, ``ValidityType``, ``ValidityDate`` and
``ExecutedVolume + RemainedVolume == Volume``), the edit is considered applied and the
attributes are updated. If the order is no longer active (``Cancelled``, ``Broken`` or
``Settled``), only ``OrderStatus`` is updated. Otherwise nothing changes.
Price : int Args:
New order price. 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 ``ExecutedVolume + RemainedVolume``), it is not the
remaining volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD', 'FAK', 'FOK']): The new order validity type.
Defaults to ``'DAY'``. ``'FAK'`` (Fill And Kill) and ``'FOK'`` (Fill Or Kill) are listed
only here; the order creation methods accept ``'DAY'``, ``'GTC'`` and ``'GTD'``.
ValidityDate (int): New expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Volume : int Returns:
New order volume. None: Always. Errors are swallowed (nothing is raised). Compare ``Price``, ``Volume``,
``ValidityType`` and ``ValidityDate`` with what you requested (or call ``Status()``) to
know whether the edit was applied.
Returns Example:
-------
None
Raises
------
None
Examples
--------
>>> order.Edit( >>> order.Edit(
Price = 105, ... Price=105,
Volume = 15, ... Volume=15,
Order_ValidityType = 'GTD', ... Order_ValidityType='GTD',
ValidityDate = 20271206 ... ValidityDate=20271206,
) ... )
>>> order.Price, order.Volume
(105, 15)
""" """
try : try :
@@ -225,7 +287,6 @@ class Order:
Edit_response = Edit_response.json() Edit_response = Edit_response.json()
self.OrderId = Edit_response['Data']['order_uuid']
self.ValidityType = Edit_response['Data']['order_validity_type'] self.ValidityType = Edit_response['Data']['order_validity_type']
self.ValidityDate = ValidityDate self.ValidityDate = ValidityDate
self.Price = Edit_response['Data']['order_price'] self.Price = Edit_response['Data']['order_price']
@@ -270,77 +331,47 @@ class Order:
""" """
Retrieve the current status of the order. Retrieve the current status of the order.
This method queries the EMS Engine and returns detailed This method queries the EMS Engine and returns detailed execution and lifecycle information of
execution and lifecycle information of the order. the order. It sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/order/status`` with the
``order_uuid``. This method requires a valid ``OrderId``: nothing is sent if the order has not
been sent yet. 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 Returns:
------- OrderStatus | None: The ``Data`` part of the server's reply when the HTTP status is ``200``,
OrderStatus | None a dictionary with the following keys. ``None`` if the order has not been sent, the status
A dictionary containing order status information. is not ``200`` or any error occurred (network and server errors are silently ignored).
On success, the returned object contains the following fields: - order_uuid (HexUUID): Unique identifier of the order.
- order_status (Literal['InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
Current lifecycle state of the order:
- order_uuid : HexUUID * ``InQueue``: Order is waiting for execution (active).
Unique identifier of the order. * ``PartiallyFilled``: Part of the order has been executed, the rest is still
waiting (active).
* ``Cancelled``: Order was cancelled (final).
* ``Broken``: Order was rejected or failed (final).
* ``Settled``: Order fully executed (final).
- Price (int): Order price, in IRR.
- Volume (int): Total requested volume.
- RemainedVolume (int): Remaining unexecuted volume.
- ExecutedVolume (int): Total executed volume.
- OrderSide (Literal['Buy', 'Sell']): Side of the order.
- ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type.
- ValidityDate (int): Expiration date (for GTD orders, ``0`` otherwise).
- order_status : Literal['InQueue', 'PartiallyFilled, 'Cancelled', 'Broken', 'Settled'] Example:
Current lifecycle state of the order.
* InQueue : Order is waiting for execution.
* Cancelled : Order was cancelled.
* Broken : Order was rejected or failed.
* Settled : Order fully executed.
- Price : int
Order price.
- Volume : int
Total requested volume.
- RemainedVolume : int
Remaining unexecuted volume.
- ExecutedVolume : int
Total executed volume.
- OrderSide : Literal['Buy', 'Sell']
Side of the order.
- ValidityType : Literal['DAY', 'GTC', 'GTD']
Order validity type.
- ValidityDate : int
Expiration date (for GTD orders).
Returns None if the request fails or if the order
has not been sent yet.
Raises
------
None
Notes
-----
- This method requires a valid OrderId.
- If OrderId is None, None is returned.
- Network or server errors are silently ignored.
Examples
--------
>>> status = order.Status() >>> status = order.Status()
>>> print(status["order_status"]) >>> print(status["order_status"])
'Settled' Settled
>>> print(status["ExecutedVolume"]) >>> print(status["ExecutedVolume"])
1000 1000
>>> if status["RemainedVolume"] == 0: >>> if status["RemainedVolume"] == 0:
... print("Order fully executed") ... print("Order fully executed")
Order fully executed
Example Output >>> print(status)
--------------
{ {
"order_uuid": "0xA91F23BC...", "order_uuid": "953097ac6ced45ca8ef205b76ca6faf2",
"order_status": "Settled", "order_status": "Settled",
"Price": 12000, "Price": 12000,
"Volume": 1000, "Volume": 1000,
@@ -383,18 +414,23 @@ class Order:
""" """
Cancel/Delete the order. Cancel/Delete the order.
Sends delete request to EMS Engine. Sends ``DELETE https://core.hedgetech.ir/ems-engine/tse-ifb/order/delete`` with the
``order_uuid``. Nothing is sent if the order has not been sent yet (``OrderId is None``).
Returns How the result is applied:
------- * Status ``200``: ``is_deleted`` is set to ``True`` and ``OrderStatus`` to ``'Cancelled'``.
None * 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.
Notes ``OrderId`` is kept after deletion.
-----
After deletion, `is_deleted` becomes True.
Examples Returns:
-------- None: Always. Errors are swallowed (nothing is raised). After a successful deletion
``is_deleted`` becomes ``True``; check it (and ``OrderStatus``) to know the outcome.
Example:
>>> order.Delete() >>> order.Delete()
>>> print(order.is_deleted) >>> print(order.is_deleted)
True True
@@ -442,16 +478,54 @@ class Order:
class EmsEngine_TseIfb_SyncClient: class EmsEngine_TseIfb_SyncClient:
""" """
Synchronous EMS Engine client for TSE/IFB markets. Synchronous (blocking) EMS Engine client for TSE/IFB markets.
This client manages authentication, OMS login, This client manages authentication, OMS login,
and order creation. and order creation.
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_Name(...)`` (or ``Sell_by_Name``, ``Buy_by_isin``,
``Sell_by_isin``): 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_TSEBourseCode (str | None): TSE 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_TseIfb_SyncClient(AuthSyncClient=auth_client)
>>> captcha = client.Get_Captcha('Omex | Parsian')
>>> captcha.show()
>>> client.oms_login(
... username="user123",
... password="pass123",
... captcha_value="abcd",
... )
>>> order = client.Buy_by_Name(symbolName="اهرم", Price=12000, Volume=1000)
>>> order.send()
>>> print(order.OrderId)
953097ac6ced45ca8ef205b76ca6faf2
""" """
def __init__( def __init__(
self, self,
AuthSyncClient : AuthSyncClient, AuthSyncClient : AuthSyncClient,
): ):
"""
Create the EMS Engine client. Nothing is sent to the server.
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 self.__AuthSyncClient = AuthSyncClient
@@ -467,31 +541,34 @@ class EmsEngine_TseIfb_SyncClient:
self, self,
OMS : Literal[ OMS : Literal[
'Omex | Parsian', 'Omex | Parsian',
'Omex | Khobregan',
'Sahra | Karamad', 'Sahra | Karamad',
'Sahra | NIBB', 'Sahra | NIBB',
'Sahra | Charisma',
] ]
)-> ImageFile: )-> ImageFile:
""" """
Fetch captcha image for OMS login. Fetch captcha image for OMS login.
Parameters Sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` with the ``oms`` parameter.
---------- The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
OMS : Literal established by this call: call it with the same client right after ``Get_Captcha``.
OMS provider name.
Returns Args:
------- OMS (Literal['Omex | Parsian', 'Omex | Khobregan', 'Sahra | Karamad', 'Sahra | NIBB', 'Sahra | Charisma']):
ImageFile The OMS (broker system) to log into. The format is ``'<provider> | <broker>'``.
Captcha image.
Raises Returns:
------ ImageFile: The CAPTCHA image (a ``PIL`` image opened from the response bytes). Show or save it
ValueError and pass the value you read to ``oms_login``.
If server returns error.
Examples 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:
>>> img = client.Get_Captcha("Omex | Parsian") >>> img = client.Get_Captcha("Omex | Parsian")
>>> img.show() >>> img.show()
""" """
@@ -517,33 +594,36 @@ class EmsEngine_TseIfb_SyncClient:
""" """
Authenticate user in OMS system. Authenticate user in OMS system.
Parameters Sends ``POST https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` (form data: ``username``,
---------- ``Password``, ``Captcha_Value``). Call ``Get_Captcha`` first, with the same client. All arguments
username : str are keyword-only.
Trading account username.
password : str On success (HTTP ``200``) ``Customer_FullName``, ``Customer_TSEBourseCode`` and ``oms_session``
Trading account password. 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.
captcha_value : str Args:
Captcha solution. username (str): Trading account username.
password (str): Trading account password.
captcha_value (str): Captcha solution (the text of the image from ``Get_Captcha``).
Returns Returns:
-------
None None
Raises Raises:
------ ValueError: If authentication fails. For HTTP ``400`` (for example a wrong CAPTCHA or wrong
ValueError credentials) the message is the server's ``detail.Status.Description.en``; for any other
If authentication fails. non-``200`` status it is the raw response text.
Examples Example:
--------
>>> client.oms_login( >>> client.oms_login(
username = "user123", ... username="user123",
password = "pass123", ... password="pass123",
captcha_value = "abcd" ... captcha_value="abcd",
) ... )
>>> print(client.oms_session)
953097ac6ced45ca8ef205b76ca6faf2
""" """
response = self.__AuthSyncClient.httpx_Client.post( response = self.__AuthSyncClient.httpx_Client.post(
@@ -579,7 +659,6 @@ class EmsEngine_TseIfb_SyncClient:
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
def Buy_by_Name( def Buy_by_Name(
self, self,
*, *,
@@ -590,8 +669,6 @@ class EmsEngine_TseIfb_SyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
@@ -599,32 +676,43 @@ class EmsEngine_TseIfb_SyncClient:
""" """
Create a buy order using symbol name. Create a buy order using symbol name.
Parameters 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
symbolName : str if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Trading symbol name. ``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
Price : int A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
Order price. 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.
Volume : int All arguments are keyword-only.
Order volume.
Returns Args:
------- symbolName (str): Trading symbol name (e.g., "اهرم").
Order | None Price (int): Order price, in IRR.
Order instance if logged in, otherwise None. Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Examples Returns:
-------- Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
``None``.
Example:
>>> order = client.Buy_by_Name( >>> order = client.Buy_by_Name(
... symbolName="اهرم", ... symbolName="اهرم",
... Price=12000, ... Price=12000,
... Volume=1000, ... Volume=1000,
... Order_ValidityType='DAY', ... Order_ValidityType='DAY',
... ValidityDate = 0 ... ValidityDate=0,
... ) ... )
>>> order.send() >>> if order is not None:
... order.send()
""" """
if self.oms_session is not None: if self.oms_session is not None:
@@ -644,7 +732,8 @@ class EmsEngine_TseIfb_SyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolName' : symbolName, 'symbolName' : symbolName,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -665,8 +754,6 @@ class EmsEngine_TseIfb_SyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
@@ -674,32 +761,43 @@ class EmsEngine_TseIfb_SyncClient:
""" """
Create a sell order using symbol name. Create a sell order using symbol name.
Parameters 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
symbolName : str if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Trading symbol name. ``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
Price : int A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
Order price. 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.
Volume : int All arguments are keyword-only.
Order volume.
Returns Args:
------- symbolName (str): Trading symbol name (e.g., "اهرم").
Order | None Price (int): Order price, in IRR.
Order instance if logged in, otherwise None. Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Examples Returns:
-------- Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
``None``.
Example:
>>> order = client.Sell_by_Name( >>> order = client.Sell_by_Name(
... symbolName="اهرم", ... symbolName="اهرم",
... Price=12000, ... Price=12000,
... Volume=1000, ... Volume=1000,
... Order_ValidityType='DAY', ... Order_ValidityType='DAY',
... ValidityDate = 0 ... ValidityDate=0,
... ) ... )
>>> order.send() >>> if order is not None:
... order.send()
""" """
if self.oms_session is not None: if self.oms_session is not None:
@@ -719,7 +817,8 @@ class EmsEngine_TseIfb_SyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolName' : symbolName, 'symbolName' : symbolName,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -738,41 +837,50 @@ class EmsEngine_TseIfb_SyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
""" """
Create a buy order using symbol isin. Create a buy order using symbol ISIN.
Parameters 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
symbolIsin : str if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Trading symbol isin. ``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
Price : int A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
Order price. 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.
Volume : int All arguments are keyword-only.
Order volume.
Returns Args:
------- symbolIsin (str): Trading symbol ISIN code (e.g., "IRO1FOLD0001").
Order | None Price (int): Order price, in IRR.
Order instance if logged in, otherwise None. Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Examples Returns:
-------- Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
``None``.
Example:
>>> order = client.Buy_by_isin( >>> order = client.Buy_by_isin(
... symbolName="اهرم", ... symbolIsin="IRO1FOLD0001",
... Price=12000, ... Price=12000,
... Volume=1000, ... Volume=1000,
... Order_ValidityType='DAY', ... Order_ValidityType='DAY',
... ValidityDate = 0 ... ValidityDate=0,
... ) ... )
>>> order.send() >>> if order is not None:
... order.send()
""" """
if self.oms_session is not None: if self.oms_session is not None:
@@ -792,7 +900,8 @@ class EmsEngine_TseIfb_SyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolIsin' : symbolIsin, 'symbolIsin' : symbolIsin,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -811,41 +920,50 @@ class EmsEngine_TseIfb_SyncClient:
'DAY', 'DAY',
'GTC', # Good Till Cancelled 'GTC', # Good Till Cancelled
'GTD', # Good Till Date 'GTD', # Good Till Date
'FAK', # Fill And Kill
'FOK', # Fill Or Kill
] = 'DAY', ] = 'DAY',
ValidityDate : int = 0, ValidityDate : int = 0,
)-> Order | None: )-> Order | None:
""" """
Create a sell order using symbol isin. Create a sell order using symbol ISIN.
Parameters 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
symbolIsin : str if you need to (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
Trading symbol isin. ``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
Price : int A logged-in OMS session is required: if ``oms_session`` is ``None`` (``oms_login`` has not
Order price. 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.
Volume : int All arguments are keyword-only.
Order volume.
Returns Args:
------- symbolIsin (str): Trading symbol ISIN code (e.g., "IRO1FOLD0001").
Order | None Price (int): Order price, in IRR.
Order instance if logged in, otherwise None. Volume (int): Order volume.
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
``ValidityDate``.
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
``0``.
Examples Returns:
-------- Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
``None``.
Example:
>>> order = client.Sell_by_isin( >>> order = client.Sell_by_isin(
... symbolName="اهرم", ... symbolIsin="IRO1FOLD0001",
... Price=12000, ... Price=12000,
... Volume=1000, ... Volume=1000,
... Order_ValidityType='DAY', ... Order_ValidityType='DAY',
... ValidityDate = 0 ... ValidityDate=0,
... ) ... )
>>> order.send() >>> if order is not None:
... order.send()
""" """
if self.oms_session is not None: if self.oms_session is not None:
@@ -865,7 +983,8 @@ class EmsEngine_TseIfb_SyncClient:
'ValidityDate' : ValidityDate, 'ValidityDate' : ValidityDate,
'symbolIsin' : symbolIsin, 'symbolIsin' : symbolIsin,
'Price' : Price, 'Price' : Price,
'Volume' : Volume 'Volume' : Volume,
'InitialOrderId' : uuid4().hex,
} }
} }
) )
@@ -873,4 +992,3 @@ class EmsEngine_TseIfb_SyncClient:
else : return None else : return None
# +--------------------------------------------------------------------------------------+ # # +--------------------------------------------------------------------------------------+ #
@@ -21,51 +21,60 @@ class OrderStatus(TypedDict):
""" """
Represents the current status and execution details of an order. Represents the current status and execution details of an order.
Attributes Attributes:
---------- order_uuid (HexUUID): Unique identifier of the order.
order_uuid : HexUUID order_status (Literal['InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
Unique identifier of the order.
order_status : Literal['InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']
Current lifecycle status of the order. Current lifecycle status of the order.
Possible values: Possible values:
- ``InQueue``: The order has been accepted and is waiting to be matched. - ``InQueue``: The order has been accepted and is waiting to be matched.
- ``PartiallyFilled``: Part of the order has been executed, while the remaining volume is still active. - ``PartiallyFilled``: Part of the order has been executed, while the remaining volume is still active.
- ``Cancelled``: The order has been cancelled and will no longer be executed. - ``Cancelled``: The order has been cancelled and will no longer be executed.
- ``Broken``: The order has been rejected or terminated due to an error or exchange-side condition. - ``Broken``: The order has been rejected or terminated due to an error or exchange-side condition.
- ``Settled``: The order has been completely executed. - ``Settled``: The order has been completely executed.
Price : int ``InQueue`` and ``PartiallyFilled`` are active states (the order can still
Order price. be executed or cancelled). ``Cancelled``, ``Broken`` and ``Settled`` are
final states.
Volume : int Price (int): Order price, in IRR.
Total requested order volume. Volume (int): Total requested order volume.
RemainedVolume (int): Remaining volume that has not yet been executed.
RemainedVolume : int ExecutedVolume (int): Total executed volume so far. For an active order,
Remaining volume that has not yet been executed. ``Volume`` equals ``ExecutedVolume + RemainedVolume``.
OrderSide (Literal['Buy', 'Sell']): Side of the order.
ExecutedVolume : int
Total executed volume.
OrderSide : Literal['Buy', 'Sell']
Side of the order.
Possible values: Possible values:
- ``Buy``: Buy order. - ``Buy``: Buy order.
- ``Sell``: Sell order. - ``Sell``: Sell order.
ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity policy.
ValidityType : Literal['DAY', 'GTC', 'GTD']
Order validity policy.
Possible values: Possible values:
- ``DAY``: Valid only for the current trading session. - ``DAY``: Valid only for the current trading session.
- ``GTC`` (*Good Till Cancelled*): Remains active until cancelled. - ``GTC`` (*Good Till Cancelled*): Remains active until cancelled.
- ``GTD`` (*Good Till Date*): Remains active until the specified expiration date. - ``GTD`` (*Good Till Date*): Remains active until the specified expiration date.
ValidityDate (int): Expiration date of the order when ``ValidityType`` is
``GTD``. The format depends on the trading engine. It is only meaningful
for ``GTD`` orders.
ValidityDate : int Example:
Expiration date of the order when ``ValidityType`` is ``GTD``. >>> status: OrderStatus = {
The format depends on the trading engine. ... "order_uuid": "3f2b8c1e9a4d4e6f8b7a1c2d3e4f5a6b",
... "order_status": "PartiallyFilled",
... "Price": 35200,
... "Volume": 100,
... "RemainedVolume": 60,
... "ExecutedVolume": 40,
... "OrderSide": "Buy",
... "ValidityType": "GTD",
... "ValidityDate": 20251220
... }
>>> status['order_status'] in ('InQueue', 'PartiallyFilled')
True
>>> status['ExecutedVolume'] + status['RemainedVolume'] == status['Volume']
True
""" """
order_uuid : HexUUID order_uuid : HexUUID
+1881 -253
View File
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "HedgeTech" name = "HedgeTech"
version = "0.3.1b5" 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." 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" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
@@ -28,12 +28,12 @@ classifiers = [
"Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"License :: OSI Approved :: Apache Software License", "License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent", "Operating System :: OS Independent",
"Development Status :: 4 - Beta", "Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers", "Intended Audience :: Developers",
"Intended Audience :: Financial and Insurance Industry", "Intended Audience :: Financial and Insurance Industry",
@@ -61,3 +61,5 @@ dependencies = [
Homepage = "https://hedgetech.ir/landing/" Homepage = "https://hedgetech.ir/landing/"
Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md" Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md"
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech" Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
Store = "https://store.hedgetech.ir/"
LinkedIn = "https://www.linkedin.com/company/hedgetech-ir/"