54 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
mtrshirazi21 4d775e9000 fix: add missing comma in OrderStatus Literal 2026-07-23 21:46:46 +03:30
mtrshirazi21 6c943a559c improve order edit state recovery after failed requests 2026-07-23 21:28:08 +03:30
mtrshirazi21 ed991a3035 Added support for PartiallyFilled order status 2026-07-22 23:50:03 +03:30
mtrshirazi21 52367d54e1 unify sync and async order management logic 2026-07-22 01:00:37 +03:30
mtrshirazi21 c8090ba334 update pyproject.toml 2026-07-22 00:09:06 +03:30
mtrshirazi21 854bee9f9e improve order edit recovery using status verification 2026-07-22 00:05:15 +03:30
mtrshirazi21 3a603db3cf add .vscode dir 2026-07-21 11:59:14 +03:30
mtrshirazi21 3906a203a6 edit version 2026-05-31 14:23:48 +03:30
mtrshirazi21 a49db4397c solve bug Generator 2026-05-31 14:23:37 +03:30
mtrshirazi21 3d947bc558 add in init files 2026-05-31 14:05:45 +03:30
mtrshirazi21 2af7dfd648 update class ime clients 2026-05-29 17:02:30 +03:30
mtrshirazi21 bde8c980ef set new beta version 2026-05-29 16:36:37 +03:30
mtrshirazi21 e63dcddbea define sync and async client in ime DE 2026-05-29 16:33:47 +03:30
mtrshirazi21 cedbd76d0e edit README and pyproject toml 2026-05-29 15:38:41 +03:30
mtrshirazi21 52be955e6e expose types 2026-05-25 19:30:05 +03:30
mtrshirazi21 ecc1070f1c defin websocket io types 2026-05-25 19:12:00 +03:30
mtrshirazi21 126eab66f7 edit io types 2026-05-25 19:11:10 +03:30
mtrshirazi21 8a5f3142ef edit io_types 2026-05-24 21:18:57 +03:30
mtrshirazi21 9cfd36a891 define io types 2026-05-24 21:18:41 +03:30
mtrshirazi21 034c9a50ea define DE IME 2026-05-24 19:27:24 +03:30
mtrshirazi21 17bea4f2a3 Modifications to the terms and conditions related to Internet force majeure during times of war. 2026-05-17 21:44:05 +03:30
mtrshirazi21 747b257432 update version 2026-02-17 17:46:56 +03:30
mtrshirazi21 e6bd5852c2 Refactor order class functions in sync and async versions for improved error handling 2026-02-17 17:46:15 +03:30
mtrshirazi21 88359c882f update version 2026-02-14 15:31:36 +03:30
mtrshirazi21 420ebda323 Add timeout for more control on Async ws 2026-02-14 15:31:08 +03:30
mtrshirazi21 83314e0074 Add timeout for more control on sync ws 2026-02-14 15:12:22 +03:30
mtrshirazi21 f6132f8044 update 0.2.3 2026-02-06 17:43:46 +03:30
mtrshirazi21 2b4e532708 edit note and email - github issue 2026-02-06 17:43:04 +03:30
mtrshirazi21 db1001111a update to Stable v 2026-02-06 00:26:28 +03:30
mtrshirazi21 f3a9dd214b update readme 2026-02-06 00:18:20 +03:30
mtrshirazi21 07ca759248 edit def docs 2026-02-05 15:30:14 +03:30
mtrshirazi21 c9799fbd7f update readme 2026-02-05 01:18:41 +03:30
mtrshirazi21 22f8ea17d6 update version 2026-02-05 01:06:23 +03:30
mtrshirazi21 440c7947cc Function constructor variable modifications 2026-02-05 01:03:30 +03:30
mtrshirazi21 312f230b08 Updating the structure and design in EMS 2026-02-05 00:57:34 +03:30
mtrshirazi21 aa4d4bbabb define Retriable Client & edit name class EmsEngine_TseIfb_AsyncClient 2026-01-20 20:47:57 +03:30
mtrshirazi21 569a36edaa edit versions 2026-01-12 22:41:39 +03:30
mtrshirazi21 6b5e8ece84 del property -> order is valid from oeder class 2026-01-12 21:18:18 +03:30
mtrshirazi21 74f2a1e857 debug to create new order class & del property -> order is valid from oeder class 2026-01-12 21:16:57 +03:30
mtrshirazi21 870d660130 update OrderStatus TypedDict -> fild: order_status 2026-01-12 21:15:24 +03:30
27 changed files with 9559 additions and 993 deletions

No files matched your search

