Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8e2e028a7 | ||
|
|
cead5ef4f4 | ||
|
|
dba5684940 | ||
|
|
7295d07c03 | ||
|
|
66aa5b41e6 | ||
|
|
f841157084 | ||
|
|
20d99ff661 | ||
|
|
115add658f | ||
|
|
57d2c7c8fd | ||
|
|
a0351324f9 | ||
|
|
3f936c17d7 | ||
|
|
71aeebfb44 | ||
|
|
0aa91d4e79 | ||
|
|
08244f17f2 | ||
|
|
4d775e9000 | ||
|
|
6c943a559c | ||
|
|
ed991a3035 | ||
|
|
52367d54e1 | ||
|
|
c8090ba334 | ||
|
|
854bee9f9e | ||
|
|
3a603db3cf | ||
|
|
3906a203a6 | ||
|
|
a49db4397c |
No files matched your search
+3
-1
@@ -208,4 +208,6 @@ __marimo__/
|
||||
*.env*
|
||||
*.ipynb
|
||||
requirements.txt
|
||||
*test*.py
|
||||
*test*.py
|
||||
|
||||
.vscode
|
||||
@@ -17,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(
|
||||
@@ -33,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,
|
||||
*,
|
||||
@@ -44,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,
|
||||
@@ -85,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(
|
||||
@@ -110,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={
|
||||
@@ -120,13 +190,13 @@ 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 = RetriableAsyncClient(
|
||||
client = AsyncClient(
|
||||
verify=True ,
|
||||
@@ -143,12 +213,12 @@ class AuthAsyncClient:
|
||||
),
|
||||
retries= 10
|
||||
)
|
||||
|
||||
|
||||
return cls(
|
||||
httpx_Client = httpx_Client,
|
||||
token = token
|
||||
)
|
||||
|
||||
|
||||
else :
|
||||
|
||||
|
||||
raise ValueError(login_res.json().get('detail'))
|
||||
@@ -18,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(
|
||||
@@ -34,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,
|
||||
*,
|
||||
@@ -45,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,
|
||||
@@ -86,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(
|
||||
@@ -111,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={
|
||||
@@ -122,14 +195,14 @@ 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 = RetriableSyncClient(
|
||||
client = Client(
|
||||
verify=True ,
|
||||
@@ -146,12 +219,12 @@ class AuthSyncClient:
|
||||
),
|
||||
retries= 10
|
||||
)
|
||||
|
||||
|
||||
return cls(
|
||||
httpx_Client = httpx_Client,
|
||||
token = token
|
||||
)
|
||||
|
||||
|
||||
else :
|
||||
|
||||
|
||||
raise ValueError(login_res.json().get('detail'))
|
||||
@@ -19,10 +19,10 @@ from typing import (
|
||||
from .__io_types import (
|
||||
WebsocketBase_contractName,
|
||||
WebsocketBase_contractId,
|
||||
|
||||
|
||||
OverviewResponse,
|
||||
Contracts,
|
||||
|
||||
|
||||
ContractInfoResponse,
|
||||
AllowedPriceRangeResponse,
|
||||
AggregateResponse,
|
||||
@@ -34,14 +34,76 @@ from .__io_types import (
|
||||
# ========================================|======================================== #
|
||||
|
||||
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(
|
||||
@@ -53,233 +115,568 @@ class DataEngine_Ime_AsyncClient:
|
||||
],
|
||||
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],
|
||||
@@ -288,11 +685,73 @@ class DataEngine_Ime_AsyncClient:
|
||||
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?"
|
||||
@@ -300,19 +759,19 @@ class DataEngine_Ime_AsyncClient:
|
||||
),
|
||||
additional_headers=self.__AuthAsyncClient.token
|
||||
) as ws:
|
||||
|
||||
|
||||
while event.is_set():
|
||||
|
||||
|
||||
try : yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def websocket_by_id(
|
||||
@@ -323,11 +782,71 @@ class DataEngine_Ime_AsyncClient:
|
||||
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?"
|
||||
@@ -335,15 +854,15 @@ class DataEngine_Ime_AsyncClient:
|
||||
),
|
||||
additional_headers=self.__AuthAsyncClient.token
|
||||
) as ws:
|
||||
|
||||
|
||||
while event.is_set():
|
||||
|
||||
|
||||
try : yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
@@ -14,10 +14,10 @@ from typing import (
|
||||
from .__io_types import (
|
||||
WebsocketBase_contractName,
|
||||
WebsocketBase_contractId,
|
||||
|
||||
|
||||
OverviewResponse,
|
||||
Contracts,
|
||||
|
||||
|
||||
ContractInfoResponse,
|
||||
AllowedPriceRangeResponse,
|
||||
AggregateResponse,
|
||||
@@ -29,14 +29,80 @@ from .__io_types import (
|
||||
# ========================================|======================================== #
|
||||
|
||||
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(
|
||||
@@ -48,241 +114,642 @@ class DataEngine_Ime_SyncClient:
|
||||
],
|
||||
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()
|
||||
@@ -294,17 +761,17 @@ class DataEngine_Ime_SyncClient:
|
||||
),
|
||||
additional_headers=self.__AuthSyncClient.token
|
||||
) as ws:
|
||||
|
||||
|
||||
while event.is_set():
|
||||
|
||||
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
|
||||
def websocket_by_id(
|
||||
self,
|
||||
@@ -312,13 +779,77 @@ class DataEngine_Ime_SyncClient:
|
||||
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?"
|
||||
@@ -326,12 +857,11 @@ class DataEngine_Ime_SyncClient:
|
||||
),
|
||||
additional_headers=self.__AuthSyncClient.token
|
||||
) as ws:
|
||||
|
||||
|
||||
while event.is_set():
|
||||
|
||||
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
|
||||
break
|
||||
@@ -17,11 +17,18 @@ from typing import (
|
||||
|
||||
class WebsocketBase_contractId(TypedDict):
|
||||
"""
|
||||
Base structure for websocket messages containing IME contract information
|
||||
Minimal base structure for websocket messages containing IME contract information
|
||||
identified by Contract ID.
|
||||
|
||||
This TypedDict defines the common structure of messages received over a websocket
|
||||
where each message is linked to a specific IME Contract ID.
|
||||
This TypedDict defines the common envelope of messages received over a websocket
|
||||
where each message is linked to a specific IME Contract ID. It does NOT include the
|
||||
live market payload (``data``).
|
||||
|
||||
Note:
|
||||
A class with the same name is defined again later in this file, which also
|
||||
includes the ``data`` field (the full live-stream message). Because Python
|
||||
keeps the last definition, the later one is the one that takes effect at
|
||||
runtime and for type checkers.
|
||||
|
||||
Attributes:
|
||||
channel (str): The name of the websocket channel through which the message is sent.
|
||||
@@ -43,11 +50,18 @@ class WebsocketBase_contractId(TypedDict):
|
||||
|
||||
class WebsocketBase_contractName(TypedDict):
|
||||
"""
|
||||
Base structure for websocket messages containing IME contract information
|
||||
Minimal base structure for websocket messages containing IME contract information
|
||||
identified by contract name.
|
||||
|
||||
This TypedDict defines the common structure of messages received over a websocket
|
||||
where each message is linked to a specific contract name.
|
||||
This TypedDict defines the common envelope of messages received over a websocket
|
||||
where each message is linked to a specific contract name. It does NOT include the
|
||||
live market payload (``data``).
|
||||
|
||||
Note:
|
||||
A class with the same name is defined again later in this file, which also
|
||||
includes the ``data`` field (the full live-stream message). Because Python
|
||||
keeps the last definition, the later one is the one that takes effect at
|
||||
runtime and for type checkers.
|
||||
|
||||
Attributes:
|
||||
channel (str): The name of the websocket channel through which the message is sent.
|
||||
@@ -96,12 +110,16 @@ class Status(TypedDict):
|
||||
|
||||
Attributes:
|
||||
State (bool): Indicates whether the operation or request was successful.
|
||||
ServerTimeStamp (float): Server timestamp, typically a Unix timestamp.
|
||||
ServerTimeStamp (float): Server time as a Unix timestamp (seconds since epoch,
|
||||
may include fractional seconds). Note that this is a
|
||||
number, unlike the ISO-formatted string ``timestamp``
|
||||
used in websocket messages.
|
||||
Version (str): Version of the API or server sending the message.
|
||||
Author (str): Name of the author or owner of the API/server.
|
||||
Description (StatusDescription): A human-readable description of the status
|
||||
in multiple languages.
|
||||
StatusCode (int): Numeric status code returned by the server.
|
||||
StatusCode (int): Numeric status code returned by the server (HTTP-style,
|
||||
e.g. 200 for success).
|
||||
|
||||
Example:
|
||||
>>> status: Status = {
|
||||
@@ -132,23 +150,27 @@ class IMEDepositCertificate(TypedDict):
|
||||
traded on the Iran Mercantile Exchange (IME), including identification, trading rules,
|
||||
commission rates, volume limits, and storage costs.
|
||||
|
||||
Note:
|
||||
Rates such as commissions are expressed as fractions, not percentages
|
||||
(e.g. ``0.0025`` means 0.25%). Multiply by 100 to display a percentage.
|
||||
|
||||
Attributes:
|
||||
contractId (str): Unique contractId code identifying the certificate.
|
||||
contractId (str): Unique identifier of the certificate.
|
||||
title (str): Full display name of the deposit certificate.
|
||||
contractName (str): Short name or ticker contract of the certificate.
|
||||
contractName (str): Short name / ticker of the certificate.
|
||||
minPriceChangeRate (float): Minimum allowed price change rate (tick size).
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
|
||||
owner (str): Market or organization that owns the certificate.
|
||||
buyCommission (float): Commission rate applied when buying (as percentage or fixed).
|
||||
sellCommission (float): Commission rate applied when selling (as percentage or fixed).
|
||||
buyCommission (float): Commission rate applied when buying (fraction, e.g. 0.0025 = 0.25%).
|
||||
sellCommission (float): Commission rate applied when selling (fraction, e.g. 0.0025 = 0.25%).
|
||||
canBuy (bool): Indicates if the certificate can currently be bought.
|
||||
canSell (bool): Indicates if the certificate can currently be sold.
|
||||
minValidBuyVolume (int): Minimum allowed buy order volume (lot size).
|
||||
maxValidBuyVolume (int): Maximum allowed buy order volume (lot size).
|
||||
minValidSellVolume (int): Minimum allowed sell order volume (lot size).
|
||||
maxValidSellVolume (int): Maximum allowed sell order volume (lot size).
|
||||
minDealablePrice (float): Minimum price per trade (floor price).
|
||||
minDealableCount (int): Minimum quantity per trade (minimum lot size).
|
||||
minValidBuyVolume (int): Minimum allowed volume for a single buy order.
|
||||
maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
|
||||
minValidSellVolume (int): Minimum allowed volume for a single sell order.
|
||||
maxValidSellVolume (int): Maximum allowed volume for a single sell order.
|
||||
minDealablePrice (float): Minimum price at which a trade can be executed (floor price).
|
||||
minDealableCount (int): Minimum quantity that can be traded in a single deal.
|
||||
StorageCost (float): Storage cost associated with the certificate (warehousing fee).
|
||||
dataClass (str): Internal classification or source of the instrument data.
|
||||
|
||||
@@ -208,35 +230,41 @@ class IMEFutures(TypedDict):
|
||||
traded on the Iran Mercantile Exchange (IME), including identification, margin requirements,
|
||||
trading rules, expiration details, exercise fees, and underlying asset information.
|
||||
|
||||
Note:
|
||||
Margins, commissions and taxes are expressed as fractions, not percentages
|
||||
(e.g. ``0.10`` means 10%). Multiply by 100 to display a percentage.
|
||||
|
||||
Attributes:
|
||||
contractId (str): Unique contractId code identifying the futures contract.
|
||||
contractId (str): Unique identifier of the futures contract.
|
||||
title (str): Full display name of the futures contract.
|
||||
contractName (str): Short name or ticker contract of the futures instrument.
|
||||
initialMargin (float): Initial margin required to open a position (as percentage or fixed).
|
||||
maintenanceMargin (float): Minimum maintenance margin required to keep position open.
|
||||
contractName (str): Short name / ticker of the futures instrument.
|
||||
initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.10 = 10%).
|
||||
maintenanceMargin (float): Minimum maintenance margin required to keep a position open (fraction).
|
||||
minPriceChangeRate (float): Minimum allowed price change rate (tick size).
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate (daily price limit).
|
||||
owner (str): Market or organization that owns the instrument.
|
||||
ExpirationDate (str): Expiration date of the futures contract (YYYY-MM-DD format).
|
||||
DaysToExpiration (int): Number of days remaining until expiration.
|
||||
buyCommission (float): Commission rate applied when buying (as percentage or fixed).
|
||||
sellCommission (float): Commission rate applied when selling (as percentage or fixed).
|
||||
buyCommission (float): Commission rate applied when buying (fraction, e.g. 0.0015 = 0.15%).
|
||||
sellCommission (float): Commission rate applied when selling (fraction, e.g. 0.0015 = 0.15%).
|
||||
canBuy (bool): Indicates if the instrument can currently be bought.
|
||||
canSell (bool): Indicates if the instrument can currently be sold.
|
||||
csize (int): Contract size of the futures instrument (lot size multiplier).
|
||||
minValidBuyVolume (int): Minimum allowed buy order volume.
|
||||
maxValidBuyVolume (int): Maximum allowed buy order volume.
|
||||
minValidSellVolume (int): Minimum allowed sell order volume.
|
||||
maxValidSellVolume (int): Maximum allowed sell order volume.
|
||||
minDealablePrice (float): Minimum price per trade (floor price).
|
||||
minDealableCount (int): Minimum quantity per trade (minimum lot size).
|
||||
csize (int): Contract size of the futures instrument (multiplier applied to price to get contract value).
|
||||
minValidBuyVolume (int): Minimum allowed volume for a single buy order.
|
||||
maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
|
||||
minValidSellVolume (int): Minimum allowed volume for a single sell order.
|
||||
maxValidSellVolume (int): Maximum allowed volume for a single sell order.
|
||||
minDealablePrice (float): Minimum price at which a trade can be executed (floor price).
|
||||
minDealableCount (int): Minimum quantity that can be traded in a single deal.
|
||||
ExerciseFeePhysical (float): Exercise fee for physical settlement.
|
||||
ExerciseFeeCash (float): Exercise fee for cash settlement.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell (as percentage).
|
||||
ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
|
||||
dataClass (str): Internal classification or source of the instrument data.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of the underlying asset.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
|
||||
(for IME instruments) of the underlying asset.
|
||||
UnderlyingAssets_title (str): Title/name of the underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of the underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
|
||||
contractName (for IME instruments) of the underlying asset.
|
||||
|
||||
Example:
|
||||
>>> futures: IMEFuturesDict = {
|
||||
@@ -312,38 +340,44 @@ class IMEOption(TypedDict):
|
||||
"""
|
||||
Static metadata structure for IME Option contracts.
|
||||
|
||||
Note:
|
||||
Margins, commissions and taxes are expressed as fractions, not percentages
|
||||
(e.g. ``0.05`` means 5%). Multiply by 100 to display a percentage.
|
||||
|
||||
Attributes:
|
||||
optionType (str): Type of the option - "Call" or "Put".
|
||||
contractId (str): Unique identifier of the option contract.
|
||||
title (str): Full display name of the option contract.
|
||||
contractName (str): Short name or ticker symbol.
|
||||
initialMargin (float): Initial margin required to open a position.
|
||||
requiredMargin (float): Total required margin for the position.
|
||||
maintenanceMargin (float): Minimum maintenance margin required.
|
||||
contractName (str): Short name / ticker of the option.
|
||||
initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.05 = 5%).
|
||||
requiredMargin (float): Total required margin for the position (fraction).
|
||||
maintenanceMargin (float): Minimum maintenance margin required (fraction).
|
||||
minPriceChangeRate (float): Minimum allowed price change rate (tick size).
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
|
||||
strikePrice (float): Strike (exercise) price of the option.
|
||||
owner (str): Market or organization that owns the option.
|
||||
ExpirationDate (str): Expiration date (YYYY-MM-DD).
|
||||
DaysToExpiration (int): Number of days remaining until expiration.
|
||||
buyCommission (float): Commission rate when buying.
|
||||
sellCommission (float): Commission rate when selling.
|
||||
buyCommission (float): Commission rate when buying (fraction, e.g. 0.002 = 0.2%).
|
||||
sellCommission (float): Commission rate when selling (fraction, e.g. 0.002 = 0.2%).
|
||||
canBuy (bool): Whether the option can currently be bought.
|
||||
canSell (bool): Whether the option can currently be sold.
|
||||
csize (int): Contract size of the option.
|
||||
minValidBuyVolume (int): Minimum allowed buy order volume.
|
||||
maxValidBuyVolume (int): Maximum allowed buy order volume.
|
||||
minValidSellVolume (int): Minimum allowed sell order volume.
|
||||
maxValidSellVolume (int): Maximum allowed sell order volume.
|
||||
minDealablePrice (float): Minimum price per trade.
|
||||
minDealableCount (int): Minimum quantity per trade.
|
||||
csize (int): Contract size of the option (number of underlying units per contract).
|
||||
minValidBuyVolume (int): Minimum allowed volume for a single buy order.
|
||||
maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
|
||||
minValidSellVolume (int): Minimum allowed volume for a single sell order.
|
||||
maxValidSellVolume (int): Maximum allowed volume for a single sell order.
|
||||
minDealablePrice (float): Minimum price at which a trade can be executed.
|
||||
minDealableCount (int): Minimum quantity that can be traded in a single deal.
|
||||
ExerciseFeePhysical (float): Exercise fee for physical settlement.
|
||||
ExerciseFeeCash (float): Exercise fee for cash settlement.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
|
||||
dataClass (str): Internal classification of the instrument data.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of underlying asset.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
|
||||
(for IME instruments) of the underlying asset.
|
||||
UnderlyingAssets_title (str): Title of the underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
|
||||
contractName (for IME instruments) of the underlying asset.
|
||||
|
||||
Example:
|
||||
>>> option: IMEOptionDict = {
|
||||
@@ -425,9 +459,15 @@ class Contracts(TypedDict):
|
||||
This TypedDict defines the response format returned by instrument search endpoints.
|
||||
Contains a list of matching instruments along with status metadata.
|
||||
|
||||
The type of each item can be told apart by its fields: options have ``optionType``
|
||||
and ``strikePrice``, futures have ``initialMargin`` but no ``optionType``, and
|
||||
deposit certificates have ``StorageCost``.
|
||||
|
||||
Attributes:
|
||||
Data (list[IMEDepositCertificateDict | IMEFuturesDict | IMEOptionDict | None]):
|
||||
List of matching instruments. Each item can be a Deposit Certificate, Futures, Option, or None if not found.
|
||||
List of matching instruments, in the same order as the requested
|
||||
identifiers. Each item can be a Deposit Certificate, Futures, Option, or
|
||||
None if no instrument was found for the corresponding identifier.
|
||||
Status (StatusDict): Status metadata including execution state, timestamp, version, and status code.
|
||||
|
||||
Example:
|
||||
@@ -485,11 +525,16 @@ class BestLimitItem(TypedDict):
|
||||
with their respective quantities and prices. It is used within the nested
|
||||
structure of BestLimit response.
|
||||
|
||||
Note:
|
||||
A level that has no orders on one side is expected to carry ``0`` for that
|
||||
side's price and quantity. Check that a price is greater than zero before
|
||||
using it in calculations (e.g. spread).
|
||||
|
||||
Attributes:
|
||||
buy_quantity (int): Total buy quantity available at this price level.
|
||||
buy_price (int): Buy price (bid) at this level.
|
||||
buy_price (int): Buy price (bid) at this level, in IRR.
|
||||
sell_quantity (int): Total sell quantity available at this price level.
|
||||
sell_price (int): Sell price (ask) at this level.
|
||||
sell_price (int): Sell price (ask) at this level, in IRR.
|
||||
|
||||
Example:
|
||||
>>> level: BestLimitItem = {
|
||||
@@ -516,8 +561,12 @@ class BestLimitResponse(TypedDict):
|
||||
"""
|
||||
Response structure for best limit order book endpoints.
|
||||
|
||||
The order book has up to 3 levels per contract: ``"1"`` is the best level
|
||||
(highest bid / lowest ask), ``"2"`` the next, and ``"3"`` the third.
|
||||
|
||||
Attributes:
|
||||
Data (BestLimit): Nested dictionary mapping contract IDs/names to limit levels.
|
||||
Data (Dict[str, Dict[Literal['1','2','3'], BestLimitItem]]):
|
||||
Dictionary mapping each contract ID/name to its order book levels.
|
||||
Status (Status): Status metadata of the response.
|
||||
|
||||
Example:
|
||||
@@ -559,13 +608,19 @@ class Aggregate(TypedDict):
|
||||
This TypedDict contains comprehensive trading data including OHLC prices,
|
||||
volume, value, trade count, and timestamps.
|
||||
|
||||
Note:
|
||||
Prices here are typed as ``float`` while prices in ``BestLimitItem`` are
|
||||
``int``. If a contract has had no trades yet in the session, price/volume
|
||||
fields may be ``0`` (and ``previous_close`` still holds the last session's
|
||||
close).
|
||||
|
||||
Attributes:
|
||||
date (str): Trading date in YYYY-MM-DD format.
|
||||
time (str): Time of last trade update in HH:MM:SS format.
|
||||
trade_count (int): Number of trades executed.
|
||||
total_volume (int): Total volume traded.
|
||||
total_value (int): Total value of trades in IRR.
|
||||
closing_price (float): Closing price of the contract.
|
||||
closing_price (float): Closing price of the contract (final settlement-style price of the session).
|
||||
last_price (float): Last traded price.
|
||||
low_price (float): Lowest traded price during the session.
|
||||
high_price (float): Highest traded price during the session.
|
||||
@@ -657,6 +712,7 @@ class AllowedPriceRange(TypedDict):
|
||||
|
||||
This TypedDict defines the minimum and maximum allowed prices for a contract
|
||||
on a given trading day, typically based on a percentage of the previous day's closing price.
|
||||
Orders outside this range are rejected by the exchange.
|
||||
|
||||
Attributes:
|
||||
minAllowedPrice (float): Minimum allowed price for the contract (lower price limit).
|
||||
@@ -724,7 +780,8 @@ class ContractInfo(TypedDict):
|
||||
|
||||
Attributes:
|
||||
open_interest (int): Open interest for the contract (number of open positions).
|
||||
open_interest_changes (int): Change in open interest compared to the previous period.
|
||||
open_interest_changes (int): Change in open interest compared to the previous period
|
||||
(positive = increase, negative = decrease).
|
||||
|
||||
Example:
|
||||
>>> info: ContractInfo = {
|
||||
@@ -780,26 +837,27 @@ class OverviewIMEDepositCertificate(TypedDict):
|
||||
"""
|
||||
Live market overview for IME Deposit Certificate instruments.
|
||||
|
||||
This combines static metadata with real-time market data including best limits,
|
||||
aggregate statistics, price ranges, and contract information.
|
||||
This combines static metadata (same fields as ``IMEDepositCertificate``) with
|
||||
real-time market data including best limits, aggregate statistics, price ranges,
|
||||
and contract information.
|
||||
|
||||
Attributes:
|
||||
contractId (str): Unique contractId code identifying the certificate.
|
||||
contractId (str): Unique identifier of the certificate.
|
||||
title (str): Full display name of the deposit certificate.
|
||||
contractName (str): Short name or ticker contract of the certificate.
|
||||
minPriceChangeRate (float): Minimum allowed price change rate.
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate.
|
||||
contractName (str): Short name / ticker of the certificate.
|
||||
minPriceChangeRate (float): Minimum allowed price change rate (tick size).
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
|
||||
owner (str): Market or organization that owns the certificate.
|
||||
buyCommission (float): Commission rate applied when buying.
|
||||
sellCommission (float): Commission rate applied when selling.
|
||||
buyCommission (float): Commission rate applied when buying (fraction, e.g. 0.0025 = 0.25%).
|
||||
sellCommission (float): Commission rate applied when selling (fraction, e.g. 0.0025 = 0.25%).
|
||||
canBuy (bool): Indicates if the certificate can currently be bought.
|
||||
canSell (bool): Indicates if the certificate can currently be sold.
|
||||
minValidBuyVolume (int): Minimum allowed buy order volume.
|
||||
maxValidBuyVolume (int): Maximum allowed buy order volume.
|
||||
minValidSellVolume (int): Minimum allowed sell order volume.
|
||||
maxValidSellVolume (int): Maximum allowed sell order volume.
|
||||
minDealablePrice (float): Minimum price per trade.
|
||||
minDealableCount (int): Minimum quantity per trade.
|
||||
minValidBuyVolume (int): Minimum allowed volume for a single buy order.
|
||||
maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
|
||||
minValidSellVolume (int): Minimum allowed volume for a single sell order.
|
||||
maxValidSellVolume (int): Maximum allowed volume for a single sell order.
|
||||
minDealablePrice (float): Minimum price at which a trade can be executed (floor price).
|
||||
minDealableCount (int): Minimum quantity that can be traded in a single deal.
|
||||
StorageCost (float): Storage cost associated with the certificate.
|
||||
dataClass (str): Internal classification or source of the instrument data.
|
||||
BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3").
|
||||
@@ -871,38 +929,41 @@ class OverviewIMEFutures(TypedDict):
|
||||
"""
|
||||
Live market overview for IME Futures contracts.
|
||||
|
||||
This combines static futures metadata with real-time market data including best limits,
|
||||
aggregate statistics, price ranges, and contract information.
|
||||
This combines static futures metadata (same fields as ``IMEFutures``) with
|
||||
real-time market data including best limits, aggregate statistics, price ranges,
|
||||
and contract information.
|
||||
|
||||
Attributes:
|
||||
contractId (str): Unique contractId code identifying the futures contract.
|
||||
contractId (str): Unique identifier of the futures contract.
|
||||
title (str): Full display name of the futures contract.
|
||||
contractName (str): Short name or ticker contract.
|
||||
initialMargin (float): Initial margin required to open a position.
|
||||
maintenanceMargin (float): Minimum maintenance margin required.
|
||||
minPriceChangeRate (float): Minimum allowed price change rate.
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate.
|
||||
contractName (str): Short name / ticker of the futures instrument.
|
||||
initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.10 = 10%).
|
||||
maintenanceMargin (float): Minimum maintenance margin required (fraction).
|
||||
minPriceChangeRate (float): Minimum allowed price change rate (tick size).
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
|
||||
owner (str): Market or organization that owns the instrument.
|
||||
ExpirationDate (str): Expiration date of the futures contract.
|
||||
ExpirationDate (str): Expiration date of the futures contract (YYYY-MM-DD).
|
||||
DaysToExpiration (int): Number of days remaining until expiration.
|
||||
buyCommission (float): Commission rate applied when buying.
|
||||
sellCommission (float): Commission rate applied when selling.
|
||||
buyCommission (float): Commission rate applied when buying (fraction).
|
||||
sellCommission (float): Commission rate applied when selling (fraction).
|
||||
canBuy (bool): Indicates if the instrument can currently be bought.
|
||||
canSell (bool): Indicates if the instrument can currently be sold.
|
||||
csize (int): Contract size of the futures instrument.
|
||||
minValidBuyVolume (int): Minimum allowed buy order volume.
|
||||
maxValidBuyVolume (int): Maximum allowed buy order volume.
|
||||
minValidSellVolume (int): Minimum allowed sell order volume.
|
||||
maxValidSellVolume (int): Maximum allowed sell order volume.
|
||||
minDealablePrice (float): Minimum price per trade.
|
||||
minDealableCount (int): Minimum quantity per trade.
|
||||
minValidBuyVolume (int): Minimum allowed volume for a single buy order.
|
||||
maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
|
||||
minValidSellVolume (int): Minimum allowed volume for a single sell order.
|
||||
maxValidSellVolume (int): Maximum allowed volume for a single sell order.
|
||||
minDealablePrice (float): Minimum price at which a trade can be executed.
|
||||
minDealableCount (int): Minimum quantity that can be traded in a single deal.
|
||||
ExerciseFeePhysical (float): Exercise fee for physical settlement.
|
||||
ExerciseFeeCash (float): Exercise fee for cash settlement.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
|
||||
dataClass (str): Internal classification or source of the instrument data.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of underlying asset.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
|
||||
(for IME instruments) of the underlying asset.
|
||||
UnderlyingAssets_title (str): Title of the underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
|
||||
contractName (for IME instruments) of the underlying asset.
|
||||
BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3").
|
||||
Aggregate (Aggregate): Aggregate trading statistics.
|
||||
AllowedPriceRange (AllowedPriceRange): Daily price limits.
|
||||
@@ -949,41 +1010,44 @@ class OverviewIMEOption(TypedDict):
|
||||
"""
|
||||
Live market overview for IME Option contracts.
|
||||
|
||||
This combines static option metadata with real-time market data including best limits,
|
||||
aggregate statistics, price ranges, and contract information.
|
||||
This combines static option metadata (same fields as ``IMEOption``) with
|
||||
real-time market data including best limits, aggregate statistics, price ranges,
|
||||
and contract information.
|
||||
|
||||
Attributes:
|
||||
optionType (str): Type of the option - "Call" or "Put".
|
||||
contractId (str): Unique contractId code identifying the option.
|
||||
contractId (str): Unique identifier of the option.
|
||||
title (str): Full display name of the option contract.
|
||||
contractName (str): Short name or ticker contract.
|
||||
initialMargin (float): Initial margin required to open a position.
|
||||
requiredMargin (float): Total required margin for the position.
|
||||
maintenanceMargin (float): Minimum maintenance margin required.
|
||||
minPriceChangeRate (float): Minimum allowed price change rate.
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate.
|
||||
contractName (str): Short name / ticker of the option.
|
||||
initialMargin (float): Initial margin required to open a position (fraction, e.g. 0.05 = 5%).
|
||||
requiredMargin (float): Total required margin for the position (fraction).
|
||||
maintenanceMargin (float): Minimum maintenance margin required (fraction).
|
||||
minPriceChangeRate (float): Minimum allowed price change rate (tick size).
|
||||
maxPriceChangeRate (float): Maximum allowed price change rate (daily limit).
|
||||
strikePrice (float): Strike price of the option.
|
||||
owner (str): Market or organization that owns the option.
|
||||
ExpirationDate (str): Expiration date of the option contract.
|
||||
ExpirationDate (str): Expiration date of the option contract (YYYY-MM-DD).
|
||||
DaysToExpiration (int): Number of days remaining until expiration.
|
||||
buyCommission (float): Commission rate applied when buying.
|
||||
sellCommission (float): Commission rate applied when selling.
|
||||
buyCommission (float): Commission rate applied when buying (fraction).
|
||||
sellCommission (float): Commission rate applied when selling (fraction).
|
||||
canBuy (bool): Indicates if the option can currently be bought.
|
||||
canSell (bool): Indicates if the option can currently be sold.
|
||||
csize (int): Contract size of the option.
|
||||
minValidBuyVolume (int): Minimum allowed buy order volume.
|
||||
maxValidBuyVolume (int): Maximum allowed buy order volume.
|
||||
minValidSellVolume (int): Minimum allowed sell order volume.
|
||||
maxValidSellVolume (int): Maximum allowed sell order volume.
|
||||
minDealablePrice (float): Minimum price per trade.
|
||||
minDealableCount (int): Minimum quantity per trade.
|
||||
minValidBuyVolume (int): Minimum allowed volume for a single buy order.
|
||||
maxValidBuyVolume (int): Maximum allowed volume for a single buy order.
|
||||
minValidSellVolume (int): Minimum allowed volume for a single sell order.
|
||||
maxValidSellVolume (int): Maximum allowed volume for a single sell order.
|
||||
minDealablePrice (float): Minimum price at which a trade can be executed.
|
||||
minDealableCount (int): Minimum quantity that can be traded in a single deal.
|
||||
ExerciseFeePhysical (float): Exercise fee for physical settlement.
|
||||
ExerciseFeeCash (float): Exercise fee for cash settlement.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell.
|
||||
ExerciseSellTax (float): Tax applied on exercise sell (fraction, e.g. 0.005 = 0.5%).
|
||||
dataClass (str): Internal classification of the instrument data.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN or contractId of underlying asset.
|
||||
UnderlyingAssets_symbolIsin_or_contractId (str | int): ISIN (for equities) or contractId
|
||||
(for IME instruments) of the underlying asset.
|
||||
UnderlyingAssets_title (str): Title of the underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol or contractName of underlying asset.
|
||||
UnderlyingAssets_symbolName_or_contractName (str): Symbol name (for equities) or
|
||||
contractName (for IME instruments) of the underlying asset.
|
||||
BestLimit (dict[str, BestLimitItem]): Best limit order book (levels "1", "2", "3").
|
||||
Aggregate (Aggregate): Aggregate trading statistics.
|
||||
AllowedPriceRange (AllowedPriceRange): Daily price limits.
|
||||
@@ -1036,9 +1100,14 @@ class OverviewResponse(TypedDict):
|
||||
This endpoint returns a dictionary mapping contract identifiers to their complete
|
||||
overview data (static + live) or None if the contract is not found.
|
||||
|
||||
The type of each overview can be told apart by its fields: options have
|
||||
``optionType`` and ``strikePrice``, futures have ``initialMargin`` but no
|
||||
``optionType``, and deposit certificates have ``StorageCost``.
|
||||
|
||||
Attributes:
|
||||
Data (dict[str, OverviewIMEDepositCertificate | OverviewIMEFutures | OverviewIMEOption | None]):
|
||||
Dictionary mapping contract IDs or names to overview objects or None.
|
||||
Dictionary mapping each requested contract ID or name to its overview
|
||||
object, or to None if no contract was found for that key.
|
||||
Status (Status): Status metadata of the response.
|
||||
|
||||
Example:
|
||||
@@ -1113,17 +1182,19 @@ class OverviewResponse(TypedDict):
|
||||
|
||||
|
||||
class Websocket_data(TypedDict):
|
||||
|
||||
"""
|
||||
Live market data payload for IME WebSocket streams.
|
||||
|
||||
This TypedDict represents the complete real-time market data for a single contract,
|
||||
including order book, trading statistics, price limits, and contract information.
|
||||
It is the value of the ``data`` field in the WebSocket messages below, and each
|
||||
new message carries a fresh full snapshot of these four sections.
|
||||
|
||||
Attributes:
|
||||
BestLimit (Dict[Literal['1','2','3'], BestLimitItem]):
|
||||
Best limit order book with 3 levels. Keys "1" (best), "2", "3" (worst).
|
||||
Each level contains buy/sell quantities and prices.
|
||||
Each level contains buy/sell quantities and prices. Empty levels carry
|
||||
zero values.
|
||||
|
||||
Aggregate (Aggregate):
|
||||
Aggregate trading statistics including OHLC, volume, trade count,
|
||||
@@ -1202,6 +1273,11 @@ class WebsocketBase_contractId(TypedDict):
|
||||
This TypedDict defines the standard format of all real-time messages received
|
||||
when subscribing to the `/contract/id` WebSocket endpoint.
|
||||
|
||||
Note:
|
||||
This is the full message type and it replaces the earlier, smaller
|
||||
``WebsocketBase_contractId`` defined at the top of this file (the one without
|
||||
``data``), since the last definition wins.
|
||||
|
||||
Attributes:
|
||||
channel (Literal["IME Stream"]):
|
||||
Fixed channel name for IME live market data streams.
|
||||
@@ -1211,7 +1287,10 @@ class WebsocketBase_contractId(TypedDict):
|
||||
|
||||
timestamp (str):
|
||||
ISO-formatted timestamp when the message was generated
|
||||
(e.g., "2025-01-15T14:30:00.123456").
|
||||
(e.g., "2025-01-15T14:30:00.123456"). This is a string, unlike the
|
||||
numeric ``ServerTimeStamp`` in ``Status``. It may or may not carry a
|
||||
timezone suffix (such as "Z"), so don't assume it is UTC unless you
|
||||
have confirmed it.
|
||||
|
||||
data (Websocket_data):
|
||||
Live market data payload containing BestLimit, Aggregate,
|
||||
@@ -1239,7 +1318,7 @@ class WebsocketBase_contractId(TypedDict):
|
||||
>>> print(f"Channel: {message['channel']}")
|
||||
Channel: IME Stream
|
||||
>>> print(f"Contract ID: {message['contractId']}")
|
||||
Contract ID: IME0012345
|
||||
Contract ID: 012345
|
||||
>>> print(f"Timestamp: {message['timestamp']}")
|
||||
Timestamp: 2025-01-15T14:30:00.123456
|
||||
>>> print(f"Last price: {message['data']['Aggregate']['last_price']}")
|
||||
@@ -1258,6 +1337,11 @@ class WebsocketBase_contractName(TypedDict):
|
||||
This TypedDict defines the standard format of all real-time messages received
|
||||
when subscribing to the `/contract/name` WebSocket endpoint.
|
||||
|
||||
Note:
|
||||
This is the full message type and it replaces the earlier, smaller
|
||||
``WebsocketBase_contractName`` defined at the top of this file (the one
|
||||
without ``data``), since the last definition wins.
|
||||
|
||||
Attributes:
|
||||
channel (Literal["IME Stream"]):
|
||||
Fixed channel name for IME live market data streams.
|
||||
@@ -1267,7 +1351,10 @@ class WebsocketBase_contractName(TypedDict):
|
||||
|
||||
timestamp (str):
|
||||
ISO-formatted timestamp when the message was generated
|
||||
(e.g., "2025-01-15T14:30:00.123456").
|
||||
(e.g., "2025-01-15T14:30:00.123456"). This is a string, unlike the
|
||||
numeric ``ServerTimeStamp`` in ``Status``. It may or may not carry a
|
||||
timezone suffix (such as "Z"), so don't assume it is UTC unless you
|
||||
have confirmed it.
|
||||
|
||||
data (Websocket_data):
|
||||
Live market data payload containing BestLimit, Aggregate,
|
||||
|
||||
@@ -54,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
|
||||
@@ -71,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=["فملی"]
|
||||
@@ -87,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__(
|
||||
@@ -134,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
|
||||
@@ -190,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
|
||||
@@ -208,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',
|
||||
@@ -239,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.
|
||||
|
||||
@@ -399,7 +408,8 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names.
|
||||
|
||||
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
|
||||
|
||||
@@ -412,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
|
||||
@@ -429,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(
|
||||
@@ -453,7 +464,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes.
|
||||
|
||||
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]):
|
||||
@@ -463,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
|
||||
@@ -480,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(
|
||||
@@ -924,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
|
||||
},
|
||||
...
|
||||
},
|
||||
@@ -972,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
|
||||
},
|
||||
...
|
||||
},
|
||||
@@ -1115,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
|
||||
@@ -1193,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
|
||||
@@ -1267,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:
|
||||
@@ -1278,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
|
||||
@@ -1332,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:
|
||||
@@ -1343,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
|
||||
@@ -1419,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:
|
||||
@@ -1432,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'
|
||||
@@ -1448,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)
|
||||
@@ -1463,7 +1509,8 @@ 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 not isinstance(event,Event):
|
||||
@@ -1524,9 +1571,19 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Subscribe to **real-time WebSocket updates** for a list of instruments using their ISIN codes.
|
||||
|
||||
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]):
|
||||
@@ -1541,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'
|
||||
@@ -1557,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)
|
||||
@@ -1572,7 +1639,8 @@ 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 not isinstance(event,Event):
|
||||
|
||||
@@ -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,7 +1489,8 @@ 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 not isinstance(event,Event):
|
||||
@@ -1477,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'
|
||||
@@ -1494,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)
|
||||
@@ -1516,7 +1618,8 @@ 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 not isinstance(event,Event):
|
||||
|
||||
@@ -21,17 +21,34 @@ class WebsocketBase_symbolIsin(TypedDict):
|
||||
Base structure for websocket messages containing fund or instrument information
|
||||
identified by ISIN (International Securities Identification Number).
|
||||
|
||||
This TypedDict defines the common structure of messages received over a websocket
|
||||
where each message is linked to a specific ISIN.
|
||||
This TypedDict defines the common envelope of messages received over a websocket
|
||||
where each message is linked to a specific ISIN. It does NOT include the
|
||||
market payload (``data``): every channel-specific message type below
|
||||
(``BestLimit_WS_symbolIsin``, ``OrderBook_WS_symbolIsin``, ...) extends this class and
|
||||
adds its own ``data`` field.
|
||||
|
||||
Attributes:
|
||||
channel (str): The name of the websocket channel through which the message is sent.
|
||||
channel (Literal["best-limit", "order-book", "ohlcv-last-1m", "aggregate",
|
||||
"institutional-vs-individual", "contract-info", "fund-info"]):
|
||||
The name of the websocket channel through which the message is sent.
|
||||
It identifies the kind of payload carried in ``data``:
|
||||
|
||||
- ``best-limit``: best limit order book levels (``BestLimit_WS_*``).
|
||||
- ``order-book``: full order book (``OrderBook_WS_*``).
|
||||
- ``ohlcv-last-1m``: live 1-minute OHLCV data (``OHLCV_WS_*``).
|
||||
- ``aggregate``: aggregate trading statistics (``Aggregate_WS_*``).
|
||||
- ``institutional-vs-individual``: individual vs institutional breakdown
|
||||
(``institutional_vs_individual_WS_*``).
|
||||
- ``contract-info``: open interest and margins (``ContractInfo_WS_*``).
|
||||
- ``fund-info``: NAV, units and market cap (``FundInfo_WS_*``).
|
||||
symbolIsin (str): The ISIN code of the instrument or fund.
|
||||
timestamp (str): ISO-formatted timestamp indicating when the message was generated.
|
||||
It is a string, unlike the numeric ``ServerTimeStamp`` in ``Status``, and it
|
||||
may or may not carry a timezone suffix.
|
||||
|
||||
Example:
|
||||
>>> message: WebsocketBase_symbolIsin = {
|
||||
... "channel": "fund_live_updates",
|
||||
... "channel": "best-limit",
|
||||
... "symbolIsin": "IR0001234567",
|
||||
... "timestamp": "2025-11-19T10:30:00Z"
|
||||
... }
|
||||
@@ -56,17 +73,34 @@ class WebsocketBase_symbolName(TypedDict):
|
||||
Base structure for websocket messages containing fund or instrument information
|
||||
identified by symbol name.
|
||||
|
||||
This TypedDict defines the common structure of messages received over a websocket
|
||||
where each message is linked to a specific symbol name.
|
||||
This TypedDict defines the common envelope of messages received over a websocket
|
||||
where each message is linked to a specific symbol name. It does NOT include the
|
||||
market payload (``data``): every channel-specific message type below
|
||||
(``BestLimit_WS_symbolName``, ``OrderBook_WS_symbolName``, ...) extends this class and
|
||||
adds its own ``data`` field.
|
||||
|
||||
Attributes:
|
||||
channel (str): The name of the websocket channel through which the message is sent.
|
||||
channel (Literal["best-limit", "order-book", "ohlcv-last-1m", "aggregate",
|
||||
"institutional-vs-individual", "contract-info", "fund-info"]):
|
||||
The name of the websocket channel through which the message is sent.
|
||||
It identifies the kind of payload carried in ``data``:
|
||||
|
||||
- ``best-limit``: best limit order book levels (``BestLimit_WS_*``).
|
||||
- ``order-book``: full order book (``OrderBook_WS_*``).
|
||||
- ``ohlcv-last-1m``: live 1-minute OHLCV data (``OHLCV_WS_*``).
|
||||
- ``aggregate``: aggregate trading statistics (``Aggregate_WS_*``).
|
||||
- ``institutional-vs-individual``: individual vs institutional breakdown
|
||||
(``institutional_vs_individual_WS_*``).
|
||||
- ``contract-info``: open interest and margins (``ContractInfo_WS_*``).
|
||||
- ``fund-info``: NAV, units and market cap (``FundInfo_WS_*``).
|
||||
symbolName (str): The symbol name of the instrument or fund.
|
||||
timestamp (str): ISO-formatted timestamp indicating when the message was generated.
|
||||
It is a string, unlike the numeric ``ServerTimeStamp`` in ``Status``, and it
|
||||
may or may not carry a timezone suffix.
|
||||
|
||||
Example:
|
||||
>>> message: WebsocketBase_symbolName = {
|
||||
... "channel": "fund_live_updates",
|
||||
... "channel": "best-limit",
|
||||
... "symbolName": "ETF001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z"
|
||||
... }
|
||||
@@ -115,12 +149,15 @@ class Status(TypedDict):
|
||||
|
||||
Attributes:
|
||||
State (bool): Indicates whether the operation or request was successful.
|
||||
ServerTimeStamp (float): Server timestamp, typically a Unix timestamp.
|
||||
ServerTimeStamp (float): Server time as a Unix timestamp (seconds since epoch,
|
||||
may include fractional seconds). Note that this is a number, unlike the
|
||||
ISO-formatted string ``timestamp`` used in websocket messages.
|
||||
Version (str): Version of the API or server sending the message.
|
||||
Author (str): Name of the author or owner of the API/server.
|
||||
Description (StatusDescription): A human-readable description of the status
|
||||
in multiple languages.
|
||||
StatusCode (int): Numeric status code returned by the server.
|
||||
in multiple languages.
|
||||
StatusCode (int): Numeric status code returned by the server (HTTP-style,
|
||||
e.g. 200 for success).
|
||||
|
||||
Example:
|
||||
>>> status: Status = {
|
||||
@@ -153,13 +190,19 @@ class SecuritiesAndFunds(TypedDict):
|
||||
traded instruments, providing all necessary details for order validation,
|
||||
display, and transaction execution.
|
||||
|
||||
Note:
|
||||
Commission rates are fractions, not percentages (``0.0015`` means 0.15%).
|
||||
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this is the type
|
||||
that has ``baseVolume`` (``TreasuryBonds`` has ``baseVol``) and has no
|
||||
``optionType`` or ``firstMargin``.
|
||||
|
||||
Attributes:
|
||||
symbolIsin (str): International Securities Identification Number (ISIN) of the instrument.
|
||||
symbolName (str): Trading symbol of the instrument.
|
||||
title (str): Human-readable name or title of the security/fund.
|
||||
|
||||
buyCommission (float): Commission rate applied when buying this security/fund.
|
||||
sellCommission (float): Commission rate applied when selling this security/fund.
|
||||
buyCommission (float): Commission rate applied when buying this security/fund (fraction, e.g. 0.0015 = 0.15%).
|
||||
sellCommission (float): Commission rate applied when selling this security/fund (fraction, e.g. 0.0015 = 0.15%).
|
||||
|
||||
minValidBuyVolume (int): Minimum allowable buy volume per order.
|
||||
maxValidBuyVolume (int): Maximum allowable buy volume per order.
|
||||
@@ -169,11 +212,11 @@ class SecuritiesAndFunds(TypedDict):
|
||||
canBuy (bool): Indicates whether buying is currently permitted.
|
||||
canSell (bool): Indicates whether selling is currently permitted.
|
||||
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order.
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
|
||||
|
||||
is_ETF (bool): Indicates if the security/fund is an Exchange-Traded Fund (ETF).
|
||||
baseVolume (float): The base trading volume unit of the instrument.
|
||||
baseVolume (float): Base volume (حجم مبنا) of the instrument, as defined by the exchange.
|
||||
minDealablePrice (float): Minimum price at which a deal can be executed.
|
||||
minDealableCount (int): Minimum number of units that can be traded per deal.
|
||||
|
||||
@@ -251,6 +294,11 @@ class StockFutures(TypedDict):
|
||||
ETFs, or other underlying instruments, providing all necessary details for order
|
||||
validation, execution, and reporting.
|
||||
|
||||
Note:
|
||||
Commission rates are fractions, not percentages (``0.001`` means 0.1%).
|
||||
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this type is
|
||||
recognized by ``firstMargin`` / ``minimumMargin``.
|
||||
|
||||
Attributes:
|
||||
symbolIsin (str): ISIN code of the futures contract.
|
||||
title (str): Human-readable name or title of the futures contract.
|
||||
@@ -269,8 +317,8 @@ class StockFutures(TypedDict):
|
||||
ExpirationDate (str): Expiration date of the contract in ISO format (YYYY-MM-DD).
|
||||
DaysToExpiration (int): Number of days remaining until the contract expires.
|
||||
|
||||
buyCommission (float): Commission rate applied when buying the contract.
|
||||
sellCommission (float): Commission rate applied when selling the contract.
|
||||
buyCommission (float): Commission rate applied when buying the contract (fraction, e.g. 0.001 = 0.1%).
|
||||
sellCommission (float): Commission rate applied when selling the contract (fraction, e.g. 0.001 = 0.1%).
|
||||
|
||||
minValidBuyVolume (int): Minimum valid buy volume per order.
|
||||
maxValidBuyVolume (int): Maximum valid buy volume per order.
|
||||
@@ -280,8 +328,8 @@ class StockFutures(TypedDict):
|
||||
canBuy (bool): Indicates whether buying is currently allowed.
|
||||
canSell (bool): Indicates whether selling is currently allowed.
|
||||
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order.
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
|
||||
|
||||
minDealableCount (int): Minimum number of contracts per deal.
|
||||
minDealablePrice (float): Minimum price at which a deal can be executed.
|
||||
@@ -399,13 +447,18 @@ class StockOptions(TypedDict):
|
||||
This TypedDict is typically used in systems that handle equity options, providing
|
||||
all necessary details for order validation, execution, reporting, and margin calculations.
|
||||
|
||||
Note:
|
||||
Commission rates are fractions, not percentages (``0.001`` means 0.1%).
|
||||
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this type is
|
||||
recognized by ``optionType`` / ``strikePrice``.
|
||||
|
||||
Attributes:
|
||||
symbolIsin (str): ISIN code of the options contract.
|
||||
symbolName (str): Trading symbol of the options contract.
|
||||
title (str): Human-readable name or title of the options contract.
|
||||
|
||||
buyCommission (float): Commission rate applied when buying the option.
|
||||
sellCommission (float): Commission rate applied when selling the option.
|
||||
buyCommission (float): Commission rate applied when buying the option (fraction, e.g. 0.001 = 0.1%).
|
||||
sellCommission (float): Commission rate applied when selling the option (fraction, e.g. 0.001 = 0.1%).
|
||||
|
||||
minValidBuyVolume (int): Minimum valid buy volume per order.
|
||||
maxValidBuyVolume (int): Maximum valid buy volume per order.
|
||||
@@ -415,17 +468,17 @@ class StockOptions(TypedDict):
|
||||
canBuy (bool): Indicates whether buying is currently allowed.
|
||||
canSell (bool): Indicates whether selling is currently allowed.
|
||||
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order.
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
|
||||
|
||||
minDealablePrice (float): Minimum price at which a deal can be executed.
|
||||
minDealableCount (int): Minimum number of contracts per deal.
|
||||
|
||||
owner (str): Name of the contract owner or issuing entity.
|
||||
|
||||
strikePrice (float): Strike price of the option.
|
||||
strikePrice (float): Strike (exercise) price of the option, in IRR.
|
||||
csize (int): Contract size (number of underlying units per option contract).
|
||||
optionType (str): Type of the option, e.g., "Call" or "Put".
|
||||
optionType (str): Type of the option: "Call" or "Put".
|
||||
ExpirationDate (str): Expiration date of the option in ISO format (YYYY-MM-DD).
|
||||
DaysToExpiration (int): Number of days remaining until expiration.
|
||||
|
||||
@@ -543,13 +596,19 @@ class TreasuryBonds(TypedDict):
|
||||
ETFs, or similar instruments, providing all necessary details for order validation,
|
||||
execution, reporting, and risk management.
|
||||
|
||||
Note:
|
||||
Commission rates are fractions, not percentages (``0.001`` means 0.1%).
|
||||
Prices are in IRR. Inside ``Instruments`` / ``OverviewResponse`` this type is
|
||||
recognized by ``baseVol`` (``SecuritiesAndFunds`` calls the same concept
|
||||
``baseVolume``).
|
||||
|
||||
Attributes:
|
||||
symbolIsin (str): ISIN code of the treasury bond.
|
||||
symbolName (str): Trading symbol of the bond.
|
||||
title (str): Human-readable name or title of the bond.
|
||||
|
||||
buyCommission (float): Commission rate applied when buying the bond.
|
||||
sellCommission (float): Commission rate applied when selling the bond.
|
||||
buyCommission (float): Commission rate applied when buying the bond (fraction, e.g. 0.001 = 0.1%).
|
||||
sellCommission (float): Commission rate applied when selling the bond (fraction, e.g. 0.001 = 0.1%).
|
||||
|
||||
minValidBuyVolume (int): Minimum valid buy volume per order.
|
||||
maxValidBuyVolume (int): Maximum valid buy volume per order.
|
||||
@@ -559,10 +618,10 @@ class TreasuryBonds(TypedDict):
|
||||
canBuy (bool): Indicates whether buying is currently allowed.
|
||||
canSell (bool): Indicates whether selling is currently allowed.
|
||||
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order.
|
||||
minAllowedPrice (float): Minimum price allowed for placing an order (lower daily price limit), in IRR.
|
||||
maxAllowedPrice (float): Maximum price allowed for placing an order (upper daily price limit), in IRR.
|
||||
|
||||
baseVol (float): Base trading volume unit of the bond.
|
||||
baseVol (float): Base volume (حجم مبنا) of the bond, as defined by the exchange.
|
||||
minDealablePrice (float): Minimum price at which a deal can be executed.
|
||||
minDealableCount (int): Minimum number of bonds per deal.
|
||||
|
||||
@@ -646,19 +705,27 @@ class Instruments(TypedDict):
|
||||
Represents a complete response containing a list of various financial instruments
|
||||
along with the server status metadata.
|
||||
|
||||
This TypedDict is commonly used to fetch or store all instruments data from an API,
|
||||
This TypedDict is commonly used to fetch or store instruments data from an API,
|
||||
including equities, ETFs, stock futures, stock options, and treasury bonds. Each
|
||||
instrument in the `Data` list can be one of several TypedDict types, providing
|
||||
a unified structure for heterogeneous financial instruments.
|
||||
|
||||
The type of an item can be recognized from its fields:
|
||||
|
||||
- ``optionType`` / ``strikePrice`` present -> ``StockOptions``
|
||||
- ``firstMargin`` / ``minimumMargin`` present -> ``StockFutures``
|
||||
- ``baseVol`` present -> ``TreasuryBonds``
|
||||
- ``baseVolume`` present -> ``SecuritiesAndFunds``
|
||||
|
||||
Attributes:
|
||||
Data (List[Union[SecuritiesAndFunds, StockFutures, StockOptions, TreasuryBonds, None]]):
|
||||
A list containing individual instrument data. Each item can be:
|
||||
- SecuritiesAndFunds: For standard securities and ETFs
|
||||
- StockFutures: For futures contracts on equities or ETFs
|
||||
- StockOptions: For options contracts
|
||||
- TreasuryBonds: For government-issued debt instruments
|
||||
- None: In case of missing or unavailable data
|
||||
|
||||
- SecuritiesAndFunds: For standard securities and ETFs
|
||||
- StockFutures: For futures contracts on equities or ETFs
|
||||
- StockOptions: For options contracts
|
||||
- TreasuryBonds: For government-issued debt instruments
|
||||
- None: In case of missing or unavailable data
|
||||
|
||||
Status (Status): Metadata about the server response, including success state,
|
||||
timestamp, version, author, description, and status code.
|
||||
@@ -755,13 +822,18 @@ class BestLimitItem(TypedDict):
|
||||
"""
|
||||
Represents the best limit order information at a given price level for a financial instrument.
|
||||
|
||||
Note:
|
||||
A level that has no orders on one side is expected to carry ``0`` for that
|
||||
side's count, quantity and price. Check that a price is greater than zero
|
||||
before using it in calculations (e.g. spread). Prices are in IRR.
|
||||
|
||||
Attributes:
|
||||
buy_order_count (int): Number of active buy orders at this price level.
|
||||
buy_quantity (int): Total quantity available for buying at this price level.
|
||||
buy_price (int): Price level for buy orders.
|
||||
buy_price (int): Price level for buy orders (bid).
|
||||
sell_order_count (int): Number of active sell orders at this price level.
|
||||
sell_quantity (int): Total quantity available for selling at this price level.
|
||||
sell_price (int): Price level for sell orders.
|
||||
sell_price (int): Price level for sell orders (ask).
|
||||
|
||||
Example:
|
||||
>>> item: BestLimitItem = {
|
||||
@@ -786,8 +858,13 @@ class BestLimitResponse(TypedDict):
|
||||
"""
|
||||
Response structure for best limit orders from a REST API call.
|
||||
|
||||
The depth is up to 6 levels per instrument: ``"1"`` is the best level (highest bid /
|
||||
lowest ask) and ``"6"`` the deepest.
|
||||
|
||||
Attributes:
|
||||
Data (BestLimit): Aggregated best limit order data.
|
||||
Data (Dict[str, Dict[Literal['1','2','3','4','5','6'], BestLimitItem]]):
|
||||
Dictionary mapping each instrument identifier (ISIN or symbolName) to its
|
||||
best limit levels.
|
||||
Status (Status): Metadata about the server response, including success state,
|
||||
timestamp, version, author, description, and status code.
|
||||
|
||||
@@ -836,13 +913,15 @@ class BestLimit_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
This TypedDict extends `WebsocketBase_symbolIsin` and represents real-time best
|
||||
limit order updates for a specific instrument identified by its ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"best-limit"``.
|
||||
|
||||
Attributes:
|
||||
data (Dict[str, BestLimitItem]): Dictionary mapping price levels or order priorities
|
||||
to BestLimitItem objects for the instrument.
|
||||
data (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit levels of
|
||||
the instrument. Key ``"1"`` is the best level and ``"6"`` the deepest.
|
||||
|
||||
Example:
|
||||
>>> ws_data: BestLimit_WS_symbolIsin = {
|
||||
... "channel": "best_limit_updates",
|
||||
... "channel": "best-limit",
|
||||
... "symbolIsin": "IR0001234567",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": {
|
||||
@@ -880,13 +959,15 @@ class BestLimit_WS_symbolName(WebsocketBase_symbolName):
|
||||
This TypedDict extends `WebsocketBase_symbolName` and represents real-time best
|
||||
limit order updates for a specific instrument identified by its trading symbol.
|
||||
|
||||
The ``channel`` of these messages is ``"best-limit"``.
|
||||
|
||||
Attributes:
|
||||
data (Dict[str, BestLimitItem]): Dictionary mapping price levels or order priorities
|
||||
to BestLimitItem objects for the instrument.
|
||||
data (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit levels of
|
||||
the instrument. Key ``"1"`` is the best level and ``"6"`` the deepest.
|
||||
|
||||
Example:
|
||||
>>> ws_data: BestLimit_WS_symbolName = {
|
||||
... "channel": "best_limit_updates",
|
||||
... "channel": "best-limit",
|
||||
... "symbolName": "ETF001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": {
|
||||
@@ -924,7 +1005,7 @@ class OrderItem(TypedDict):
|
||||
Represents a single order entry in the order book.
|
||||
|
||||
Attributes:
|
||||
price (float): Price level of the order.
|
||||
price (float): Price level of the order, in IRR.
|
||||
quantity (int): Total quantity available at this price level.
|
||||
count (int): Number of orders at this price level.
|
||||
|
||||
@@ -1002,12 +1083,14 @@ class OrderBook_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
"""
|
||||
Websocket message structure for order book updates identified by ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"order-book"``.
|
||||
|
||||
Attributes:
|
||||
data (OrderBook): Real-time order book for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> ws_data: OrderBook_WS_symbolIsin = {
|
||||
... "channel": "order_book_updates",
|
||||
... "channel": "order-book",
|
||||
... "symbolIsin": "IR0001234567",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": {
|
||||
@@ -1025,12 +1108,14 @@ class OrderBook_WS_symbolName(WebsocketBase_symbolName):
|
||||
"""
|
||||
Websocket message structure for order book updates identified by symbol name.
|
||||
|
||||
The ``channel`` of these messages is ``"order-book"``.
|
||||
|
||||
Attributes:
|
||||
data (OrderBook): Real-time order book for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> ws_data: OrderBook_WS_symbolName = {
|
||||
... "channel": "order_book_updates",
|
||||
... "channel": "order-book",
|
||||
... "symbolName": "ETF001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": {
|
||||
@@ -1053,13 +1138,18 @@ class Aggregate(TypedDict):
|
||||
|
||||
This includes trade statistics, volume, value, and price information.
|
||||
|
||||
Note:
|
||||
Prices and ``total_value`` are in IRR. Before the first trade of a session the
|
||||
price / volume fields may be ``0``, while ``previous_close`` still holds the
|
||||
last close.
|
||||
|
||||
Attributes:
|
||||
date (str): Date of the aggregation in ISO format (YYYY-MM-DD).
|
||||
time (str): Time of the aggregation in HH:MM:SS format.
|
||||
trade_count (int): Number of trades executed during this period.
|
||||
total_volume (int): Total traded volume.
|
||||
total_value (int): Total traded value (sum of price * quantity).
|
||||
closing_price (float): Closing price at the end of the period.
|
||||
total_value (int): Total traded value (sum of price * quantity), in IRR.
|
||||
closing_price (float): Closing price as computed by the exchange (it can differ from ``last_price``).
|
||||
last_price (float): Last traded price.
|
||||
low_price (float): Lowest price during the period.
|
||||
high_price (float): Highest price during the period.
|
||||
@@ -1107,6 +1197,7 @@ class AggregateResponse(TypedDict):
|
||||
timestamp, version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``agg`` is the ``Aggregate`` object from the example above.
|
||||
>>> response: AggregateResponse = {
|
||||
... "Data": {
|
||||
... "IR0001234567": agg
|
||||
@@ -1133,12 +1224,15 @@ class Aggregate_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
"""
|
||||
Websocket message structure for aggregated market data identified by ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"aggregate"``.
|
||||
|
||||
Attributes:
|
||||
data (Aggregate): Real-time aggregated data for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> # ``agg`` is the ``Aggregate`` object from the example above.
|
||||
>>> ws_data: Aggregate_WS_symbolIsin = {
|
||||
... "channel": "aggregate_updates",
|
||||
... "channel": "aggregate",
|
||||
... "symbolIsin": "IR0001234567",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": agg
|
||||
@@ -1153,12 +1247,15 @@ class Aggregate_WS_symbolName(WebsocketBase_symbolName):
|
||||
"""
|
||||
Websocket message structure for aggregated market data identified by symbol name.
|
||||
|
||||
The ``channel`` of these messages is ``"aggregate"``.
|
||||
|
||||
Attributes:
|
||||
data (Aggregate): Real-time aggregated data for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> # ``agg`` is the ``Aggregate`` object from the example above.
|
||||
>>> ws_data: Aggregate_WS_symbolName = {
|
||||
... "channel": "aggregate_updates",
|
||||
... "channel": "aggregate",
|
||||
... "symbolName": "ETF001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": agg
|
||||
@@ -1221,6 +1318,7 @@ class Institutional_vs_IndividualItemResponse(TypedDict):
|
||||
timestamp, version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``trades`` is the ``institutional_vs_individual`` object from the example above.
|
||||
>>> response: Institutional_vs_IndividualItemResponse = {
|
||||
... "Data": {"IR0001234567": trades},
|
||||
... "Status": {
|
||||
@@ -1245,13 +1343,16 @@ class institutional_vs_individual_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
"""
|
||||
Websocket message structure for institutional vs individual trading data identified by ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"institutional-vs-individual"``.
|
||||
|
||||
Attributes:
|
||||
data (institutional_vs_individual): Real-time breakdown of buy/sell activity for
|
||||
individual and institutional traders.
|
||||
|
||||
Example:
|
||||
>>> # ``trades`` is the ``institutional_vs_individual`` object from the example above.
|
||||
>>> ws_data: institutional_vs_individual_WS_symbolIsin = {
|
||||
... "channel": "inst_vs_ind_updates",
|
||||
... "channel": "institutional-vs-individual",
|
||||
... "symbolIsin": "IR0001234567",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": trades
|
||||
@@ -1266,13 +1367,16 @@ class institutional_vs_individual_WS_symbolName(WebsocketBase_symbolName):
|
||||
"""
|
||||
Websocket message structure for institutional vs individual trading data identified by symbol name.
|
||||
|
||||
The ``channel`` of these messages is ``"institutional-vs-individual"``.
|
||||
|
||||
Attributes:
|
||||
data (institutional_vs_individual): Real-time breakdown of buy/sell activity for
|
||||
individual and institutional traders.
|
||||
|
||||
Example:
|
||||
>>> # ``trades`` is the ``institutional_vs_individual`` object from the example above.
|
||||
>>> ws_data: institutional_vs_individual_WS_symbolName = {
|
||||
... "channel": "inst_vs_ind_updates",
|
||||
... "channel": "institutional-vs-individual",
|
||||
... "symbolName": "ETF001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": trades
|
||||
@@ -1289,6 +1393,10 @@ class ContractInfo(TypedDict):
|
||||
"""
|
||||
Represents key contract information for derivatives, including open interest and margin requirements.
|
||||
|
||||
Note:
|
||||
Present in every overview, but intended for derivatives (stock futures and
|
||||
options). For other instrument types check the values before relying on them.
|
||||
|
||||
Attributes:
|
||||
open_interest (int): Total number of outstanding contracts that have not been settled.
|
||||
initial_margin (int): Margin required to open a new position.
|
||||
@@ -1319,6 +1427,7 @@ class ContractInfoResponse(TypedDict):
|
||||
timestamp, version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``contract`` is the ``ContractInfo`` object from the example above.
|
||||
>>> response: ContractInfoResponse = {
|
||||
... "Data": {"IRFUT123456": contract},
|
||||
... "Status": {
|
||||
@@ -1343,12 +1452,15 @@ class ContractInfo_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
"""
|
||||
Websocket message structure for contract information updates identified by ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"contract-info"``.
|
||||
|
||||
Attributes:
|
||||
data (ContractInfo): Real-time contract information for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> # ``contract`` is the ``ContractInfo`` object from the example above.
|
||||
>>> ws_data: ContractInfo_WS_symbolIsin = {
|
||||
... "channel": "contract_info_updates",
|
||||
... "channel": "contract-info",
|
||||
... "symbolIsin": "IRFUT123456",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": contract
|
||||
@@ -1363,12 +1475,15 @@ class ContractInfo_WS_symbolName(WebsocketBase_symbolName):
|
||||
"""
|
||||
Websocket message structure for contract information updates identified by symbol name.
|
||||
|
||||
The ``channel`` of these messages is ``"contract-info"``.
|
||||
|
||||
Attributes:
|
||||
data (ContractInfo): Real-time contract information for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> # ``contract`` is the ``ContractInfo`` object from the example above.
|
||||
>>> ws_data: ContractInfo_WS_symbolName = {
|
||||
... "channel": "contract_info_updates",
|
||||
... "channel": "contract-info",
|
||||
... "symbolName": "FUT001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": contract
|
||||
@@ -1386,10 +1501,15 @@ class FundInfo(TypedDict):
|
||||
Represents key information about a fund, including its net asset value, total units,
|
||||
market capitalization, and the timestamp of the data.
|
||||
|
||||
Note:
|
||||
``as_of`` is annotated as ``datetime``, but a response decoded directly from JSON
|
||||
carries it as a plain JSON value (typically an ISO-formatted string). Convert it
|
||||
yourself if you need a ``datetime`` object.
|
||||
|
||||
Attributes:
|
||||
nav (float): Net Asset Value of the fund per unit.
|
||||
nav (float): Net Asset Value of the fund per unit, in IRR.
|
||||
units (int): Total number of fund units outstanding.
|
||||
marketCap (int): Total market capitalization of the fund.
|
||||
marketCap (int): Total market capitalization of the fund, in IRR.
|
||||
as_of (datetime): Timestamp indicating when the data was recorded.
|
||||
|
||||
Example:
|
||||
@@ -1419,6 +1539,7 @@ class FundInfoResponse(TypedDict):
|
||||
timestamp, version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``fund`` is the ``FundInfo`` object from the example above.
|
||||
>>> response: FundInfoResponse = {
|
||||
... "Data": {"IRFND123456": fund},
|
||||
... "Status": {
|
||||
@@ -1443,12 +1564,15 @@ class FundInfo_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
"""
|
||||
Websocket message structure for fund information updates identified by ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"fund-info"``.
|
||||
|
||||
Attributes:
|
||||
data (FundInfo): Real-time fund information for the specified fund.
|
||||
|
||||
Example:
|
||||
>>> # ``fund`` is the ``FundInfo`` object from the example above.
|
||||
>>> ws_data: FundInfo_WS_symbolIsin = {
|
||||
... "channel": "fund_info_updates",
|
||||
... "channel": "fund-info",
|
||||
... "symbolIsin": "IRFND123456",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": fund
|
||||
@@ -1463,12 +1587,15 @@ class FundInfo_WS_symbolName(WebsocketBase_symbolName):
|
||||
"""
|
||||
Websocket message structure for fund information updates identified by symbol name.
|
||||
|
||||
The ``channel`` of these messages is ``"fund-info"``.
|
||||
|
||||
Attributes:
|
||||
data (FundInfo): Real-time fund information for the specified fund.
|
||||
|
||||
Example:
|
||||
>>> # ``fund`` is the ``FundInfo`` object from the example above.
|
||||
>>> ws_data: FundInfo_WS_symbolName = {
|
||||
... "channel": "fund_info_updates",
|
||||
... "channel": "fund-info",
|
||||
... "symbolName": "FND001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": fund
|
||||
@@ -1485,6 +1612,9 @@ class OHLCV_live(TypedDict):
|
||||
"""
|
||||
Represents live OHLCV (Open, High, Low, Close, Volume) data for a financial instrument.
|
||||
|
||||
The data covers the last 1-minute interval (see the ``ohlcv-last-1m`` channel and
|
||||
``OHLCVLast1mResponse``). Prices are in IRR.
|
||||
|
||||
Attributes:
|
||||
open (float): Opening price of the instrument for the current interval.
|
||||
high (float): Highest price reached during the interval.
|
||||
@@ -1521,6 +1651,7 @@ class OHLCVLast1mResponse(TypedDict):
|
||||
timestamp, version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``ohlcv`` is the ``OHLCV_live`` object from the example above.
|
||||
>>> response: OHLCVLast1mResponse = {
|
||||
... "Data": {"IR0001234567": ohlcv},
|
||||
... "Status": {
|
||||
@@ -1545,12 +1676,15 @@ class OHLCV_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
"""
|
||||
Websocket message structure for live OHLCV updates identified by ISIN.
|
||||
|
||||
The ``channel`` of these messages is ``"ohlcv-last-1m"``.
|
||||
|
||||
Attributes:
|
||||
data (OHLCV_live): Real-time OHLCV data for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> # ``ohlcv`` is the ``OHLCV_live`` object from the example above.
|
||||
>>> ws_data: OHLCV_WS_symbolIsin = {
|
||||
... "channel": "ohlcv_updates",
|
||||
... "channel": "ohlcv-last-1m",
|
||||
... "symbolIsin": "IR0001234567",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": ohlcv
|
||||
@@ -1565,12 +1699,15 @@ class OHLCV_WS_symbolName(WebsocketBase_symbolName):
|
||||
"""
|
||||
Websocket message structure for live OHLCV updates identified by symbol name.
|
||||
|
||||
The ``channel`` of these messages is ``"ohlcv-last-1m"``.
|
||||
|
||||
Attributes:
|
||||
data (OHLCV_live): Real-time OHLCV data for the specified instrument.
|
||||
|
||||
Example:
|
||||
>>> # ``ohlcv`` is the ``OHLCV_live`` object from the example above.
|
||||
>>> ws_data: OHLCV_WS_symbolName = {
|
||||
... "channel": "ohlcv_updates",
|
||||
... "channel": "ohlcv-last-1m",
|
||||
... "symbolName": "ETF001",
|
||||
... "timestamp": "2025-11-19T10:30:00Z",
|
||||
... "data": ohlcv
|
||||
@@ -1592,12 +1729,14 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
|
||||
Inherits from `SecuritiesAndFunds` and extends it with additional real-time and aggregated metrics.
|
||||
|
||||
Attributes:
|
||||
BestLimit (Dict[str, BestLimitItem]): Best limit orders for this instrument by price level.
|
||||
BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
|
||||
for this instrument by price level ("1" best ... "6" deepest).
|
||||
Aggregate (Aggregate): Aggregated trading statistics for this instrument.
|
||||
institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
|
||||
between individual and institutional traders.
|
||||
FundInfo (FundInfo): Net asset value, total units, and market capitalization.
|
||||
ContractInfo (ContractInfo): Derivatives contract data (if applicable).
|
||||
FundInfo (FundInfo): Net asset value, total units, and market capitalization
|
||||
(intended for funds / ETFs).
|
||||
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
|
||||
|
||||
Example:
|
||||
>>> overview: OverviewSecuritiesAndFunds = {
|
||||
@@ -1630,7 +1769,7 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
|
||||
>>> overview["BestLimit"]["1"]["buy_price"]
|
||||
12000
|
||||
>>> overview["Aggregate"]["high_price"]
|
||||
12150
|
||||
12150.0
|
||||
>>> overview["FundInfo"]["nav"]
|
||||
12500.0
|
||||
"""
|
||||
@@ -1646,17 +1785,22 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
|
||||
|
||||
class OverviewTreasuryBonds(TreasuryBonds):
|
||||
"""
|
||||
Overview of a treasury bond instrument including best limit orders, aggregated market data,
|
||||
trading breakdown, fund info, and contract info.
|
||||
Overview of a treasury bond instrument: its static metadata (inherited from ``TreasuryBonds``) combined with
|
||||
live market data in a single object.
|
||||
|
||||
Inherits from `TreasuryBonds` and extends it with additional metrics.
|
||||
Inherits from `TreasuryBonds` and extends it with additional real-time and aggregated metrics.
|
||||
|
||||
Attributes:
|
||||
BestLimit (Dict[str, BestLimitItem])
|
||||
Aggregate (Aggregate)
|
||||
institutional_vs_individual (institutional_vs_individual)
|
||||
FundInfo (FundInfo)
|
||||
ContractInfo (ContractInfo)
|
||||
BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
|
||||
by price level ("1" best ... "6" deepest).
|
||||
Aggregate (Aggregate): Aggregated trading statistics.
|
||||
institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
|
||||
between individual and institutional traders.
|
||||
FundInfo (FundInfo): Net asset value, total units, and market capitalization
|
||||
(intended for funds / ETFs).
|
||||
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
|
||||
|
||||
See ``OverviewSecuritiesAndFunds`` for a complete example.
|
||||
"""
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
@@ -1670,17 +1814,22 @@ class OverviewTreasuryBonds(TreasuryBonds):
|
||||
|
||||
class OverviewStockOptions(StockOptions):
|
||||
"""
|
||||
Overview of a stock option instrument including best limit orders, aggregated market data,
|
||||
trading breakdown, fund info, and contract info.
|
||||
Overview of a stock option instrument: its static metadata (inherited from ``StockOptions``) combined with
|
||||
live market data in a single object.
|
||||
|
||||
Inherits from `StockOptions` and extends it with additional metrics.
|
||||
Inherits from `StockOptions` and extends it with additional real-time and aggregated metrics.
|
||||
|
||||
Attributes:
|
||||
BestLimit (Dict[str, BestLimitItem])
|
||||
Aggregate (Aggregate)
|
||||
institutional_vs_individual (institutional_vs_individual)
|
||||
FundInfo (FundInfo)
|
||||
ContractInfo (ContractInfo)
|
||||
BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
|
||||
by price level ("1" best ... "6" deepest).
|
||||
Aggregate (Aggregate): Aggregated trading statistics.
|
||||
institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
|
||||
between individual and institutional traders.
|
||||
FundInfo (FundInfo): Net asset value, total units, and market capitalization
|
||||
(intended for funds / ETFs).
|
||||
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
|
||||
|
||||
See ``OverviewSecuritiesAndFunds`` for a complete example.
|
||||
"""
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
@@ -1694,17 +1843,22 @@ class OverviewStockOptions(StockOptions):
|
||||
|
||||
class OverviewStockFuturess(StockFutures):
|
||||
"""
|
||||
Overview of a stock futures instrument including best limit orders, aggregated market data,
|
||||
trading breakdown, fund info, and contract info.
|
||||
Overview of a stock futures instrument: its static metadata (inherited from ``StockFutures``) combined with
|
||||
live market data in a single object.
|
||||
|
||||
Inherits from `StockFutures` and extends it with additional metrics.
|
||||
Inherits from `StockFutures` and extends it with additional real-time and aggregated metrics.
|
||||
|
||||
Attributes:
|
||||
BestLimit (Dict[str, BestLimitItem])
|
||||
Aggregate (Aggregate)
|
||||
institutional_vs_individual (institutional_vs_individual)
|
||||
FundInfo (FundInfo)
|
||||
ContractInfo (ContractInfo)
|
||||
BestLimit (Dict[Literal['1','2','3','4','5','6'], BestLimitItem]): Best limit orders
|
||||
by price level ("1" best ... "6" deepest).
|
||||
Aggregate (Aggregate): Aggregated trading statistics.
|
||||
institutional_vs_individual (institutional_vs_individual): Buy/sell activity breakdown
|
||||
between individual and institutional traders.
|
||||
FundInfo (FundInfo): Net asset value, total units, and market capitalization
|
||||
(intended for funds / ETFs).
|
||||
ContractInfo (ContractInfo): Open interest and margins (intended for futures / options).
|
||||
|
||||
See ``OverviewSecuritiesAndFunds`` for a complete example.
|
||||
"""
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
@@ -1720,6 +1874,10 @@ class OverviewResponse:
|
||||
"""
|
||||
Response structure for the comprehensive overview of multiple financial instruments.
|
||||
|
||||
The type of each entry can be recognized from its fields in the same way as for
|
||||
``Instruments`` (``optionType`` -> options, ``firstMargin`` -> futures,
|
||||
``baseVol`` -> bonds, ``baseVolume`` -> securities and funds).
|
||||
|
||||
Attributes:
|
||||
Data (Dict[str, Optional[Union[OverviewSecuritiesAndFunds, OverviewTreasuryBonds,
|
||||
OverviewStockOptions, OverviewStockFuturess]]]): Dictionary mapping instrument
|
||||
@@ -1729,6 +1887,7 @@ class OverviewResponse:
|
||||
version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``overview`` is the ``OverviewSecuritiesAndFunds`` object from the example above.
|
||||
>>> overview_response: OverviewResponse = {
|
||||
... "Data": {"IR0001234567": overview},
|
||||
... "Status": {
|
||||
@@ -1766,8 +1925,12 @@ class OHLCV_historical(TypedDict):
|
||||
Represents historical OHLCV (Open, High, Low, Close, Volume) data for a financial instrument
|
||||
over multiple timestamps.
|
||||
|
||||
Note:
|
||||
All lists have the same length and are index-aligned: element ``i`` of every
|
||||
list belongs to the same record. Prices are in IRR.
|
||||
|
||||
Attributes:
|
||||
Date_timestamp (List[int]): List of timestamps (in UNIX epoch format) for each OHLCV record.
|
||||
Date_timestamp (List[int]): List of timestamps (UNIX epoch, in seconds) for each OHLCV record.
|
||||
Open (List[Union[float, int]]): Opening prices corresponding to each timestamp.
|
||||
High (List[Union[float, int]]): Highest prices for each timestamp.
|
||||
Low (List[Union[float, int]]): Lowest prices for each timestamp.
|
||||
@@ -1807,12 +1970,17 @@ class OHLCVResponse(TypedDict):
|
||||
"""
|
||||
Response structure for historical OHLCV data from a REST API call.
|
||||
|
||||
Note:
|
||||
Unlike most other responses, ``Data`` is a single ``OHLCV_historical`` object for
|
||||
the requested instrument, not a dictionary keyed by instrument identifier.
|
||||
|
||||
Attributes:
|
||||
Data (OHLCV_historical): Historical OHLCV data for the specified instrument.
|
||||
Status (Status): Metadata about the server response, including success state, timestamp,
|
||||
version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``ohlcv_hist`` is the ``OHLCV_historical`` object from the example above.
|
||||
>>> response: OHLCVResponse = {
|
||||
... "Data": ohlcv_hist,
|
||||
... "Status": {
|
||||
@@ -1840,13 +2008,20 @@ class DividendAction(TypedDict):
|
||||
"""
|
||||
Represents a dividend distribution action for a financial instrument.
|
||||
|
||||
Note:
|
||||
Some field names are in Persian. In a dict literal they are written as normal
|
||||
string keys. Their values are strings as returned by the server, not numbers.
|
||||
|
||||
Attributes:
|
||||
Date_timestamp (int): Timestamp of the dividend action in UNIX epoch format.
|
||||
corporateAction (str): Type of corporate action (e.g., "Dividend").
|
||||
corporateAction (str): Type of corporate action (e.g., "Dividend"). Use it to tell
|
||||
``DividendAction`` and ``CapitalIncreaseAction`` apart.
|
||||
symbolName (str): Symbol name of the instrument.
|
||||
symbolIsin (str): ISIN identifier of the instrument.
|
||||
سود_تقسیم_شده (Optional[str]): Distributed dividend amount (may be None if not available).
|
||||
تاریخ (str): Human-readable date of the dividend action.
|
||||
سود_تقسیم_شده (Optional[str]): Distributed dividend ("سود تقسیم شده") as a string;
|
||||
None if not available.
|
||||
تاریخ (str): Human-readable date ("تاریخ") of the dividend action, as a string
|
||||
(format and calendar as provided by the server).
|
||||
|
||||
Example:
|
||||
>>> dividend: DividendAction = {
|
||||
@@ -1872,15 +2047,24 @@ class CapitalIncreaseAction(TypedDict):
|
||||
"""
|
||||
Represents a capital increase action for a financial instrument.
|
||||
|
||||
Note:
|
||||
Some field names are in Persian. In a dict literal they are written as normal
|
||||
string keys. Their values are strings as returned by the server, not numbers.
|
||||
|
||||
Attributes:
|
||||
Date_timestamp (int): Timestamp of the capital increase action in UNIX epoch format.
|
||||
corporateAction (str): Type of corporate action (e.g., "Capital Increase").
|
||||
corporateAction (str): Type of corporate action (e.g., "Capital Increase"). Use it to
|
||||
tell ``DividendAction`` and ``CapitalIncreaseAction`` apart.
|
||||
symbolName (str): Symbol name of the instrument.
|
||||
symbolIsin (str): ISIN identifier of the instrument.
|
||||
سرمایه_قبلی (Optional[str]): Previous capital amount (may be None if not available).
|
||||
سرمایه_جدید (Optional[str]): New capital amount after increase (may be None if not available).
|
||||
درصد_افزایش (Optional[str]): Percentage of capital increase (may be None if not available).
|
||||
تاریخ (str): Human-readable date of the capital increase action.
|
||||
سرمایه_قبلی (Optional[str]): Previous capital ("سرمایه قبلی") as a string; None if
|
||||
not available.
|
||||
سرمایه_جدید (Optional[str]): New capital after the increase ("سرمایه جدید") as a
|
||||
string; None if not available.
|
||||
درصد_افزایش (Optional[str]): Percentage of the capital increase ("درصد افزایش") as a
|
||||
string (it may include a "%" sign); None if not available.
|
||||
تاریخ (str): Human-readable date ("تاریخ") of the capital increase action, as a string
|
||||
(format and calendar as provided by the server).
|
||||
|
||||
Example:
|
||||
>>> capital_inc: CapitalIncreaseAction = {
|
||||
@@ -1914,10 +2098,12 @@ class CorporateActionResponse(TypedDict):
|
||||
Attributes:
|
||||
Data (List[Union[DividendAction, CapitalIncreaseAction, None]]): List of corporate action records.
|
||||
Each item may represent a dividend action, a capital increase action, or None if unavailable.
|
||||
Use ``corporateAction`` to tell them apart.
|
||||
Status (Status): Metadata about the server response, including success state, timestamp,
|
||||
version, author, description, and status code.
|
||||
|
||||
Example:
|
||||
>>> # ``dividend`` and ``capital_inc`` are the objects from the examples above.
|
||||
>>> response: CorporateActionResponse = {
|
||||
... "Data": [dividend, capital_inc, None],
|
||||
... "Status": {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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']
|
||||
@@ -1,4 +1,8 @@
|
||||
from .__tse_ifb import (
|
||||
EmsEngine_TseIfb_SyncClient,
|
||||
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
@@ -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
|
||||
order_status : Literal['InQueue','Cancelled','Broken','Settled']
|
||||
order_status : Literal['InQueue','PartiallyFilled','Cancelled','Broken','Settled']
|
||||
Price : int
|
||||
Volume : int
|
||||
RemainedVolume : int
|
||||
|
||||
+6
-4
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "HedgeTech"
|
||||
version = "0.3.0b2"
|
||||
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",
|
||||
@@ -60,4 +60,6 @@ dependencies = [
|
||||
[project.urls]
|
||||
Homepage = "https://hedgetech.ir/landing/"
|
||||
Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md"
|
||||
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
|
||||
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
|
||||
Store = "https://store.hedgetech.ir/"
|
||||
LinkedIn = "https://www.linkedin.com/company/hedgetech-ir/"
|
||||
Reference in new issue
Block a user