+3 -1
View File
@@ -208,4 +208,6 @@ __marimo__/
*.env*
*.ipynb
requirements.txt
*test*.py
*test*.py
.vscode
+114 -40
View File
@@ -2,6 +2,7 @@
# Imports #
# ========================================|======================================== #
from .__utils import RetriableAsyncClient
from httpx import (
AsyncClient ,
Timeout ,
@@ -16,12 +17,36 @@ class AuthAsyncClient:
"""
Asynchronous client for interacting with the HedgeTech API using JWT-based authentication.
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`.
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:
httpx_Client (AsyncClient): An instance of `httpx.AsyncClient` configured with authentication headers.
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'.
httpx_Client (AsyncClient): The HTTP client used for authorized requests. When created
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:
>>> client = await AuthAsyncClient.login(
@@ -32,8 +57,9 @@ class AuthAsyncClient:
'eyJ0eXAiOi'
>>> client.Permissions # Decoded JWT payload
{'sub': 'user_id', 'exp': 1700350200, ...}
>>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=client)
"""
def __init__(
self,
*,
@@ -43,40 +69,70 @@ class AuthAsyncClient:
"""
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:
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.token : dict[str,str] = token
self.UpdatePermission
@property
def UpdatePermission(self)-> None:
"""
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:
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 :
self.Permissions = decode(
jwt=self.token['Authorization'].encode(),
algorithms='HS256',
options={"verify_signature": False},
)
except Exception as e:
raise ValueError(e)
@classmethod
async def login(
cls,
@@ -84,22 +140,37 @@ class AuthAsyncClient:
UserName_or_Email : str,
Password : str
)-> "AuthAsyncClient":
"""
Authenticate a user and return an instance of `AuthAsyncClient`.
This method performs the login request to the HedgeTech API, retrieves JWT tokens,
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:
UserName_or_Email (str): The username or email of the user.
Password (str): The user's password.
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:
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:
>>> client = await AuthAsyncClient.login(
@@ -109,9 +180,9 @@ class AuthAsyncClient:
>>> client.token['Authorization'][:10]
'eyJ0eXAiOi'
"""
httpx_Client = AsyncClient(verify=True ,http1=False ,http2=True)
login_res = await httpx_Client.post(
url='https://core.hedgetech.ir/auth/user/token/issue',
data={
@@ -119,32 +190,35 @@ class AuthAsyncClient:
'Password' : Password
}
)
if login_res.status_code == 201:
token = login_res.json()
headers = {'origin' : 'https://core.hedgetech.ir'}
headers.update(token)
httpx_Client = AsyncClient(
verify=True ,
http1=False ,
http2=True ,
headers=headers,
cookies=httpx_Client.cookies,
timeout=Timeout(
connect=.5,
read=1,
write=1,
pool=.5,
httpx_Client = RetriableAsyncClient(
client = AsyncClient(
verify=True ,
http1=False ,
http2=True ,
headers=headers,
cookies=httpx_Client.cookies,
timeout=Timeout(
connect=.250,
read=1.5,
write=1.5,
pool=.250,
),
),
retries= 10
)
return cls(
httpx_Client = httpx_Client,
token = token
)
else :
raise ValueError(login_res.json().get('detail'))
+119 -42
View File
@@ -2,6 +2,7 @@
# Imports #
# ========================================|======================================== #
from .__utils import RetriableSyncClient
from httpx import (
Client ,
Timeout ,
@@ -17,12 +18,39 @@ class AuthSyncClient:
"""
Synchronous client for interacting with the HedgeTech API using JWT-based authentication.
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`.
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:
httpx_Client (Client): An instance of `httpx.Client` configured with authentication headers.
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'.
httpx_Client (Client): The HTTP client used for authorized requests. When created
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:
>>> client = AuthSyncClient.login(
@@ -33,8 +61,9 @@ class AuthSyncClient:
'eyJ0eXAiOi'
>>> client.Permissions # Decoded JWT payload
{'sub': 'user_id', 'exp': 1700350200, ...}
>>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=client)
"""
def __init__(
self,
*,
@@ -44,40 +73,70 @@ class AuthSyncClient:
"""
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:
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.token : dict[str,str] = token
self.UpdatePermission
@property
def UpdatePermission(self)-> None:
"""
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:
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 :
self.Permissions = decode(
jwt=self.token['Authorization'].encode(),
algorithms='HS256',
options={"verify_signature": False},
)
except Exception as e:
raise ValueError(e)
@classmethod
def login(
cls,
@@ -85,22 +144,37 @@ class AuthSyncClient:
UserName_or_Email : str,
Password : str
)-> "AuthSyncClient":
"""
Authenticate a user synchronously and return an instance of `AuthSyncClient`.
This method performs the login request to the HedgeTech API, retrieves JWT tokens,
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:
UserName_or_Email (str): The username or email of the user.
Password (str): The user's password.
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:
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:
>>> client = AuthSyncClient.login(
@@ -110,10 +184,10 @@ class AuthSyncClient:
>>> client.token['Authorization'][:10]
'eyJ0eXAiOi'
"""
httpx_Client = Client(verify=True ,http1=False ,http2=True)
login_res = httpx_Client.post(
url='https://core.hedgetech.ir/auth/user/token/issue',
data={
@@ -121,33 +195,36 @@ class AuthSyncClient:
'Password' : Password
}
)
if login_res.status_code == 201:
token = login_res.json()
headers = {'origin' : 'https://core.hedgetech.ir'}
headers.update(token)
httpx_Client = Client(
verify=True ,
http1=False ,
http2=True ,
headers=headers,
cookies=httpx_Client.cookies,
timeout=Timeout(
connect=.5,
read=1,
write=1,
pool=.5,
httpx_Client = RetriableSyncClient(
client = Client(
verify=True ,
http1=False ,
http2=True ,
headers=headers,
cookies=httpx_Client.cookies,
timeout=Timeout(
connect=.250,
read=1.5,
write=1.5,
pool=.250,
),
),
retries= 10
)
return cls(
httpx_Client = httpx_Client,
token = login_res.json()
token = token
)
else :
raise ValueError(login_res.json().get('detail'))
@@ -0,0 +1,63 @@
# ========================================|======================================== #
# Exports #
# ========================================|======================================== #
__all__ = [
'RetriableAsyncClient'
]
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from httpx import (
AsyncClient,
ConnectTimeout,
PoolTimeout,
ReadTimeout,
WriteTimeout,
)
# ========================================|======================================== #
# Class Definitions #
# ========================================|======================================== #
class RetriableAsyncClient:
def __init__(
self,
client: AsyncClient,
retries: int = 10,
)-> AsyncClient:
self._client = client
self._retries = retries
async def _request(self, method: str, **kwargs):
attempt = self._retries
while True:
try:
return await getattr(self._client, method)(**kwargs)
except (
ConnectTimeout,
PoolTimeout,
ReadTimeout,
WriteTimeout,
):
if attempt <= 0:
raise
attempt -= 1
def __getattr__(self, name: str):
attr = getattr(self._client, name)
if name in {"get", "post", "put", "delete", "patch", "options", "head"}:
async def wrapper(**kwargs):
return await self._request(name, **kwargs)
return wrapper
return attr
@@ -0,0 +1,65 @@
# ========================================|======================================== #
# Exports #
# ========================================|======================================== #
__all__ = [
'RetriableSyncClient'
]
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from httpx import (
Client,
ConnectTimeout,
PoolTimeout,
ReadTimeout,
WriteTimeout,
)
# ========================================|======================================== #
# Class Definitions #
# ========================================|======================================== #
class RetriableSyncClient:
def __init__(
self,
client: Client,
retries: int = 10,
)-> Client:
self._client = client
self._retries = retries
def _request(self, method: str, **kwargs):
attempt = self._retries
while True:
try:
return getattr(self._client, method)(**kwargs)
except (
ConnectTimeout,
PoolTimeout,
ReadTimeout,
WriteTimeout,
):
if attempt <= 0:
raise
attempt -= 1
def __getattr__(self, name: str):
attr = getattr(self._client, name)
if name in {"get", "post", "put", "delete", "patch", "options", "head"}:
def wrapper(**kwargs):
return self._request(name, **kwargs)
return wrapper
return attr
+2
View File
@@ -0,0 +1,2 @@
from .__RetriableAsyncClient import *
from .__RetriableSyncClient import *
+868
View File
@@ -0,0 +1,868 @@
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from asyncio import (
Event,
wait_for,
TimeoutError,
sleep,
)
from websockets.asyncio.client import connect
from json import loads
from HedgeTech.Auth import AuthAsyncClient
from typing import (
Literal,
List,
AsyncGenerator,
)
from .__io_types import (
WebsocketBase_contractName,
WebsocketBase_contractId,
OverviewResponse,
Contracts,
ContractInfoResponse,
AllowedPriceRangeResponse,
AggregateResponse,
BestLimitResponse,
)
# ========================================|======================================== #
# Class Definitions #
# ========================================|======================================== #
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__(
self,
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
# +--------------------------------------------------------------------------------------+ #
async def search_contracts(
self,
market : Literal[
"IMEDepositCertificate",
"IMEFutures",
"IMEOption",
],
Search_char : str,
)-> 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(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search',
params={
'market' : market,
'Search_char' : Search_char
}
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
async def websocket_by_name(
self,
contract_names: List[str],
event: Event | None = None,
)-> AsyncGenerator[
WebsocketBase_contractName,
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):
event = Event()
event.set()
async with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name?"
+ "&".join(f"contract_name={s}" for s in contract_names)
),
additional_headers=self.__AuthAsyncClient.token
) as ws:
while event.is_set():
try : yield loads(await wait_for(ws.recv(), timeout=2))
except TimeoutError:
await sleep(0)
continue
except Exception:
await ws.close()
break
# +--------------------------------------------------------------------------------------+ #
async def websocket_by_id(
self,
contract_ids: List[str | int],
event: Event | None = None,
)-> AsyncGenerator[
WebsocketBase_contractId,
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):
event = Event()
event.set()
async with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id?"
+ "&".join(f"contract_id={s}" for s in contract_ids)
),
additional_headers=self.__AuthAsyncClient.token
) as ws:
while event.is_set():
try : yield loads(await wait_for(ws.recv(), timeout=2))
except TimeoutError:
await sleep(0)
continue
except Exception:
await ws.close()
break
+867
View File
@@ -0,0 +1,867 @@
# ========================================|======================================== #
# Imports #
# ========================================|======================================== #
from threading import Event
from websockets.sync.client import connect
from json import loads
from HedgeTech.Auth import AuthSyncClient
from typing import (
Literal,
List,
Generator,
)
from .__io_types import (
WebsocketBase_contractName,
WebsocketBase_contractId,
OverviewResponse,
Contracts,
ContractInfoResponse,
AllowedPriceRangeResponse,
AggregateResponse,
BestLimitResponse,
)
# ========================================|======================================== #
# Class Definitions #
# ========================================|======================================== #
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__(
self,
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
# +--------------------------------------------------------------------------------------+ #
def search_contracts(
self,
market : Literal[
"IMEDepositCertificate",
"IMEFutures",
"IMEOption",
],
Search_char : str,
)-> 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(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search',
params={
'market' : market,
'Search_char' : Search_char
}
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name',
params=[('contract_names', name) for name in contract_names]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
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(
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id',
params=[('contract_ids', id) for id in contract_ids]
)
if data.is_success :
return data.json()
else :
raise ValueError(data.json().get('detail'))
# +--------------------------------------------------------------------------------------+ #
def websocket_by_name(
self,
contract_names: List[str],
event: Event | None = None,
)-> Generator[
WebsocketBase_contractName,
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):
event = Event()
event.set()
with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name?"
+ "&".join(f"contract_name={s}" for s in contract_names)
),
additional_headers=self.__AuthSyncClient.token
) as ws:
while event.is_set():
try : yield loads(ws.recv(timeout=2))
except TimeoutError : continue
except Exception:
ws.close()
break
# +--------------------------------------------------------------------------------------+ #
def websocket_by_id(
self,
contract_ids: List[str | int],
event: Event | None = None,
)-> Generator[
WebsocketBase_contractId,
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):
event = Event()
event.set()
with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id?"
+ "&".join(f"contract_id={s}" for s in contract_ids)
),
additional_headers=self.__AuthSyncClient.token
) as ws:
while event.is_set():
try : yield loads(ws.recv(timeout=2))
except TimeoutError : continue
except Exception:
ws.close()
break
+2
View File
@@ -0,0 +1,2 @@
from .__AsyncClient import DataEngine_Ime_AsyncClient
from .__SyncClient import DataEngine_Ime_SyncClient
@@ -0,0 +1,12 @@
from .__response import(
WebsocketBase_contractName,
WebsocketBase_contractId,
OverviewResponse,
Contracts,
ContractInfoResponse,
AllowedPriceRangeResponse,
AggregateResponse,
BestLimitResponse,
)
File diff suppressed because it is too large. Load diff
+4
View File
@@ -1,4 +1,8 @@
from .__tse_ifb import (
DataEngine_TseIfb_SyncClient,
DataEngine_TseIfb_AsyncClient
)
from .__ime import (
DataEngine_Ime_SyncClient,
DataEngine_Ime_AsyncClient
)
+149 -68
View File
@@ -2,7 +2,12 @@
# Imports #
# ========================================|======================================== #
from asyncio import Event
from asyncio import (
Event,
wait_for,
TimeoutError,
sleep,
)
from websockets.asyncio.client import connect
from json import loads
from HedgeTech.Auth import AuthAsyncClient
@@ -49,7 +54,7 @@ from .__io_types import (
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,
order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other
@@ -66,14 +71,14 @@ class DataEngine_TseIfb_AsyncClient:
__AuthAsyncClient (AuthAsyncClient): An instance of `AuthAsyncClient` used to perform
authorized HTTP requests and WebSocket connections.
Examples:
Example:
>>> auth_client = await AuthAsyncClient.login(
... UserName_or_Email="user@example.com",
... Password="secure_password"
... )
>>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth_client)
>>> 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(
... channels=["best-limit", "order-book"],
... symbol_names=["فملی"]
@@ -82,8 +87,14 @@ class DataEngine_TseIfb_AsyncClient:
Notes:
- 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`.
- 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__(
@@ -129,7 +140,8 @@ class DataEngine_TseIfb_AsyncClient:
Returns:
Instruments:
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
* TreasuryBonds
* StockOptions
@@ -185,8 +197,9 @@ class DataEngine_TseIfb_AsyncClient:
Returns:
Instruments:
A dictionary containing:
- Data: A mapping of symbol_name → Instrument info.
Instrument info is one of:
- Data: A list of instruments matching the provided symbol names.
Identify each item by its ``symbolName`` field (do not rely on the order).
Each item is one of:
* SecuritiesAndFunds
* TreasuryBonds
* StockOptions
@@ -203,7 +216,7 @@ class DataEngine_TseIfb_AsyncClient:
>>> result = await client.instruments_static_info_by_name(
... ["فملی", "خودرو"]
... )
>>> print(result["Data"]["فملی"]["symbolIsin"])
>>> print(result["Data"][0]["symbolIsin"])
"""
data = await self.__AuthAsyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name',
@@ -234,7 +247,8 @@ class DataEngine_TseIfb_AsyncClient:
Instruments:
A dictionary containing:
- 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.
- Status: Status information returned by the API.
@@ -394,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.
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 ask price, quantity, and order count
@@ -407,8 +422,9 @@ class DataEngine_TseIfb_AsyncClient:
BestLimitResponse:
An object containing:
- **Data**:
Mapping of symbol_name → BestLimitItem
Each BestLimitItem includes:
Mapping of symbol_name → best limit levels: a dictionary with up to 6
levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count
* buy_quantity
* buy_price
@@ -424,7 +440,7 @@ class DataEngine_TseIfb_AsyncClient:
Example:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
>>> 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(
@@ -448,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.
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:
symbol_isins (List[str]):
@@ -458,8 +474,9 @@ class DataEngine_TseIfb_AsyncClient:
BestLimitResponse:
An object containing:
- **Data**:
Mapping of symbol_isin → BestLimitItem
Each BestLimitItem includes:
Mapping of symbol_isin → best limit levels: a dictionary with up to 6
levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count
* buy_quantity
* buy_price
@@ -475,7 +492,7 @@ class DataEngine_TseIfb_AsyncClient:
Example:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
>>> 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(
@@ -919,7 +936,7 @@ class DataEngine_TseIfb_AsyncClient:
"nav": float,
"units": int,
"marketCap": int,
"as_of": datetime
"as_of": datetime # typically an ISO-formatted string in the decoded JSON
},
...
},
@@ -967,7 +984,7 @@ class DataEngine_TseIfb_AsyncClient:
"nav": float,
"units": int,
"marketCap": int,
"as_of": datetime
"as_of": datetime # typically an ISO-formatted string in the decoded JSON
},
...
},
@@ -1110,10 +1127,14 @@ class DataEngine_TseIfb_AsyncClient:
"""
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:
symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) for the start 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).
Resolution (Literal): Data resolution. Options:
- "1m", "5m", "15m", "30m", "1h" for intraday
@@ -1188,10 +1209,14 @@ class DataEngine_TseIfb_AsyncClient:
"""
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:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) for the start 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).
Resolution (Literal): Data resolution. Options:
- "1m", "5m", "15m", "30m", "1h" for intraday
@@ -1262,10 +1287,12 @@ class DataEngine_TseIfb_AsyncClient:
"""
Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name.
All parameters are keyword-only.
Args:
symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns:
CorporateActionResponse: TypedDict with structure:
@@ -1273,7 +1300,8 @@ class DataEngine_TseIfb_AsyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"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
- corporateAction: str
- symbolName: str
@@ -1327,10 +1355,12 @@ class DataEngine_TseIfb_AsyncClient:
"""
Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code.
All parameters are keyword-only.
Args:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns:
CorporateActionResponse: TypedDict with structure:
@@ -1338,7 +1368,8 @@ class DataEngine_TseIfb_AsyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"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
- corporateAction: str
- symbolName: str
@@ -1414,6 +1445,16 @@ class DataEngine_TseIfb_AsyncClient:
best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs 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()`` (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:
channels (List[str]):
List of channels to subscribe to. Possible values:
@@ -1427,13 +1468,15 @@ class DataEngine_TseIfb_AsyncClient:
symbol_names (List[str]):
List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]).
event (Event | None, optional):
Optional asyncio.Event to control the WebSocket loop.
If provided, the loop will continue while `event.is_set()` is True.
Defaults to a new set Event.
Optional asyncio.Event used as a stop switch. It must be set for the stream to run:
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:
AsyncGenerator:
Yields TypedDict objects depending on the channel subscribed:
Yields:
Union[BestLimit_WS_symbolName, OrderBook_WS_symbolName, Aggregate_WS_symbolName,
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'
- **OrderBook_WS_symbolName** for 'order-book'
- **OHLCV_WS_symbolName** for 'ohlcv-last-1m'
@@ -1443,14 +1486,22 @@ class DataEngine_TseIfb_AsyncClient:
- **FundInfo_WS_symbolName** for 'fund-info'
Each yielded object contains:
- `channel`: str — name of the channel
- `symbolName`: str — instrument symbol
- `timestamp`: str — server timestamp
- `data`: Dict[...] — channel-specific real-time data.
- `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:
WebSocketException or ValueError:
If the WebSocket connection fails or an exception occurs while receiving data.
websockets.exceptions.WebSocketException or OSError:
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:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
@@ -1458,10 +1509,11 @@ class DataEngine_TseIfb_AsyncClient:
... channels=["best-limit", "order-book"],
... symbol_names=["فملی"]
... ):
... print(update["data"])
... if update["channel"] == "best-limit":
... print(update["symbolName"], update["data"]["1"]["buy_price"])
"""
if event is None :
if not isinstance(event,Event):
event = Event()
event.set()
@@ -1473,12 +1525,16 @@ class DataEngine_TseIfb_AsyncClient:
),
additional_headers=self.__AuthAsyncClient.token
) as ws:
while event.is_set():
try:
yield loads(await ws.recv())
except :
try : yield loads(await wait_for(ws.recv(), timeout=2))
except TimeoutError:
await sleep(0)
continue
except Exception:
await ws.close()
break
@@ -1515,9 +1571,19 @@ class DataEngine_TseIfb_AsyncClient:
"""
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,
last 1-minute OHLCV, aggregate data, institutional vs individual trades, contract information,
and fund information.
This function streams continuous updates for multiple market channels such as
best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs 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()`` (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:
channels (List[str]):
@@ -1532,13 +1598,15 @@ class DataEngine_TseIfb_AsyncClient:
symbol_isins (List[str]):
List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]).
event (Event | None, optional):
Optional asyncio.Event to control the WebSocket loop.
If provided, the loop continues while `event.is_set()` is True.
Defaults to a new set Event.
Optional asyncio.Event used as a stop switch. It must be set for the stream to run:
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:
AsyncGenerator:
Yields TypedDict objects depending on the channel subscribed:
Yields:
Union[BestLimit_WS_symbolIsin, OrderBook_WS_symbolIsin, Aggregate_WS_symbolIsin,
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'
- **OrderBook_WS_symbolIsin** for 'order-book'
- **OHLCV_WS_symbolIsin** for 'ohlcv-last-1m'
@@ -1548,14 +1616,22 @@ class DataEngine_TseIfb_AsyncClient:
- **FundInfo_WS_symbolIsin** for 'fund-info'
Each yielded object contains:
- `channel`: str — channel name
- `channel`: Literal — name of the channel (one of the values above)
- `symbolIsin`: str — instrument ISIN
- `timestamp`: str — server timestamp
- `data`: Dict[...] — channel-specific real-time data.
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
numeric ``ServerTimeStamp`` in ``Status``)
- `data`: channel-specific real-time data.
Raises:
WebSocketException or ValueError:
If the WebSocket connection fails or an exception occurs during data reception.
websockets.exceptions.WebSocketException or OSError:
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:
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
@@ -1563,13 +1639,14 @@ class DataEngine_TseIfb_AsyncClient:
... channels=["best-limit", "order-book"],
... symbol_isins=["IR1234567890"]
... ):
... print(update["data"])
... if update["channel"] == "best-limit":
... print(update["symbolIsin"], update["data"]["1"]["buy_price"])
"""
if event is None :
if not isinstance(event,Event):
event = Event()
event.set()
async with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/tse-ifb/live/data/websocket/symbol/isin?"
@@ -1581,8 +1658,12 @@ class DataEngine_TseIfb_AsyncClient:
while event.is_set():
try:
yield loads(await ws.recv())
except :
try: yield loads(await wait_for(ws.recv(), timeout=2))
except TimeoutError:
await sleep(0)
continue
except Exception:
await ws.close()
break
+177 -75
View File
@@ -49,7 +49,7 @@ from .__io_types import (
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,
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
authorized synchronous HTTP requests and WebSocket connections.
Examples:
Example:
>>> auth_client = AuthSyncClient.login(
... UserName_or_Email="user@example.com",
... Password="secure_password"
... )
>>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth_client)
>>> 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(
... channels=["best-limit", "order-book"],
... symbol_names=["فملی"]
@@ -81,9 +81,19 @@ class DataEngine_TseIfb_SyncClient:
... print(update)
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.
- WebSocket methods yield streaming updates and should be used with `for` loops.
- Exceptions (ValueError) are raised when the API returns an error or request fails.
- 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 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__(
@@ -118,6 +128,8 @@ class DataEngine_TseIfb_SyncClient:
"""
Search for instruments in a specific market by name, title, or partial text (synchronous).
Both parameters are keyword-only.
Args:
market (Literal["SecuritiesAndFunds", "TreasuryBonds", "StockOptions", "StockFutures"]):
Determines which market group to search in.
@@ -130,7 +142,8 @@ class DataEngine_TseIfb_SyncClient:
Returns:
Instruments:
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
* TreasuryBonds
* StockOptions
@@ -187,8 +200,9 @@ class DataEngine_TseIfb_SyncClient:
Returns:
Instruments:
A dictionary containing:
- Data: A mapping of symbol_name → Instrument info.
Instrument info is one of:
- Data: A list of instruments matching the provided symbol names.
Identify each item by its ``symbolName`` field (do not rely on the order).
Each item is one of:
* SecuritiesAndFunds
* TreasuryBonds
* StockOptions
@@ -205,7 +219,7 @@ class DataEngine_TseIfb_SyncClient:
>>> result = client.instruments_static_info_by_name(
... ["فملی", "خودرو"]
... )
>>> print(result["Data"]["فملی"]["symbolIsin"])
>>> print(result["Data"][0]["symbolIsin"])
"""
data = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name',
@@ -236,7 +250,8 @@ class DataEngine_TseIfb_SyncClient:
Instruments:
A dictionary containing:
- 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.
- 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).
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 ask price, quantity, and order count
@@ -406,8 +422,9 @@ class DataEngine_TseIfb_SyncClient:
BestLimitResponse:
An object containing:
- **Data**:
Mapping of symbol_name → BestLimitItem
Each BestLimitItem includes:
Mapping of symbol_name → best limit levels: a dictionary with up to 6
levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count
* buy_quantity
* buy_price
@@ -423,7 +440,7 @@ class DataEngine_TseIfb_SyncClient:
Example:
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
>>> bl = client.live_best_limit_by_name(["فملی"])
>>> print(bl["Data"]["فملی"]["buy_price"])
>>> print(bl["Data"]["فملی"]["1"]["buy_price"])
"""
data = self.__AuthSyncClient.httpx_Client.get(
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).
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:
symbol_isins (List[str]):
@@ -456,8 +473,9 @@ class DataEngine_TseIfb_SyncClient:
BestLimitResponse:
An object containing:
- **Data**:
Mapping of symbol_isin → BestLimitItem
Each BestLimitItem includes:
Mapping of symbol_isin → best limit levels: a dictionary with up to 6
levels ("1" = best ... "6" = deepest).
Each level is a BestLimitItem that includes:
* buy_order_count
* buy_quantity
* buy_price
@@ -473,7 +491,7 @@ class DataEngine_TseIfb_SyncClient:
Example:
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
>>> 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(
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,
"units": 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,
"units": 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).
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:
symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) for the start 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).
Resolution (Literal): Data resolution. Options:
- "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).
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:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp for the start of the requested period.
end_timestamp (int): Unix timestamp for the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) for the start 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).
Resolution (Literal): Data resolution. Options:
- "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).
All parameters are keyword-only.
Args:
symbol_name (str): Trading symbol name (e.g., "فملی").
start_timestamp (int): Unix timestamp marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns:
CorporateActionResponse: TypedDict with structure:
@@ -1248,7 +1276,8 @@ class DataEngine_TseIfb_SyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"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
- corporateAction: 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).
All parameters are keyword-only.
Args:
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
start_timestamp (int): Unix timestamp marking the start of the requested period.
end_timestamp (int): Unix timestamp marking the end of the requested period.
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
Returns:
CorporateActionResponse: TypedDict with structure:
@@ -1313,7 +1344,8 @@ class DataEngine_TseIfb_SyncClient:
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
"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
- corporateAction: 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.
Although the method signature exists to maintain interface compatibility,
it cannot provide live updates like the asynchronous client.
Opens a blocking WebSocket connection and yields continuous updates for multiple market
channels such as best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs
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:
channels (List[str]):
List of channels to subscribe to. Possible values are:
List of channels to subscribe to. Possible values:
- 'best-limit'
- 'order-book'
- 'ohlcv-last-1m'
@@ -1402,19 +1445,43 @@ class DataEngine_TseIfb_SyncClient:
- 'fund-info'
symbol_names (List[str]):
List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]).
event (Event | None, optional):
Optional event object to mimic the async interface.
It has no effect in the synchronous client.
event (threading.Event | None, optional):
Optional ``threading.Event`` used as a stop switch. It must be set for the stream to run:
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:
Generator:
This generator does not yield any data in the synchronous client.
Use `DataEngine_TseIfb_AsyncClient.websocket_by_name` for streaming data.
Yields:
Union[BestLimit_WS_symbolName, OrderBook_WS_symbolName, Aggregate_WS_symbolName,
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'
- **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:
NotImplementedError:
Always raised to indicate that real-time WebSocket streaming
is not supported in the synchronous version.
websockets.exceptions.WebSocketException or OSError:
Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
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:
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
@@ -1422,13 +1489,14 @@ class DataEngine_TseIfb_SyncClient:
... channels=["best-limit", "order-book"],
... 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 event is None :
if not isinstance(event,Event):
event = Event()
event.set()
with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/tse-ifb/live/data/websocket/symbol/name?"
@@ -1440,13 +1508,12 @@ class DataEngine_TseIfb_SyncClient:
while event.is_set():
try :
yield loads(ws.recv())
except :
try : yield loads(ws.recv(timeout=2))
except TimeoutError : continue
except Exception:
ws.close()
break
# +--------------------------------------------------------------------------------------+ #
def websocket_by_isin(
@@ -1478,15 +1545,26 @@ class DataEngine_TseIfb_SyncClient:
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
by ISIN codes. This method exists to maintain interface consistency with
the asynchronous client but does not yield any live updates.
Opens a blocking WebSocket connection and yields continuous updates for multiple market
channels such as best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs
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:
channels (List[str]):
List of channels to subscribe to. Possible values are:
List of channels to subscribe to. Possible values:
- 'best-limit'
- 'order-book'
- 'ohlcv-last-1m'
@@ -1495,21 +1573,44 @@ class DataEngine_TseIfb_SyncClient:
- 'contract-info'
- 'fund-info'
symbol_isins (List[str]):
List of instrument ISIN codes to receive updates for
(e.g., ["IR1234567890", "IR0987654321"]).
event (Event | None, optional):
Optional event object to mimic the async interface.
It has no effect in the synchronous client.
List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]).
event (threading.Event | None, optional):
Optional ``threading.Event`` used as a stop switch. It must be set for the stream to run:
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:
Generator:
This generator does not yield any data in the synchronous client.
Use `DataEngine_TseIfb_AsyncClient.websocket_by_isin` for real-time streaming.
Yields:
Union[BestLimit_WS_symbolIsin, OrderBook_WS_symbolIsin, Aggregate_WS_symbolIsin,
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'
- **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:
NotImplementedError:
Always raised to indicate that WebSocket streaming is not supported
in the synchronous client.
websockets.exceptions.WebSocketException or OSError:
Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
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:
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
@@ -1517,13 +1618,14 @@ class DataEngine_TseIfb_SyncClient:
... channels=["best-limit", "order-book"],
... 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 event is None :
if not isinstance(event,Event):
event = Event()
event.set()
with connect(
uri=(
f"wss://core.hedgetech.ir/data-engine/tse-ifb/live/data/websocket/symbol/isin?"
@@ -1535,8 +1637,8 @@ class DataEngine_TseIfb_SyncClient:
while event.is_set():
try :
yield loads(ws.recv())
except :
try : yield loads(ws.recv(timeout=2))
except TimeoutError : continue
except Exception:
ws.close()
break
File diff suppressed because it is too large. Load diff
+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']
+5 -1
View File
@@ -1,4 +1,8 @@
from .__tse_ifb import (
EmsEngine_TseIfb_SyncClient,
EmsEngine_TseIfb_ASyncClient
EmsEngine_TseIfb_AsyncClient
)
from .__ime import (
EmsEngine_Ime_AsyncClient,
EmsEngine_Ime_SyncClient
)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,2 +1,2 @@
from .__SyncClient import EmsEngine_TseIfb_SyncClient
from .__AsyncClient import EmsEngine_TseIfb_ASyncClient
from .__AsyncClient import EmsEngine_TseIfb_AsyncClient
@@ -18,8 +18,67 @@ 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']):
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.
``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.
RemainedVolume (int): Remaining volume that has not yet been executed.
ExecutedVolume (int): Total executed volume so far. For an active order,
``Volume`` equals ``ExecutedVolume + RemainedVolume``.
OrderSide (Literal['Buy', 'Sell']): Side of the order.
Possible values:
- ``Buy``: Buy order.
- ``Sell``: Sell order.
ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity policy.
Possible values:
- ``DAY``: Valid only for the current trading session.
- ``GTC`` (*Good Till Cancelled*): Remains active until cancelled.
- ``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.
Example:
>>> status: OrderStatus = {
... "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
OrderInQueue : bool
order_status : Literal['InQueue','PartiallyFilled','Cancelled','Broken','Settled']
Price : int
Volume : int
RemainedVolume : int
+1945 -90
View File
File diff suppressed because it is too large. Load diff
+7 -5
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "HedgeTech"
version = "0.2.0b1"
version = "0.4.0"
description = "A unified, high-performance API layer that powers all trading infrastructure across the HedgeTech ecosystem, providing modular, scalable, and real-time interfaces for market data, order management, and execution systems."
readme = "README.md"
requires-python = ">=3.10"
@@ -28,12 +28,12 @@ classifiers = [
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Financial and Insurance Industry",
@@ -59,5 +59,7 @@ dependencies = [
[project.urls]
Homepage = "https://hedgetech.ir/landing/"
Documentation = "https://github.com/HedgeTech-ir/HedgeTech/blob/main/README.md"
Repository = "https://github.com/HedgeTech-ir/HedgeTech"
Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md"
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
Store = "https://store.hedgetech.ir/"
LinkedIn = "https://www.linkedin.com/company/hedgetech-ir/"