Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20d99ff661 | ||
|
|
115add658f | ||
|
|
57d2c7c8fd | ||
|
|
a0351324f9 | ||
|
|
3f936c17d7 | ||
|
|
71aeebfb44 | ||
|
|
0aa91d4e79 | ||
|
|
08244f17f2 | ||
|
|
4d775e9000 | ||
|
|
6c943a559c | ||
|
|
ed991a3035 | ||
|
|
52367d54e1 | ||
|
|
c8090ba334 | ||
|
|
854bee9f9e | ||
|
|
3a603db3cf | ||
|
|
3906a203a6 | ||
|
|
a49db4397c | ||
|
|
3d947bc558 | ||
|
|
2af7dfd648 | ||
|
|
bde8c980ef | ||
|
|
e63dcddbea | ||
|
|
cedbd76d0e | ||
|
|
52be955e6e | ||
|
|
ecc1070f1c | ||
|
|
126eab66f7 | ||
|
|
8a5f3142ef | ||
|
|
9cfd36a891 | ||
|
|
034c9a50ea | ||
|
|
17bea4f2a3 | ||
|
|
747b257432 | ||
|
|
e6bd5852c2 | ||
|
|
88359c882f | ||
|
|
420ebda323 | ||
|
|
83314e0074 | ||
|
|
f6132f8044 | ||
|
|
2b4e532708 | ||
|
|
db1001111a | ||
|
|
f3a9dd214b | ||
|
|
07ca759248 | ||
|
|
c9799fbd7f | ||
|
|
22f8ea17d6 | ||
|
|
440c7947cc | ||
|
|
312f230b08 | ||
|
|
aa4d4bbabb | ||
|
|
569a36edaa | ||
|
|
6b5e8ece84 | ||
|
|
74f2a1e857 | ||
|
|
870d660130 | ||
|
|
4de7e9b60a | ||
|
|
d96a32165d | ||
|
|
1d8fa8aac9 | ||
|
|
cb65c00066 | ||
|
|
02b63bc08e | ||
|
|
b04d690189 | ||
|
|
3e2dbfd381 |
No files matched your search
+3
-1
@@ -208,4 +208,6 @@ __marimo__/
|
||||
*.env*
|
||||
*.ipynb
|
||||
requirements.txt
|
||||
*test*.py
|
||||
*test*.py
|
||||
|
||||
.vscode
|
||||
@@ -2,6 +2,7 @@
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from .__utils import RetriableAsyncClient
|
||||
from httpx import (
|
||||
AsyncClient ,
|
||||
Timeout ,
|
||||
@@ -16,12 +17,36 @@ class AuthAsyncClient:
|
||||
"""
|
||||
Asynchronous client for interacting with the HedgeTech API using JWT-based authentication.
|
||||
|
||||
This class provides a high-level interface to authenticate users, manage JWT tokens,
|
||||
This class provides a high-level interface to authenticate users, manage JWT tokens,
|
||||
and make authorized HTTP requests using an `httpx.AsyncClient`.
|
||||
|
||||
Normally an instance is created with ``AuthAsyncClient.login(...)``. Calling the
|
||||
constructor directly is only useful when you already have a configured HTTP client and
|
||||
a valid token. The resulting object is what the data clients
|
||||
(``DataEngine_Ime_AsyncClient``, ``DataEngine_TseIfb_AsyncClient``) receive: they use
|
||||
``httpx_Client`` for REST requests and ``token`` as the WebSocket headers.
|
||||
|
||||
Note:
|
||||
* The client does not refresh the token. When the JWT expires, requests start to
|
||||
fail and you need to call ``login`` again to get a new client.
|
||||
* ``Permissions`` is decoded WITHOUT verifying the signature or the expiry, so it is
|
||||
only meant for reading the claims (e.g. to display them), never for making
|
||||
security decisions.
|
||||
|
||||
Attributes:
|
||||
httpx_Client (AsyncClient): An instance of `httpx.AsyncClient` configured with authentication headers.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'.
|
||||
httpx_Client (AsyncClient): The HTTP client used for authorized requests. When created
|
||||
by ``login`` it is a ``RetriableAsyncClient`` (a wrapper around ``httpx.AsyncClient``
|
||||
that retries failed requests, up to 10 times) configured with:
|
||||
|
||||
- the authentication headers (the token returned by the server plus an ``origin``
|
||||
header) and the cookies received at login;
|
||||
- HTTP/2 only (``http1=False``, ``http2=True``) with TLS verification enabled;
|
||||
- short timeouts: connect 0.25 s, read 1.5 s, write 1.5 s, pool 0.25 s.
|
||||
token (dict[str, str]): Dictionary containing the authentication tokens. It must contain
|
||||
the ``'Authorization'`` key holding the JWT string. It is also passed as the
|
||||
``additional_headers`` of WebSocket connections.
|
||||
Permissions (dict): The decoded JWT payload (its claims), set by ``UpdatePermission``
|
||||
when the object is created. The available claims depend on the server.
|
||||
|
||||
Example:
|
||||
>>> client = await AuthAsyncClient.login(
|
||||
@@ -32,8 +57,9 @@ class AuthAsyncClient:
|
||||
'eyJ0eXAiOi'
|
||||
>>> client.Permissions # Decoded JWT payload
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
>>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=client)
|
||||
"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
@@ -43,40 +69,70 @@ class AuthAsyncClient:
|
||||
"""
|
||||
Initialize the AuthAsyncClient with an existing httpx.AsyncClient and authentication token.
|
||||
|
||||
Both arguments are keyword-only. The token is decoded immediately (see
|
||||
``UpdatePermission``), so ``Permissions`` is available right after construction.
|
||||
|
||||
Args:
|
||||
httpx_Client (AsyncClient): Preconfigured AsyncClient for making authorized requests.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens.
|
||||
It should already send the authentication headers (``login`` does this for you).
|
||||
token (dict[str, str]): Dictionary containing authentication tokens. It must contain
|
||||
the ``'Authorization'`` key with the JWT string.
|
||||
|
||||
Raises:
|
||||
ValueError: If the token cannot be decoded (see ``UpdatePermission``).
|
||||
|
||||
Example:
|
||||
>>> client = AuthAsyncClient(
|
||||
... httpx_Client=my_httpx_client,
|
||||
... token={"Authorization": "<jwt>"}
|
||||
... )
|
||||
>>> client.Permissions
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
"""
|
||||
|
||||
|
||||
self.httpx_Client : AsyncClient = httpx_Client
|
||||
self.token : dict[str,str] = token
|
||||
|
||||
|
||||
self.UpdatePermission
|
||||
|
||||
|
||||
|
||||
|
||||
@property
|
||||
def UpdatePermission(self)-> None:
|
||||
|
||||
|
||||
"""
|
||||
Decodes the JWT 'Authorization' token to extract user permissions.
|
||||
|
||||
This is a **property**, not a method: reading ``client.UpdatePermission`` (without
|
||||
parentheses) performs the work and returns ``None``. It is read once in ``__init__``;
|
||||
read it again to re-decode ``token`` after you replace it.
|
||||
|
||||
The decoded payload is stored in ``self.Permissions``. The token is decoded
|
||||
WITHOUT verifying the signature, and the expiry (``exp``) is not checked either.
|
||||
|
||||
Raises:
|
||||
ValueError: If the JWT cannot be decoded.
|
||||
ValueError: If the JWT cannot be decoded. Any underlying error is wrapped in
|
||||
``ValueError``, including a missing ``'Authorization'`` key in ``token``.
|
||||
|
||||
Example:
|
||||
>>> client.token = new_token
|
||||
>>> client.UpdatePermission # no parentheses; re-decodes the token
|
||||
>>> client.Permissions
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
"""
|
||||
|
||||
try :
|
||||
|
||||
|
||||
try :
|
||||
|
||||
self.Permissions = decode(
|
||||
jwt=self.token['Authorization'].encode(),
|
||||
algorithms='HS256',
|
||||
options={"verify_signature": False},
|
||||
)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
|
||||
|
||||
raise ValueError(e)
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
async def login(
|
||||
cls,
|
||||
@@ -84,22 +140,37 @@ class AuthAsyncClient:
|
||||
UserName_or_Email : str,
|
||||
Password : str
|
||||
)-> "AuthAsyncClient":
|
||||
|
||||
|
||||
"""
|
||||
Authenticate a user and return an instance of `AuthAsyncClient`.
|
||||
|
||||
This method performs the login request to the HedgeTech API, retrieves JWT tokens,
|
||||
and configures an `httpx.AsyncClient` with authentication headers and cookies.
|
||||
|
||||
It sends ``POST https://core.hedgetech.ir/auth/user/token/issue`` with the credentials as
|
||||
form data. The login succeeds only when the server answers with HTTP status ``201``.
|
||||
The JSON body of that answer is used as ``token`` and is also sent as headers on every
|
||||
later request, together with an ``origin: https://core.hedgetech.ir`` header. The cookies
|
||||
set at login are kept.
|
||||
|
||||
Args:
|
||||
UserName_or_Email (str): The username or email of the user.
|
||||
Password (str): The user's password.
|
||||
|
||||
Returns:
|
||||
AuthAsyncClient: An initialized client ready to make authorized requests.
|
||||
AuthAsyncClient: An initialized client ready to make authorized requests. Its
|
||||
``httpx_Client`` is a ``RetriableAsyncClient`` (10 retries) using HTTP/2 with the
|
||||
short timeouts described in the class docstring.
|
||||
|
||||
Raises:
|
||||
ValueError: If the login attempt fails (e.g., wrong credentials).
|
||||
ValueError: If the login attempt fails (e.g., wrong credentials), i.e. the status is
|
||||
not ``201``. The message is the server's ``detail`` field, which is ``None`` if
|
||||
the server did not send one. The same exception is raised if the token returned
|
||||
by the server cannot be decoded (see ``UpdatePermission``).
|
||||
|
||||
Note:
|
||||
Network errors while sending the login request (for example a connection failure or
|
||||
timeout) are raised by ``httpx`` as they are and are not converted to ``ValueError``.
|
||||
|
||||
Example:
|
||||
>>> client = await AuthAsyncClient.login(
|
||||
@@ -109,9 +180,9 @@ class AuthAsyncClient:
|
||||
>>> client.token['Authorization'][:10]
|
||||
'eyJ0eXAiOi'
|
||||
"""
|
||||
|
||||
|
||||
httpx_Client = AsyncClient(verify=True ,http1=False ,http2=True)
|
||||
|
||||
|
||||
login_res = await httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/auth/user/token/issue',
|
||||
data={
|
||||
@@ -119,32 +190,35 @@ class AuthAsyncClient:
|
||||
'Password' : Password
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if login_res.status_code == 201:
|
||||
|
||||
|
||||
token = login_res.json()
|
||||
headers = {'origin' : 'https://core.hedgetech.ir'}
|
||||
headers.update(token)
|
||||
|
||||
httpx_Client = AsyncClient(
|
||||
verify=True ,
|
||||
http1=False ,
|
||||
http2=True ,
|
||||
headers=headers,
|
||||
cookies=httpx_Client.cookies,
|
||||
timeout=Timeout(
|
||||
connect=.5,
|
||||
read=1,
|
||||
write=1,
|
||||
pool=.5,
|
||||
|
||||
httpx_Client = RetriableAsyncClient(
|
||||
client = AsyncClient(
|
||||
verify=True ,
|
||||
http1=False ,
|
||||
http2=True ,
|
||||
headers=headers,
|
||||
cookies=httpx_Client.cookies,
|
||||
timeout=Timeout(
|
||||
connect=.250,
|
||||
read=1.5,
|
||||
write=1.5,
|
||||
pool=.250,
|
||||
),
|
||||
),
|
||||
retries= 10
|
||||
)
|
||||
|
||||
|
||||
return cls(
|
||||
httpx_Client = httpx_Client,
|
||||
token = token
|
||||
)
|
||||
|
||||
|
||||
else :
|
||||
|
||||
|
||||
raise ValueError(login_res.json().get('detail'))
|
||||
@@ -2,6 +2,7 @@
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from .__utils import RetriableSyncClient
|
||||
from httpx import (
|
||||
Client ,
|
||||
Timeout ,
|
||||
@@ -17,12 +18,39 @@ class AuthSyncClient:
|
||||
"""
|
||||
Synchronous client for interacting with the HedgeTech API using JWT-based authentication.
|
||||
|
||||
This class provides a high-level interface to authenticate users, manage JWT tokens,
|
||||
This class provides a high-level interface to authenticate users, manage JWT tokens,
|
||||
and make authorized HTTP requests using an `httpx.Client`.
|
||||
|
||||
This is the blocking twin of ``AuthAsyncClient``: same login endpoint, token handling and
|
||||
configuration, only the calling style differs (plain calls instead of ``await``).
|
||||
|
||||
Normally an instance is created with ``AuthSyncClient.login(...)``. Calling the
|
||||
constructor directly is only useful when you already have a configured HTTP client and
|
||||
a valid token. The resulting object is what the data clients
|
||||
(``DataEngine_Ime_SyncClient``, ``DataEngine_TseIfb_SyncClient``) receive: they use
|
||||
``httpx_Client`` for REST requests and ``token`` as the WebSocket headers.
|
||||
|
||||
Note:
|
||||
* The client does not refresh the token. When the JWT expires, requests start to
|
||||
fail and you need to call ``login`` again to get a new client.
|
||||
* ``Permissions`` is decoded WITHOUT verifying the signature or the expiry, so it is
|
||||
only meant for reading the claims (e.g. to display them), never for making
|
||||
security decisions.
|
||||
|
||||
Attributes:
|
||||
httpx_Client (Client): An instance of `httpx.Client` configured with authentication headers.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'.
|
||||
httpx_Client (Client): The HTTP client used for authorized requests. When created
|
||||
by ``login`` it is a ``RetriableSyncClient`` (a wrapper around ``httpx.Client``
|
||||
that retries failed requests, up to 10 times) configured with:
|
||||
|
||||
- the authentication headers (the token returned by the server plus an ``origin``
|
||||
header) and the cookies received at login;
|
||||
- HTTP/2 only (``http1=False``, ``http2=True``) with TLS verification enabled;
|
||||
- short timeouts: connect 0.25 s, read 1.5 s, write 1.5 s, pool 0.25 s.
|
||||
token (dict[str, str]): Dictionary containing the authentication tokens. It must contain
|
||||
the ``'Authorization'`` key holding the JWT string. It is also passed as the
|
||||
``additional_headers`` of WebSocket connections.
|
||||
Permissions (dict): The decoded JWT payload (its claims), set by ``UpdatePermission``
|
||||
when the object is created. The available claims depend on the server.
|
||||
|
||||
Example:
|
||||
>>> client = AuthSyncClient.login(
|
||||
@@ -33,8 +61,9 @@ class AuthSyncClient:
|
||||
'eyJ0eXAiOi'
|
||||
>>> client.Permissions # Decoded JWT payload
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
>>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=client)
|
||||
"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
@@ -44,40 +73,70 @@ class AuthSyncClient:
|
||||
"""
|
||||
Initialize the AuthSyncClient with an existing httpx.Client and authentication token.
|
||||
|
||||
Both arguments are keyword-only. The token is decoded immediately (see
|
||||
``UpdatePermission``), so ``Permissions`` is available right after construction.
|
||||
|
||||
Args:
|
||||
httpx_Client (Client): Preconfigured Client for making authorized requests.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens.
|
||||
"""
|
||||
|
||||
It should already send the authentication headers (``login`` does this for you).
|
||||
token (dict[str, str]): Dictionary containing authentication tokens. It must contain
|
||||
the ``'Authorization'`` key with the JWT string.
|
||||
|
||||
Raises:
|
||||
ValueError: If the token cannot be decoded (see ``UpdatePermission``).
|
||||
|
||||
Example:
|
||||
>>> client = AuthSyncClient(
|
||||
... httpx_Client=my_httpx_client,
|
||||
... token={"Authorization": "<jwt>"}
|
||||
... )
|
||||
>>> client.Permissions
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
"""
|
||||
|
||||
self.httpx_Client : Client = httpx_Client
|
||||
self.token : dict[str,str] = token
|
||||
|
||||
|
||||
self.UpdatePermission
|
||||
|
||||
|
||||
|
||||
@property
|
||||
def UpdatePermission(self)-> None:
|
||||
|
||||
|
||||
"""
|
||||
Decodes the JWT 'Authorization' token to extract user permissions.
|
||||
|
||||
This is a **property**, not a method: reading ``client.UpdatePermission`` (without
|
||||
parentheses) performs the work and returns ``None``. It is read once in ``__init__``;
|
||||
read it again to re-decode ``token`` after you replace it.
|
||||
|
||||
The decoded payload is stored in ``self.Permissions``. The token is decoded
|
||||
WITHOUT verifying the signature, and the expiry (``exp``) is not checked either.
|
||||
|
||||
Raises:
|
||||
ValueError: If the JWT cannot be decoded.
|
||||
ValueError: If the JWT cannot be decoded. Any underlying error is wrapped in
|
||||
``ValueError``, including a missing ``'Authorization'`` key in ``token``.
|
||||
|
||||
Example:
|
||||
>>> client.token = new_token
|
||||
>>> client.UpdatePermission # no parentheses; re-decodes the token
|
||||
>>> client.Permissions
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
"""
|
||||
|
||||
try :
|
||||
|
||||
|
||||
try :
|
||||
|
||||
self.Permissions = decode(
|
||||
jwt=self.token['Authorization'].encode(),
|
||||
algorithms='HS256',
|
||||
options={"verify_signature": False},
|
||||
)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
|
||||
|
||||
raise ValueError(e)
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def login(
|
||||
cls,
|
||||
@@ -85,22 +144,37 @@ class AuthSyncClient:
|
||||
UserName_or_Email : str,
|
||||
Password : str
|
||||
)-> "AuthSyncClient":
|
||||
|
||||
|
||||
"""
|
||||
Authenticate a user synchronously and return an instance of `AuthSyncClient`.
|
||||
|
||||
This method performs the login request to the HedgeTech API, retrieves JWT tokens,
|
||||
and configures an `httpx.Client` with authentication headers and cookies.
|
||||
|
||||
It sends ``POST https://core.hedgetech.ir/auth/user/token/issue`` with the credentials as
|
||||
form data. The login succeeds only when the server answers with HTTP status ``201``.
|
||||
The JSON body of that answer is used as ``token`` and is also sent as headers on every
|
||||
later request, together with an ``origin: https://core.hedgetech.ir`` header. The cookies
|
||||
set at login are kept.
|
||||
|
||||
Args:
|
||||
UserName_or_Email (str): The username or email of the user.
|
||||
Password (str): The user's password.
|
||||
|
||||
Returns:
|
||||
AuthSyncClient: An initialized client ready to make authorized requests.
|
||||
AuthSyncClient: An initialized client ready to make authorized requests. Its
|
||||
``httpx_Client`` is a ``RetriableSyncClient`` (10 retries) using HTTP/2 with the
|
||||
short timeouts described in the class docstring.
|
||||
|
||||
Raises:
|
||||
ValueError: If the login attempt fails (e.g., wrong credentials).
|
||||
ValueError: If the login attempt fails (e.g., wrong credentials), i.e. the status is
|
||||
not ``201``. The message is the server's ``detail`` field, which is ``None`` if
|
||||
the server did not send one. The same exception is raised if the token returned
|
||||
by the server cannot be decoded (see ``UpdatePermission``).
|
||||
|
||||
Note:
|
||||
Network errors while sending the login request (for example a connection failure or
|
||||
timeout) are raised by ``httpx`` as they are and are not converted to ``ValueError``.
|
||||
|
||||
Example:
|
||||
>>> client = AuthSyncClient.login(
|
||||
@@ -110,10 +184,10 @@ class AuthSyncClient:
|
||||
>>> client.token['Authorization'][:10]
|
||||
'eyJ0eXAiOi'
|
||||
"""
|
||||
|
||||
|
||||
httpx_Client = Client(verify=True ,http1=False ,http2=True)
|
||||
|
||||
|
||||
|
||||
|
||||
login_res = httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/auth/user/token/issue',
|
||||
data={
|
||||
@@ -121,33 +195,36 @@ class AuthSyncClient:
|
||||
'Password' : Password
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
|
||||
if login_res.status_code == 201:
|
||||
|
||||
|
||||
token = login_res.json()
|
||||
headers = {'origin' : 'https://core.hedgetech.ir'}
|
||||
headers.update(token)
|
||||
|
||||
httpx_Client = Client(
|
||||
verify=True ,
|
||||
http1=False ,
|
||||
http2=True ,
|
||||
headers=headers,
|
||||
cookies=httpx_Client.cookies,
|
||||
timeout=Timeout(
|
||||
connect=.5,
|
||||
read=1,
|
||||
write=1,
|
||||
pool=.5,
|
||||
|
||||
httpx_Client = RetriableSyncClient(
|
||||
client = Client(
|
||||
verify=True ,
|
||||
http1=False ,
|
||||
http2=True ,
|
||||
headers=headers,
|
||||
cookies=httpx_Client.cookies,
|
||||
timeout=Timeout(
|
||||
connect=.250,
|
||||
read=1.5,
|
||||
write=1.5,
|
||||
pool=.250,
|
||||
),
|
||||
),
|
||||
retries= 10
|
||||
)
|
||||
|
||||
|
||||
return cls(
|
||||
httpx_Client = httpx_Client,
|
||||
token = login_res.json()
|
||||
token = token
|
||||
)
|
||||
|
||||
|
||||
else :
|
||||
|
||||
|
||||
raise ValueError(login_res.json().get('detail'))
|
||||
@@ -0,0 +1,63 @@
|
||||
# ========================================|======================================== #
|
||||
# Exports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
__all__ = [
|
||||
'RetriableAsyncClient'
|
||||
]
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from httpx import (
|
||||
AsyncClient,
|
||||
|
||||
ConnectTimeout,
|
||||
PoolTimeout,
|
||||
ReadTimeout,
|
||||
WriteTimeout,
|
||||
)
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
|
||||
class RetriableAsyncClient:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client: AsyncClient,
|
||||
retries: int = 10,
|
||||
)-> AsyncClient:
|
||||
|
||||
self._client = client
|
||||
self._retries = retries
|
||||
|
||||
async def _request(self, method: str, **kwargs):
|
||||
attempt = self._retries
|
||||
|
||||
while True:
|
||||
try:
|
||||
return await getattr(self._client, method)(**kwargs)
|
||||
|
||||
except (
|
||||
ConnectTimeout,
|
||||
PoolTimeout,
|
||||
ReadTimeout,
|
||||
WriteTimeout,
|
||||
):
|
||||
if attempt <= 0:
|
||||
raise
|
||||
attempt -= 1
|
||||
|
||||
def __getattr__(self, name: str):
|
||||
attr = getattr(self._client, name)
|
||||
|
||||
if name in {"get", "post", "put", "delete", "patch", "options", "head"}:
|
||||
async def wrapper(**kwargs):
|
||||
return await self._request(name, **kwargs)
|
||||
return wrapper
|
||||
|
||||
return attr
|
||||
@@ -0,0 +1,65 @@
|
||||
# ========================================|======================================== #
|
||||
# Exports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
__all__ = [
|
||||
'RetriableSyncClient'
|
||||
]
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from httpx import (
|
||||
Client,
|
||||
|
||||
ConnectTimeout,
|
||||
PoolTimeout,
|
||||
ReadTimeout,
|
||||
WriteTimeout,
|
||||
)
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
|
||||
class RetriableSyncClient:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client: Client,
|
||||
retries: int = 10,
|
||||
)-> Client:
|
||||
|
||||
self._client = client
|
||||
self._retries = retries
|
||||
|
||||
def _request(self, method: str, **kwargs):
|
||||
attempt = self._retries
|
||||
|
||||
while True:
|
||||
try:
|
||||
return getattr(self._client, method)(**kwargs)
|
||||
|
||||
except (
|
||||
ConnectTimeout,
|
||||
PoolTimeout,
|
||||
ReadTimeout,
|
||||
WriteTimeout,
|
||||
):
|
||||
if attempt <= 0:
|
||||
raise
|
||||
attempt -= 1
|
||||
|
||||
def __getattr__(self, name: str):
|
||||
|
||||
attr = getattr(self._client, name)
|
||||
|
||||
if name in {"get", "post", "put", "delete", "patch", "options", "head"}:
|
||||
|
||||
def wrapper(**kwargs):
|
||||
return self._request(name, **kwargs)
|
||||
return wrapper
|
||||
|
||||
return attr
|
||||
@@ -0,0 +1,2 @@
|
||||
from .__RetriableAsyncClient import *
|
||||
from .__RetriableSyncClient import *
|
||||
@@ -0,0 +1,868 @@
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from asyncio import (
|
||||
Event,
|
||||
wait_for,
|
||||
TimeoutError,
|
||||
sleep,
|
||||
)
|
||||
from websockets.asyncio.client import connect
|
||||
from json import loads
|
||||
from HedgeTech.Auth import AuthAsyncClient
|
||||
from typing import (
|
||||
Literal,
|
||||
List,
|
||||
AsyncGenerator,
|
||||
)
|
||||
from .__io_types import (
|
||||
WebsocketBase_contractName,
|
||||
WebsocketBase_contractId,
|
||||
|
||||
OverviewResponse,
|
||||
Contracts,
|
||||
|
||||
ContractInfoResponse,
|
||||
AllowedPriceRangeResponse,
|
||||
AggregateResponse,
|
||||
BestLimitResponse,
|
||||
)
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
class DataEngine_Ime_AsyncClient:
|
||||
"""
|
||||
Asynchronous client for the HedgeTech Data Engine (Iran Mercantile Exchange - IME).
|
||||
|
||||
This client wraps the IME endpoints of the HedgeTech Data Engine
|
||||
(``core.hedgetech.ir/data-engine/ime``) and exposes them as ``async`` methods.
|
||||
All requests are sent through the authenticated ``httpx`` client held by the
|
||||
``AuthAsyncClient`` passed to the constructor, so the caller never handles tokens
|
||||
manually.
|
||||
|
||||
The endpoints are grouped into three families:
|
||||
|
||||
1. **Static data** (contract metadata that rarely changes):
|
||||
``search_contracts``, ``contracts_static_info_by_name``,
|
||||
``contracts_static_info_by_id`` -> return ``Contracts``.
|
||||
|
||||
2. **Live snapshots** (one-shot REST requests for the current market state):
|
||||
``live_overview_by_*``, ``live_best_limit_by_*``, ``live_aggregate_by_*``,
|
||||
``live_contract_info_by_*``, ``live_allowed_price_range_by_*``.
|
||||
|
||||
3. **Live streams** (continuous WebSocket push of full market snapshots):
|
||||
``websocket_by_name``, ``websocket_by_id``.
|
||||
|
||||
Every REST method (except ``search_contracts``) exists in two variants:
|
||||
|
||||
* ``*_by_name`` - contracts are identified by ``contractName``
|
||||
(e.g. ``"KASH05C170"``).
|
||||
* ``*_by_id`` - contracts are identified by ``contractId``
|
||||
(e.g. ``"123456789"``; ``int`` values are accepted and sent as text).
|
||||
|
||||
Every REST response is the raw JSON body returned by the server, typed with the
|
||||
response structures from ``__io_types``. Each response contains a ``Data`` section
|
||||
and a ``Status`` section (see ``Status``). Whenever the HTTP status is not a
|
||||
success, the method raises ``ValueError`` carrying the server's ``detail`` message.
|
||||
|
||||
Note:
|
||||
Prices, volumes and values follow the conventions documented in
|
||||
``__io_types`` (prices in IRR; commissions, margins and taxes as fractions,
|
||||
e.g. ``0.0025`` = 0.25%).
|
||||
|
||||
Attributes:
|
||||
__AuthAsyncClient (AuthAsyncClient): The authenticated client used for all
|
||||
HTTP requests (via ``httpx_Client``) and for the WebSocket auth headers
|
||||
(via ``token``). Stored privately (name-mangled).
|
||||
|
||||
Example:
|
||||
>>> auth = AuthAsyncClient(...)
|
||||
>>> client = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
|
||||
>>> response = await client.live_best_limit_by_name(["KASH05C170"])
|
||||
>>> response['Data']['KASH05C170']['1']['buy_price']
|
||||
35200
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthAsyncClient : AuthAsyncClient,
|
||||
):
|
||||
"""
|
||||
Create a new IME Data Engine client.
|
||||
|
||||
Args:
|
||||
AuthAsyncClient (AuthAsyncClient): An already authenticated HedgeTech
|
||||
client. Its ``httpx_Client`` is used for every REST call and its
|
||||
``token`` is used as the header set for WebSocket connections.
|
||||
|
||||
Example:
|
||||
>>> client = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
|
||||
"""
|
||||
|
||||
self.__AuthAsyncClient = AuthAsyncClient
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def search_contracts(
|
||||
self,
|
||||
market : Literal[
|
||||
"IMEDepositCertificate",
|
||||
"IMEFutures",
|
||||
"IMEOption",
|
||||
],
|
||||
Search_char : str,
|
||||
)-> Contracts :
|
||||
"""
|
||||
Search IME contracts of a given market by a text fragment.
|
||||
|
||||
Sends ``GET /data-engine/ime/static/data/contract/search`` and returns the
|
||||
static metadata of the matching contracts.
|
||||
|
||||
Args:
|
||||
market (Literal["IMEDepositCertificate", "IMEFutures", "IMEOption"]):
|
||||
The market (instrument class) to search in. It decides which
|
||||
structure the items in the result have:
|
||||
``IMEDepositCertificate`` -> ``IMEDepositCertificate``,
|
||||
``IMEFutures`` -> ``IMEFutures``, ``IMEOption`` -> ``IMEOption``.
|
||||
Search_char (str): The text to search for (e.g. part of a contract name
|
||||
such as ``"KASH05C"``).
|
||||
|
||||
Returns:
|
||||
Contracts: ``{"Data": [...], "Status": {...}}`` where ``Data`` is the
|
||||
list of matching instruments (static metadata only, no live prices).
|
||||
Use the returned ``contractName`` / ``contractId`` values with the
|
||||
other methods of this client.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.search_contracts(
|
||||
... market="IMEOption",
|
||||
... Search_char="KASH05C",
|
||||
... )
|
||||
>>> [item['contractName'] for item in response['Data'] if item]
|
||||
['KASH05C170', 'KASH05C180']
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search',
|
||||
params={
|
||||
'market' : market,
|
||||
'Search_char' : Search_char
|
||||
}
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def contracts_static_info_by_name(self,contract_names : List[str])-> Contracts:
|
||||
"""
|
||||
Get the static metadata of contracts identified by contract name.
|
||||
|
||||
Sends ``GET /data-engine/ime/static/data/contract/name`` with one
|
||||
``contract_names`` query parameter per name.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up
|
||||
(e.g. ``["KASH05C170", "KASH05P170"]``).
|
||||
|
||||
Returns:
|
||||
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in
|
||||
``Data`` is an ``IMEOption``, ``IMEFutures`` or
|
||||
``IMEDepositCertificate`` structure, or ``None`` when no
|
||||
instrument was found for the corresponding name.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status.
|
||||
The message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.contracts_static_info_by_name(["KASH05C170"])
|
||||
>>> response['Data'][0]['strikePrice']
|
||||
170000.0
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def contracts_static_info_by_id(self,contract_ids : List[str | int])-> Contracts:
|
||||
"""
|
||||
Get the static metadata of contracts identified by contract ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/static/data/contract/id`` with one
|
||||
``contract_ids`` query parameter per ID.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up
|
||||
(e.g. ``["123456789", 987654321]``).
|
||||
|
||||
Returns:
|
||||
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in ``Data`` is
|
||||
an ``IMEOption``, ``IMEFutures`` or ``IMEDepositCertificate``
|
||||
structure, or ``None`` when no instrument was found for the
|
||||
corresponding ID.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.contracts_static_info_by_id(["123456789"])
|
||||
>>> response['Data'][0]['contractName']
|
||||
'KASH05C170'
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_overview_by_name(self,contract_names : List[str])-> OverviewResponse:
|
||||
"""
|
||||
Get the live market overview of contracts identified by contract name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/overview/contract/name``. The overview
|
||||
combines each contract's static metadata with its live ``BestLimit``,
|
||||
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo`` sections in a single
|
||||
request.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every requested contract name to an ``OverviewIMEOption``,
|
||||
``OverviewIMEFutures`` or ``OverviewIMEDepositCertificate``
|
||||
structure, or to ``None`` if the contract was not found.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_overview_by_name(["KASH05C170"])
|
||||
>>> overview = response['Data']['KASH05C170']
|
||||
>>> if overview:
|
||||
... print(overview['Aggregate']['last_price'])
|
||||
35250.0
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_overview_by_id(self,contract_ids : List[str | int])-> OverviewResponse:
|
||||
"""
|
||||
Get the live market overview of contracts identified by contract ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/overview/contract/id``. Same content
|
||||
as ``live_overview_by_name`` (static metadata + live ``BestLimit``,
|
||||
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo``), but the keys of
|
||||
``Data`` are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every requested contract ID to its overview structure, or to
|
||||
``None`` if the contract was not found.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_overview_by_id(["123456789"])
|
||||
>>> overview = response['Data']['123456789']
|
||||
>>> if overview:
|
||||
... print(overview['BestLimit']['1']['buy_price'])
|
||||
35200
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_best_limit_by_name(self,contract_names : List[str])-> BestLimitResponse:
|
||||
"""
|
||||
Get the live best-limit order book of contracts identified by contract name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/best-limit/contract/name``.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract name to its order book, a dictionary with up to three
|
||||
levels (``"1"`` best, ``"2"``, ``"3"``), each a ``BestLimitItem``
|
||||
(``buy_quantity``, ``buy_price``, ``sell_quantity``, ``sell_price``).
|
||||
Empty sides carry zero values, so check that a price is greater than
|
||||
zero before using it.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_best_limit_by_name(["KASH05C170"])
|
||||
>>> level = response['Data']['KASH05C170']['1']
|
||||
>>> if level['buy_price'] > 0 and level['sell_price'] > 0:
|
||||
... print(level['sell_price'] - level['buy_price'])
|
||||
100
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_best_limit_by_id(self,contract_ids : List[str | int])-> BestLimitResponse:
|
||||
"""
|
||||
Get the live best-limit order book of contracts identified by contract ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/best-limit/contract/id``. Same content
|
||||
as ``live_best_limit_by_name`` but the keys of ``Data`` are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract ID to its order book levels (``"1"``, ``"2"``,
|
||||
``"3"``), each a ``BestLimitItem``. Empty sides carry zero values.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_best_limit_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['1']['sell_price']
|
||||
35300
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_aggregate_by_name(self,contract_names : List[str])-> AggregateResponse:
|
||||
"""
|
||||
Get the live aggregate trading statistics of contracts identified by name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/aggregate/contract/name``.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract name to an ``Aggregate`` structure: ``date``,
|
||||
``time``, ``trade_count``, ``total_volume``, ``total_value`` (IRR),
|
||||
and the OHLC-style prices ``open_price``, ``high_price``,
|
||||
``low_price``, ``last_price``, ``closing_price`` and
|
||||
``previous_close``.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_aggregate_by_name(["KASH05C170"])
|
||||
>>> agg = response['Data']['KASH05C170']
|
||||
>>> (agg['closing_price'] - agg['previous_close']) / agg['previous_close'] * 100
|
||||
0.8
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
async def live_aggregate_by_id(self,contract_ids : List[str | int])-> AggregateResponse :
|
||||
"""
|
||||
Get the live aggregate trading statistics of contracts identified by ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/aggregate/contract/id``. Same content
|
||||
as ``live_aggregate_by_name`` but the keys of ``Data`` are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract ID to an ``Aggregate`` structure (trade count, volume,
|
||||
value and OHLC-style prices).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_aggregate_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['last_price']
|
||||
35250.0
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_contract_info_by_name(self,contract_names : List[str])-> ContractInfoResponse:
|
||||
"""
|
||||
Get the live contract information (open interest) of contracts by name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/contract-info/contract/name``.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract name to a ``ContractInfo`` structure with
|
||||
``open_interest`` (number of open positions) and
|
||||
``open_interest_changes`` (change versus the previous period;
|
||||
positive = increase, negative = decrease).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_contract_info_by_name(["KASH05C170"])
|
||||
>>> response['Data']['KASH05C170']['open_interest']
|
||||
15000
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
async def live_contract_info_by_id(self,contract_ids : List[str | int])-> ContractInfoResponse :
|
||||
"""
|
||||
Get the live contract information (open interest) of contracts by ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/contract-info/contract/id``. Same
|
||||
content as ``live_contract_info_by_name`` but the keys of ``Data`` are
|
||||
contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract ID to a ``ContractInfo`` structure (``open_interest``
|
||||
and ``open_interest_changes``).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_contract_info_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['open_interest_changes']
|
||||
250
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def live_allowed_price_range_by_name(self,contract_names : List[str])-> AllowedPriceRangeResponse:
|
||||
"""
|
||||
Get the live allowed (daily limit) price range of contracts by name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/name``.
|
||||
Orders placed outside this range are rejected by the exchange, so it is
|
||||
useful to clamp prices before sending an order.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
|
||||
maps every contract name to an ``AllowedPriceRange`` structure with
|
||||
``minAllowedPrice`` (lower limit) and ``maxAllowedPrice`` (upper
|
||||
limit).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_allowed_price_range_by_name(["KASH05C170"])
|
||||
>>> limits = response['Data']['KASH05C170']
|
||||
>>> limits['minAllowedPrice'], limits['maxAllowedPrice']
|
||||
(23500.0, 26500.0)
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
async def live_allowed_price_range_by_id(self,contract_ids : List[str | int])-> AllowedPriceRangeResponse :
|
||||
"""
|
||||
Get the live allowed (daily limit) price range of contracts by ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/id``.
|
||||
Same content as ``live_allowed_price_range_by_name`` but the keys of ``Data``
|
||||
are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
|
||||
maps every contract ID to an ``AllowedPriceRange`` structure
|
||||
(``minAllowedPrice`` and ``maxAllowedPrice``).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = await client.live_allowed_price_range_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['maxAllowedPrice']
|
||||
26500.0
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
async def websocket_by_name(
|
||||
self,
|
||||
contract_names: List[str],
|
||||
event: Event | None = None,
|
||||
)-> AsyncGenerator[
|
||||
WebsocketBase_contractName,
|
||||
None
|
||||
]:
|
||||
"""
|
||||
Stream live market data for contracts identified by contract name.
|
||||
|
||||
Opens a WebSocket connection to
|
||||
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name``
|
||||
(one ``contract_name`` query parameter per name, authenticated with the
|
||||
``AuthAsyncClient`` token) and yields every message received as a decoded
|
||||
``WebsocketBase_contractName`` dictionary.
|
||||
|
||||
Each message is a full snapshot for one contract::
|
||||
|
||||
{
|
||||
"channel": "IME Stream",
|
||||
"contractName": "KASH05C170",
|
||||
"timestamp": "2025-01-15T14:30:00.123456",
|
||||
"data": {"BestLimit": ..., "Aggregate": ...,
|
||||
"AllowedPriceRange": ..., "ContractInfo": ...},
|
||||
}
|
||||
|
||||
Messages for all requested contracts arrive on the same connection, so use
|
||||
``message['contractName']`` to tell them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (for
|
||||
example from another task) to stop it. The check happens each time a
|
||||
message arrives, after a receive timeout (2 seconds without messages),
|
||||
and when the generator is resumed, so the stream ends within about 2
|
||||
seconds at most. The connection is closed automatically when the
|
||||
generator finishes.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to subscribe to.
|
||||
event (Event | None): Optional ``asyncio.Event`` used as a stop switch.
|
||||
It must be set for the stream to run. If ``None`` (or not an
|
||||
``Event``), an already-set internal event is created, which means
|
||||
the stream runs until the connection ends.
|
||||
|
||||
Yields:
|
||||
WebsocketBase_contractName: One live message per update, containing
|
||||
``channel``, ``contractName``, ``timestamp`` and ``data``
|
||||
(a ``Websocket_data`` snapshot).
|
||||
|
||||
Note:
|
||||
* Any error after the connection is established (connection closed by
|
||||
the server, invalid JSON, network error, ...) is swallowed: the
|
||||
connection is closed and the generator simply ends without raising.
|
||||
If you need a permanent stream, wrap the ``async for`` loop in a
|
||||
reconnect loop.
|
||||
* Errors while connecting (for example authentication failure) are
|
||||
raised by ``connect`` and are not caught here.
|
||||
* A receive timeout is not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> stop = Event()
|
||||
>>> stop.set()
|
||||
>>> async for message in client.websocket_by_name(["KASH05C170"], event=stop):
|
||||
... best = message['data']['BestLimit']['1']
|
||||
... print(message['contractName'], best['buy_price'], best['sell_price'])
|
||||
... if best['buy_price'] >= 36000:
|
||||
... stop.clear()
|
||||
KASH05C170 35200 35300
|
||||
"""
|
||||
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
async with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name?"
|
||||
+ "&".join(f"contract_name={s}" for s in contract_names)
|
||||
),
|
||||
additional_headers=self.__AuthAsyncClient.token
|
||||
) as ws:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try : yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def websocket_by_id(
|
||||
self,
|
||||
contract_ids: List[str | int],
|
||||
event: Event | None = None,
|
||||
)-> AsyncGenerator[
|
||||
WebsocketBase_contractId,
|
||||
None
|
||||
]:
|
||||
"""
|
||||
Stream live market data for contracts identified by contract ID.
|
||||
|
||||
Opens a WebSocket connection to
|
||||
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id``
|
||||
(one ``contract_id`` query parameter per ID, authenticated with the
|
||||
``AuthAsyncClient`` token) and yields every message received as a decoded
|
||||
``WebsocketBase_contractId`` dictionary.
|
||||
|
||||
Each message is a full snapshot for one contract::
|
||||
|
||||
{
|
||||
"channel": "IME Stream",
|
||||
"contractId": "123456789",
|
||||
"timestamp": "2025-01-15T14:30:00.123456",
|
||||
"data": {"BestLimit": ..., "Aggregate": ...,
|
||||
"AllowedPriceRange": ..., "ContractInfo": ...},
|
||||
}
|
||||
|
||||
Messages for all requested contracts arrive on the same connection, so use
|
||||
``message['contractId']`` to tell them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (for
|
||||
example from another task) to stop it. The check happens each time a
|
||||
message arrives, after a receive timeout (2 seconds without messages),
|
||||
and when the generator is resumed, so the stream ends within about 2
|
||||
seconds at most. The connection is closed automatically when the
|
||||
generator finishes.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to subscribe to.
|
||||
event (Event | None): Optional ``asyncio.Event`` used as a stop switch.
|
||||
It must be set for the stream to run. If ``None`` (or not an
|
||||
``Event``), an already-set internal event is created, which means
|
||||
the stream runs until the connection ends.
|
||||
|
||||
Yields:
|
||||
WebsocketBase_contractId: One live message per update, containing
|
||||
``channel``, ``contractId``, ``timestamp`` and ``data``
|
||||
(a ``Websocket_data`` snapshot).
|
||||
|
||||
Note:
|
||||
* Any error after the connection is established (connection closed by
|
||||
the server, invalid JSON, network error, ...) is swallowed: the
|
||||
connection is closed and the generator simply ends without raising.
|
||||
If you need a permanent stream, wrap the ``async for`` loop in a
|
||||
reconnect loop.
|
||||
* Errors while connecting (for example authentication failure) are
|
||||
raised by ``connect`` and are not caught here.
|
||||
* A receive timeout is not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> stop = Event()
|
||||
>>> stop.set()
|
||||
>>> async for message in client.websocket_by_id(["123456789"], event=stop):
|
||||
... print(message['contractId'], message['data']['Aggregate']['last_price'])
|
||||
... stop.clear()
|
||||
123456789 35250.0
|
||||
"""
|
||||
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
async with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id?"
|
||||
+ "&".join(f"contract_id={s}" for s in contract_ids)
|
||||
),
|
||||
additional_headers=self.__AuthAsyncClient.token
|
||||
) as ws:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try : yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
@@ -0,0 +1,867 @@
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from threading import Event
|
||||
from websockets.sync.client import connect
|
||||
from json import loads
|
||||
from HedgeTech.Auth import AuthSyncClient
|
||||
from typing import (
|
||||
Literal,
|
||||
List,
|
||||
Generator,
|
||||
)
|
||||
from .__io_types import (
|
||||
WebsocketBase_contractName,
|
||||
WebsocketBase_contractId,
|
||||
|
||||
OverviewResponse,
|
||||
Contracts,
|
||||
|
||||
ContractInfoResponse,
|
||||
AllowedPriceRangeResponse,
|
||||
AggregateResponse,
|
||||
BestLimitResponse,
|
||||
)
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
class DataEngine_Ime_SyncClient:
|
||||
"""
|
||||
Synchronous (blocking) client for the HedgeTech Data Engine (Iran Mercantile Exchange - IME).
|
||||
|
||||
This client wraps the IME endpoints of the HedgeTech Data Engine
|
||||
(``core.hedgetech.ir/data-engine/ime``) as regular blocking methods. All requests
|
||||
are sent through the authenticated ``httpx`` client held by the ``AuthSyncClient``
|
||||
passed to the constructor, so the caller never handles tokens manually.
|
||||
|
||||
The endpoints are grouped into three families:
|
||||
|
||||
1. **Static data** (contract metadata that rarely changes):
|
||||
``search_contracts``, ``contracts_static_info_by_name``,
|
||||
``contracts_static_info_by_id`` -> return ``Contracts``.
|
||||
|
||||
2. **Live snapshots** (one-shot REST requests for the current market state):
|
||||
``live_overview_by_*``, ``live_best_limit_by_*``, ``live_aggregate_by_*``,
|
||||
``live_contract_info_by_*``, ``live_allowed_price_range_by_*``.
|
||||
|
||||
3. **Live streams** (continuous WebSocket push of full market snapshots):
|
||||
``websocket_by_name``, ``websocket_by_id``.
|
||||
|
||||
Every REST method (except ``search_contracts``) exists in two variants:
|
||||
|
||||
* ``*_by_name`` - contracts are identified by ``contractName``
|
||||
(e.g. ``"KASH05C170"``).
|
||||
* ``*_by_id`` - contracts are identified by ``contractId``
|
||||
(e.g. ``"123456789"``; ``int`` values are accepted and sent as text).
|
||||
|
||||
Every REST response is the raw JSON body returned by the server, typed with the
|
||||
response structures from ``__io_types``. Each response contains a ``Data`` section
|
||||
and a ``Status`` section (see ``Status``). Whenever the HTTP status is not a
|
||||
success, the method raises ``ValueError`` carrying the server's ``detail`` message.
|
||||
|
||||
This is the blocking twin of ``DataEngine_Ime_AsyncClient``: the endpoints,
|
||||
arguments and return types are identical, only the calling style differs
|
||||
(plain calls instead of ``await``, ``threading.Event`` instead of
|
||||
``asyncio.Event``, a normal generator instead of an async generator).
|
||||
|
||||
Note:
|
||||
Prices, volumes and values follow the conventions documented in
|
||||
``__io_types`` (prices in IRR; commissions, margins and taxes as fractions,
|
||||
e.g. ``0.0025`` = 0.25%).
|
||||
|
||||
Attributes:
|
||||
__AuthSyncClient (AuthSyncClient): The authenticated client used for all
|
||||
HTTP requests (via ``httpx_Client``) and for the WebSocket auth headers
|
||||
(via ``token``). Stored privately (name-mangled).
|
||||
|
||||
Example:
|
||||
>>> auth = AuthSyncClient(...)
|
||||
>>> client = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
|
||||
>>> response = client.live_best_limit_by_name(["KASH05C170"])
|
||||
>>> response['Data']['KASH05C170']['1']['buy_price']
|
||||
35200
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
):
|
||||
"""
|
||||
Create a new IME Data Engine client.
|
||||
|
||||
Args:
|
||||
AuthSyncClient (AuthSyncClient): An already authenticated HedgeTech
|
||||
client. Its ``httpx_Client`` is used for every REST call and its
|
||||
``token`` is used as the header set for WebSocket connections.
|
||||
|
||||
Example:
|
||||
>>> client = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
|
||||
"""
|
||||
|
||||
self.__AuthSyncClient = AuthSyncClient
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def search_contracts(
|
||||
self,
|
||||
market : Literal[
|
||||
"IMEDepositCertificate",
|
||||
"IMEFutures",
|
||||
"IMEOption",
|
||||
],
|
||||
Search_char : str,
|
||||
)-> Contracts :
|
||||
"""
|
||||
Search IME contracts of a given market by a text fragment.
|
||||
|
||||
Sends ``GET /data-engine/ime/static/data/contract/search`` and returns the
|
||||
static metadata of the matching contracts.
|
||||
|
||||
Args:
|
||||
market (Literal["IMEDepositCertificate", "IMEFutures", "IMEOption"]):
|
||||
The market (instrument class) to search in. It decides which
|
||||
structure the items in the result have:
|
||||
``IMEDepositCertificate`` -> ``IMEDepositCertificate``,
|
||||
``IMEFutures`` -> ``IMEFutures``, ``IMEOption`` -> ``IMEOption``.
|
||||
Search_char (str): The text to search for (e.g. part of a contract name
|
||||
such as ``"KASH05C"``).
|
||||
|
||||
Returns:
|
||||
Contracts: ``{"Data": [...], "Status": {...}}`` where ``Data`` is the
|
||||
list of matching instruments (static metadata only, no live prices).
|
||||
Use the returned ``contractName`` / ``contractId`` values with the
|
||||
other methods of this client.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.search_contracts(
|
||||
... market="IMEOption",
|
||||
... Search_char="KASH05C",
|
||||
... )
|
||||
>>> [item['contractName'] for item in response['Data'] if item]
|
||||
['KASH05C170', 'KASH05C180']
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/search',
|
||||
params={
|
||||
'market' : market,
|
||||
'Search_char' : Search_char
|
||||
}
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def contracts_static_info_by_name(self,contract_names : List[str])-> Contracts:
|
||||
"""
|
||||
Get the static metadata of contracts identified by contract name.
|
||||
|
||||
Sends ``GET /data-engine/ime/static/data/contract/name`` with one
|
||||
``contract_names`` query parameter per name.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up
|
||||
(e.g. ``["KASH05C170", "KASH05P170"]``).
|
||||
|
||||
Returns:
|
||||
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in
|
||||
``Data`` is an ``IMEOption``, ``IMEFutures`` or
|
||||
``IMEDepositCertificate`` structure, or ``None`` when no
|
||||
instrument was found for the corresponding name.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status.
|
||||
The message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.contracts_static_info_by_name(["KASH05C170"])
|
||||
>>> response['Data'][0]['strikePrice']
|
||||
170000.0
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def contracts_static_info_by_id(self,contract_ids : List[str | int])-> Contracts:
|
||||
"""
|
||||
Get the static metadata of contracts identified by contract ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/static/data/contract/id`` with one
|
||||
``contract_ids`` query parameter per ID.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up
|
||||
(e.g. ``["123456789", 987654321]``).
|
||||
|
||||
Returns:
|
||||
Contracts: ``{"Data": [...], "Status": {...}}``. Each item in ``Data`` is
|
||||
an ``IMEOption``, ``IMEFutures`` or ``IMEDepositCertificate``
|
||||
structure, or ``None`` when no instrument was found for the
|
||||
corresponding ID.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.contracts_static_info_by_id(["123456789"])
|
||||
>>> response['Data'][0]['contractName']
|
||||
'KASH05C170'
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/static/data/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_overview_by_name(self,contract_names : List[str])-> OverviewResponse:
|
||||
"""
|
||||
Get the live market overview of contracts identified by contract name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/overview/contract/name``. The overview
|
||||
combines each contract's static metadata with its live ``BestLimit``,
|
||||
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo`` sections in a single
|
||||
request.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every requested contract name to an ``OverviewIMEOption``,
|
||||
``OverviewIMEFutures`` or ``OverviewIMEDepositCertificate``
|
||||
structure, or to ``None`` if the contract was not found.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_overview_by_name(["KASH05C170"])
|
||||
>>> overview = response['Data']['KASH05C170']
|
||||
>>> if overview:
|
||||
... print(overview['Aggregate']['last_price'])
|
||||
35250.0
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_overview_by_id(self,contract_ids : List[str | int])-> OverviewResponse:
|
||||
"""
|
||||
Get the live market overview of contracts identified by contract ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/overview/contract/id``. Same content
|
||||
as ``live_overview_by_name`` (static metadata + live ``BestLimit``,
|
||||
``Aggregate``, ``AllowedPriceRange`` and ``ContractInfo``), but the keys of
|
||||
``Data`` are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
OverviewResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every requested contract ID to its overview structure, or to
|
||||
``None`` if the contract was not found.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_overview_by_id(["123456789"])
|
||||
>>> overview = response['Data']['123456789']
|
||||
>>> if overview:
|
||||
... print(overview['BestLimit']['1']['buy_price'])
|
||||
35200
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/overview/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_best_limit_by_name(self,contract_names : List[str])-> BestLimitResponse:
|
||||
"""
|
||||
Get the live best-limit order book of contracts identified by contract name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/best-limit/contract/name``.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract name to its order book, a dictionary with up to three
|
||||
levels (``"1"`` best, ``"2"``, ``"3"``), each a ``BestLimitItem``
|
||||
(``buy_quantity``, ``buy_price``, ``sell_quantity``, ``sell_price``).
|
||||
Empty sides carry zero values, so check that a price is greater than
|
||||
zero before using it.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_best_limit_by_name(["KASH05C170"])
|
||||
>>> level = response['Data']['KASH05C170']['1']
|
||||
>>> if level['buy_price'] > 0 and level['sell_price'] > 0:
|
||||
... print(level['sell_price'] - level['buy_price'])
|
||||
100
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_best_limit_by_id(self,contract_ids : List[str | int])-> BestLimitResponse:
|
||||
"""
|
||||
Get the live best-limit order book of contracts identified by contract ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/best-limit/contract/id``. Same content
|
||||
as ``live_best_limit_by_name`` but the keys of ``Data`` are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
BestLimitResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract ID to its order book levels (``"1"``, ``"2"``,
|
||||
``"3"``), each a ``BestLimitItem``. Empty sides carry zero values.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_best_limit_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['1']['sell_price']
|
||||
35300
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/best-limit/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_aggregate_by_name(self,contract_names : List[str])-> AggregateResponse:
|
||||
"""
|
||||
Get the live aggregate trading statistics of contracts identified by name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/aggregate/contract/name``.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract name to an ``Aggregate`` structure: ``date``,
|
||||
``time``, ``trade_count``, ``total_volume``, ``total_value`` (IRR),
|
||||
and the OHLC-style prices ``open_price``, ``high_price``,
|
||||
``low_price``, ``last_price``, ``closing_price`` and
|
||||
``previous_close``.
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_aggregate_by_name(["KASH05C170"])
|
||||
>>> agg = response['Data']['KASH05C170']
|
||||
>>> (agg['closing_price'] - agg['previous_close']) / agg['previous_close'] * 100
|
||||
0.8
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
def live_aggregate_by_id(self,contract_ids : List[str | int])-> AggregateResponse :
|
||||
"""
|
||||
Get the live aggregate trading statistics of contracts identified by ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/aggregate/contract/id``. Same content
|
||||
as ``live_aggregate_by_name`` but the keys of ``Data`` are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
AggregateResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract ID to an ``Aggregate`` structure (trade count, volume,
|
||||
value and OHLC-style prices).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_aggregate_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['last_price']
|
||||
35250.0
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/aggregate/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_contract_info_by_name(self,contract_names : List[str])-> ContractInfoResponse:
|
||||
"""
|
||||
Get the live contract information (open interest) of contracts by name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/contract-info/contract/name``.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract name to a ``ContractInfo`` structure with
|
||||
``open_interest`` (number of open positions) and
|
||||
``open_interest_changes`` (change versus the previous period;
|
||||
positive = increase, negative = decrease).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_contract_info_by_name(["KASH05C170"])
|
||||
>>> response['Data']['KASH05C170']['open_interest']
|
||||
15000
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
def live_contract_info_by_id(self,contract_ids : List[str | int])-> ContractInfoResponse :
|
||||
"""
|
||||
Get the live contract information (open interest) of contracts by ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/contract-info/contract/id``. Same
|
||||
content as ``live_contract_info_by_name`` but the keys of ``Data`` are
|
||||
contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
ContractInfoResponse: ``{"Data": {...}, "Status": {...}}``. ``Data`` maps
|
||||
every contract ID to a ``ContractInfo`` structure (``open_interest``
|
||||
and ``open_interest_changes``).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_contract_info_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['open_interest_changes']
|
||||
250
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/contract-info/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def live_allowed_price_range_by_name(self,contract_names : List[str])-> AllowedPriceRangeResponse:
|
||||
"""
|
||||
Get the live allowed (daily limit) price range of contracts by name.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/name``.
|
||||
Orders placed outside this range are rejected by the exchange, so it is
|
||||
useful to clamp prices before sending an order.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to look up.
|
||||
|
||||
Returns:
|
||||
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
|
||||
maps every contract name to an ``AllowedPriceRange`` structure with
|
||||
``minAllowedPrice`` (lower limit) and ``maxAllowedPrice`` (upper
|
||||
limit).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_allowed_price_range_by_name(["KASH05C170"])
|
||||
>>> limits = response['Data']['KASH05C170']
|
||||
>>> limits['minAllowedPrice'], limits['maxAllowedPrice']
|
||||
(23500.0, 26500.0)
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/name',
|
||||
params=[('contract_names', name) for name in contract_names]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
def live_allowed_price_range_by_id(self,contract_ids : List[str | int])-> AllowedPriceRangeResponse :
|
||||
"""
|
||||
Get the live allowed (daily limit) price range of contracts by ID.
|
||||
|
||||
Sends ``GET /data-engine/ime/live/data/allowed-price-range/contract/id``.
|
||||
Same content as ``live_allowed_price_range_by_name`` but the keys of ``Data``
|
||||
are contract IDs.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to look up.
|
||||
|
||||
Returns:
|
||||
AllowedPriceRangeResponse: ``{"Data": {...}, "Status": {...}}``. ``Data``
|
||||
maps every contract ID to an ``AllowedPriceRange`` structure
|
||||
(``minAllowedPrice`` and ``maxAllowedPrice``).
|
||||
|
||||
Raises:
|
||||
ValueError: If the server answers with a non-success HTTP status. The
|
||||
message is the server's ``detail`` field.
|
||||
|
||||
Example:
|
||||
>>> response = client.live_allowed_price_range_by_id(["123456789"])
|
||||
>>> response['Data']['123456789']['maxAllowedPrice']
|
||||
26500.0
|
||||
"""
|
||||
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/ime/live/data/allowed-price-range/contract/id',
|
||||
params=[('contract_ids', id) for id in contract_ids]
|
||||
)
|
||||
|
||||
if data.is_success :
|
||||
|
||||
return data.json()
|
||||
|
||||
else :
|
||||
|
||||
raise ValueError(data.json().get('detail'))
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def websocket_by_name(
|
||||
self,
|
||||
contract_names: List[str],
|
||||
event: Event | None = None,
|
||||
)-> Generator[
|
||||
WebsocketBase_contractName,
|
||||
None,
|
||||
None
|
||||
]:
|
||||
"""
|
||||
Stream live market data for contracts identified by contract name.
|
||||
|
||||
Opens a blocking WebSocket connection to
|
||||
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name``
|
||||
(one ``contract_name`` query parameter per name, authenticated with the
|
||||
``AuthSyncClient`` token) and yields every message received as a decoded
|
||||
``WebsocketBase_contractName`` dictionary.
|
||||
|
||||
Each message is a full snapshot for one contract::
|
||||
|
||||
{
|
||||
"channel": "IME Stream",
|
||||
"contractName": "KASH05C170",
|
||||
"timestamp": "2025-01-15T14:30:00.123456",
|
||||
"data": {"BestLimit": ..., "Aggregate": ...,
|
||||
"AllowedPriceRange": ..., "ContractInfo": ...},
|
||||
}
|
||||
|
||||
Messages for all requested contracts arrive on the same connection, so use
|
||||
``message['contractName']`` to tell them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (typically
|
||||
from another thread, since the iterating thread is blocked while
|
||||
waiting) to stop it. The check happens each time a message arrives and
|
||||
after a receive timeout (2 seconds without messages), so the stream
|
||||
ends within about 2 seconds at most. The connection is closed
|
||||
automatically when the generator finishes.
|
||||
|
||||
Args:
|
||||
contract_names (List[str]): Contract names to subscribe to.
|
||||
event (threading.Event | None): Optional ``threading.Event`` used as a
|
||||
stop switch. It must be set for the stream to run. If ``None`` (or
|
||||
not an ``Event``), an already-set internal event is created, which
|
||||
means the stream runs until the connection ends.
|
||||
|
||||
Yields:
|
||||
WebsocketBase_contractName: One live message per update, containing
|
||||
``channel``, ``contractName``, ``timestamp`` and ``data``
|
||||
(a ``Websocket_data`` snapshot).
|
||||
|
||||
Note:
|
||||
* This generator blocks the calling thread while waiting for messages.
|
||||
Run it in a dedicated thread if the rest of your program must keep
|
||||
working.
|
||||
* Any error after the connection is established (connection closed by
|
||||
the server, invalid JSON, network error, ...) is swallowed: the
|
||||
connection is closed and the generator simply ends without raising.
|
||||
If you need a permanent stream, wrap the ``for`` loop in a reconnect
|
||||
loop.
|
||||
* Errors while connecting (for example authentication failure) are
|
||||
raised by ``connect`` and are not caught here.
|
||||
* A receive timeout is not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> stop = Event()
|
||||
>>> stop.set()
|
||||
>>> for message in client.websocket_by_name(["KASH05C170"], event=stop):
|
||||
... best = message['data']['BestLimit']['1']
|
||||
... print(message['contractName'], best['buy_price'], best['sell_price'])
|
||||
... if best['buy_price'] >= 36000:
|
||||
... stop.clear()
|
||||
KASH05C170 35200 35300
|
||||
"""
|
||||
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/name?"
|
||||
+ "&".join(f"contract_name={s}" for s in contract_names)
|
||||
),
|
||||
additional_headers=self.__AuthSyncClient.token
|
||||
) as ws:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
def websocket_by_id(
|
||||
self,
|
||||
contract_ids: List[str | int],
|
||||
event: Event | None = None,
|
||||
)-> Generator[
|
||||
WebsocketBase_contractId,
|
||||
None,
|
||||
None
|
||||
]:
|
||||
"""
|
||||
Stream live market data for contracts identified by contract ID.
|
||||
|
||||
Opens a blocking WebSocket connection to
|
||||
``wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id``
|
||||
(one ``contract_id`` query parameter per ID, authenticated with the
|
||||
``AuthSyncClient`` token) and yields every message received as a decoded
|
||||
``WebsocketBase_contractId`` dictionary.
|
||||
|
||||
Each message is a full snapshot for one contract::
|
||||
|
||||
{
|
||||
"channel": "IME Stream",
|
||||
"contractId": "123456789",
|
||||
"timestamp": "2025-01-15T14:30:00.123456",
|
||||
"data": {"BestLimit": ..., "Aggregate": ...,
|
||||
"AllowedPriceRange": ..., "ContractInfo": ...},
|
||||
}
|
||||
|
||||
Messages for all requested contracts arrive on the same connection, so use
|
||||
``message['contractId']`` to tell them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (typically
|
||||
from another thread, since the iterating thread is blocked while
|
||||
waiting) to stop it. The check happens each time a message arrives and
|
||||
after a receive timeout (2 seconds without messages), so the stream
|
||||
ends within about 2 seconds at most. The connection is closed
|
||||
automatically when the generator finishes.
|
||||
|
||||
Args:
|
||||
contract_ids (List[str | int]): Contract IDs to subscribe to.
|
||||
event (threading.Event | None): Optional ``threading.Event`` used as a
|
||||
stop switch. It must be set for the stream to run. If ``None`` (or
|
||||
not an ``Event``), an already-set internal event is created, which
|
||||
means the stream runs until the connection ends.
|
||||
|
||||
Yields:
|
||||
WebsocketBase_contractId: One live message per update, containing
|
||||
``channel``, ``contractId``, ``timestamp`` and ``data``
|
||||
(a ``Websocket_data`` snapshot).
|
||||
|
||||
Note:
|
||||
* This generator blocks the calling thread while waiting for messages.
|
||||
Run it in a dedicated thread if the rest of your program must keep
|
||||
working.
|
||||
* Any error after the connection is established (connection closed by
|
||||
the server, invalid JSON, network error, ...) is swallowed: the
|
||||
connection is closed and the generator simply ends without raising.
|
||||
If you need a permanent stream, wrap the ``for`` loop in a reconnect
|
||||
loop.
|
||||
* Errors while connecting (for example authentication failure) are
|
||||
raised by ``connect`` and are not caught here.
|
||||
* A receive timeout is not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> stop = Event()
|
||||
>>> stop.set()
|
||||
>>> for message in client.websocket_by_id(["123456789"], event=stop):
|
||||
... print(message['contractId'], message['data']['Aggregate']['last_price'])
|
||||
... stop.clear()
|
||||
123456789 35250.0
|
||||
"""
|
||||
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/ime/live/data/websocket/contract/id?"
|
||||
+ "&".join(f"contract_id={s}" for s in contract_ids)
|
||||
),
|
||||
additional_headers=self.__AuthSyncClient.token
|
||||
) as ws:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
@@ -0,0 +1,2 @@
|
||||
from .__AsyncClient import DataEngine_Ime_AsyncClient
|
||||
from .__SyncClient import DataEngine_Ime_SyncClient
|
||||
@@ -0,0 +1,12 @@
|
||||
from .__response import(
|
||||
WebsocketBase_contractName,
|
||||
WebsocketBase_contractId,
|
||||
|
||||
OverviewResponse,
|
||||
Contracts,
|
||||
|
||||
ContractInfoResponse,
|
||||
AllowedPriceRangeResponse,
|
||||
AggregateResponse,
|
||||
BestLimitResponse,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,8 @@
|
||||
from .__tse_ifb import (
|
||||
DataEngine_TseIfb_SyncClient,
|
||||
DataEngine_TseIfb_AsyncClient
|
||||
)
|
||||
from .__ime import (
|
||||
DataEngine_Ime_SyncClient,
|
||||
DataEngine_Ime_AsyncClient
|
||||
)
|
||||
@@ -2,7 +2,12 @@
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from asyncio import Event
|
||||
from asyncio import (
|
||||
Event,
|
||||
wait_for,
|
||||
TimeoutError,
|
||||
sleep,
|
||||
)
|
||||
from websockets.asyncio.client import connect
|
||||
from json import loads
|
||||
from HedgeTech.Auth import AuthAsyncClient
|
||||
@@ -49,7 +54,7 @@ from .__io_types import (
|
||||
class DataEngine_TseIfb_AsyncClient:
|
||||
|
||||
"""
|
||||
Asynchronous client for interacting with the TSE-IFB (Iranian Securities Exchange) Data Engine API.
|
||||
Asynchronous client for the TSE-IFB Data Engine API (Tehran Stock Exchange and Iran Fara Bourse).
|
||||
|
||||
This class provides high-level asynchronous methods to retrieve live and historical market data,
|
||||
order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other
|
||||
@@ -66,14 +71,14 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
__AuthAsyncClient (AuthAsyncClient): An instance of `AuthAsyncClient` used to perform
|
||||
authorized HTTP requests and WebSocket connections.
|
||||
|
||||
Examples:
|
||||
Example:
|
||||
>>> auth_client = await AuthAsyncClient.login(
|
||||
... UserName_or_Email="user@example.com",
|
||||
... Password="secure_password"
|
||||
... )
|
||||
>>> data_client = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth_client)
|
||||
>>> instruments = await data_client.instruments_static_info_by_name(["فملی", "خودرو"])
|
||||
>>> print(instruments["Data"]["فملی"]["symbolName"])
|
||||
>>> print(instruments["Data"][0]["symbolName"])
|
||||
>>> async for update in data_client.websocket_by_name(
|
||||
... channels=["best-limit", "order-book"],
|
||||
... symbol_names=["فملی"]
|
||||
@@ -82,8 +87,14 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
|
||||
Notes:
|
||||
- All network requests are asynchronous and should be awaited.
|
||||
- Most methods exist in two variants: ``*_by_name`` (symbol name, e.g. "فملی") and
|
||||
``*_by_isin`` (ISIN code).
|
||||
- REST methods raise ``ValueError`` (carrying the server's ``detail`` message) when the
|
||||
API returns an error.
|
||||
- WebSocket methods yield streaming updates and should be used with `async for`.
|
||||
- Exceptions (ValueError) are raised when the API returns an error or request fails.
|
||||
Once the connection is established, errors do not raise: the stream simply ends
|
||||
(see ``websocket_by_name``).
|
||||
- Prices are in IRR; commission rates are fractions (``0.001`` means 0.1%).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -129,7 +140,8 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
Returns:
|
||||
Instruments:
|
||||
A dictionary containing:
|
||||
- Data: A list of matched instruments. Each item is one of:
|
||||
- Data: A list of matched instruments (the type of each item can be
|
||||
recognized from its fields, see ``Instruments``). Each item is one of:
|
||||
* SecuritiesAndFunds
|
||||
* TreasuryBonds
|
||||
* StockOptions
|
||||
@@ -185,8 +197,9 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
Returns:
|
||||
Instruments:
|
||||
A dictionary containing:
|
||||
- Data: A mapping of symbol_name → Instrument info.
|
||||
Instrument info is one of:
|
||||
- Data: A list of instruments matching the provided symbol names.
|
||||
Identify each item by its ``symbolName`` field (do not rely on the order).
|
||||
Each item is one of:
|
||||
* SecuritiesAndFunds
|
||||
* TreasuryBonds
|
||||
* StockOptions
|
||||
@@ -203,7 +216,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
>>> result = await client.instruments_static_info_by_name(
|
||||
... ["فملی", "خودرو"]
|
||||
... )
|
||||
>>> print(result["Data"]["فملی"]["symbolIsin"])
|
||||
>>> print(result["Data"][0]["symbolIsin"])
|
||||
"""
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name',
|
||||
@@ -234,7 +247,8 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
Instruments:
|
||||
A dictionary containing:
|
||||
- Data: A list of instruments matching the provided ISINs.
|
||||
Each item can be SecuritiesAndFunds, TreasuryBonds,
|
||||
Identify each item by its ``symbolIsin`` field (do not rely on
|
||||
the order). Each item can be SecuritiesAndFunds, TreasuryBonds,
|
||||
StockOptions, StockFutures, or None if not found.
|
||||
- Status: Status information returned by the API.
|
||||
|
||||
@@ -394,7 +408,8 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names.
|
||||
|
||||
This endpoint returns the top-of-the-book order data, including:
|
||||
This endpoint returns the best limit levels of the order book (up to 6 levels per
|
||||
instrument), each including:
|
||||
- Best bid price, quantity, and order count
|
||||
- Best ask price, quantity, and order count
|
||||
|
||||
@@ -407,8 +422,9 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
BestLimitResponse:
|
||||
An object containing:
|
||||
- **Data**:
|
||||
Mapping of symbol_name → BestLimitItem
|
||||
Each BestLimitItem includes:
|
||||
Mapping of symbol_name → best limit levels: a dictionary with up to 6
|
||||
levels ("1" = best ... "6" = deepest).
|
||||
Each level is a BestLimitItem that includes:
|
||||
* buy_order_count
|
||||
* buy_quantity
|
||||
* buy_price
|
||||
@@ -424,7 +440,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
|
||||
>>> bl = await client.live_best_limit_by_name(["فملی"])
|
||||
>>> print(bl["Data"]["فملی"]["buy_price"])
|
||||
>>> print(bl["Data"]["فملی"]["1"]["buy_price"])
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
@@ -448,7 +464,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes.
|
||||
|
||||
This endpoint returns the top-of-book order metrics for each ISIN instrument.
|
||||
This endpoint returns the best limit levels (up to 6 per instrument) for each ISIN instrument.
|
||||
|
||||
Args:
|
||||
symbol_isins (List[str]):
|
||||
@@ -458,8 +474,9 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
BestLimitResponse:
|
||||
An object containing:
|
||||
- **Data**:
|
||||
Mapping of symbol_isin → BestLimitItem
|
||||
Each BestLimitItem includes:
|
||||
Mapping of symbol_isin → best limit levels: a dictionary with up to 6
|
||||
levels ("1" = best ... "6" = deepest).
|
||||
Each level is a BestLimitItem that includes:
|
||||
* buy_order_count
|
||||
* buy_quantity
|
||||
* buy_price
|
||||
@@ -475,7 +492,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
|
||||
>>> bl = await client.live_best_limit_by_isin(["IRO1XYZ12345"])
|
||||
>>> print(bl["Data"]["IRO1XYZ12345"]["sell_quantity"])
|
||||
>>> print(bl["Data"]["IRO1XYZ12345"]["1"]["sell_quantity"])
|
||||
"""
|
||||
|
||||
data = await self.__AuthAsyncClient.httpx_Client.get(
|
||||
@@ -919,7 +936,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"nav": float,
|
||||
"units": int,
|
||||
"marketCap": int,
|
||||
"as_of": datetime
|
||||
"as_of": datetime # typically an ISO-formatted string in the decoded JSON
|
||||
},
|
||||
...
|
||||
},
|
||||
@@ -967,7 +984,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"nav": float,
|
||||
"units": int,
|
||||
"marketCap": int,
|
||||
"as_of": datetime
|
||||
"as_of": datetime # typically an ISO-formatted string in the decoded JSON
|
||||
},
|
||||
...
|
||||
},
|
||||
@@ -1110,10 +1127,14 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by symbol name.
|
||||
|
||||
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
|
||||
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
|
||||
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
|
||||
|
||||
Args:
|
||||
symbol_name (str): Trading symbol name (e.g., "فملی").
|
||||
start_timestamp (int): Unix timestamp for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp for the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
|
||||
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
|
||||
Resolution (Literal): Data resolution. Options:
|
||||
- "1m", "5m", "15m", "30m", "1h" for intraday
|
||||
@@ -1188,10 +1209,14 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by ISIN code.
|
||||
|
||||
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
|
||||
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
|
||||
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
|
||||
|
||||
Args:
|
||||
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
|
||||
start_timestamp (int): Unix timestamp for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp for the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
|
||||
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
|
||||
Resolution (Literal): Data resolution. Options:
|
||||
- "1m", "5m", "15m", "30m", "1h" for intraday
|
||||
@@ -1262,10 +1287,12 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name.
|
||||
|
||||
All parameters are keyword-only.
|
||||
|
||||
Args:
|
||||
symbol_name (str): Trading symbol name (e.g., "فملی").
|
||||
start_timestamp (int): Unix timestamp marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp marking the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
|
||||
|
||||
Returns:
|
||||
CorporateActionResponse: TypedDict with structure:
|
||||
@@ -1273,7 +1300,8 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
|
||||
"Status": Status
|
||||
}
|
||||
Each item in Data includes fields such as:
|
||||
Each item in Data includes fields such as (use ``corporateAction`` to tell the two
|
||||
kinds of items apart):
|
||||
- Date_timestamp: int
|
||||
- corporateAction: str
|
||||
- symbolName: str
|
||||
@@ -1327,10 +1355,12 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code.
|
||||
|
||||
All parameters are keyword-only.
|
||||
|
||||
Args:
|
||||
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
|
||||
start_timestamp (int): Unix timestamp marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp marking the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
|
||||
|
||||
Returns:
|
||||
CorporateActionResponse: TypedDict with structure:
|
||||
@@ -1338,7 +1368,8 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
|
||||
"Status": Status
|
||||
}
|
||||
Each item in Data includes fields such as:
|
||||
Each item in Data includes fields such as (use ``corporateAction`` to tell the two
|
||||
kinds of items apart):
|
||||
- Date_timestamp: int
|
||||
- corporateAction: str
|
||||
- symbolName: str
|
||||
@@ -1414,6 +1445,16 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs individual trades,
|
||||
contract information, and fund information.
|
||||
|
||||
All requested channels and instruments share a single connection. Every message belongs to
|
||||
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolName"]`` to tell
|
||||
them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (for example from another
|
||||
task) to stop it. The check happens each time a message arrives and after a receive
|
||||
timeout (2 seconds without messages), so the stream ends within about 2 seconds at most.
|
||||
The connection is closed automatically when the generator finishes.
|
||||
|
||||
Args:
|
||||
channels (List[str]):
|
||||
List of channels to subscribe to. Possible values:
|
||||
@@ -1427,13 +1468,15 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
symbol_names (List[str]):
|
||||
List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]).
|
||||
event (Event | None, optional):
|
||||
Optional asyncio.Event to control the WebSocket loop.
|
||||
If provided, the loop will continue while `event.is_set()` is True.
|
||||
Defaults to a new set Event.
|
||||
Optional asyncio.Event used as a stop switch. It must be set for the stream to run:
|
||||
the loop continues while `event.is_set()` is True.
|
||||
Defaults to a new, already-set Event (the stream then runs until the connection ends).
|
||||
|
||||
Returns:
|
||||
AsyncGenerator:
|
||||
Yields TypedDict objects depending on the channel subscribed:
|
||||
Yields:
|
||||
Union[BestLimit_WS_symbolName, OrderBook_WS_symbolName, Aggregate_WS_symbolName,
|
||||
institutional_vs_individual_WS_symbolName, ContractInfo_WS_symbolName, FundInfo_WS_symbolName,
|
||||
OHLCV_WS_symbolName]:
|
||||
One message per update, as a TypedDict that depends on the channel:
|
||||
- **BestLimit_WS_symbolName** for 'best-limit'
|
||||
- **OrderBook_WS_symbolName** for 'order-book'
|
||||
- **OHLCV_WS_symbolName** for 'ohlcv-last-1m'
|
||||
@@ -1443,14 +1486,22 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
- **FundInfo_WS_symbolName** for 'fund-info'
|
||||
|
||||
Each yielded object contains:
|
||||
- `channel`: str — name of the channel
|
||||
- `symbolName`: str — instrument symbol
|
||||
- `timestamp`: str — server timestamp
|
||||
- `data`: Dict[...] — channel-specific real-time data.
|
||||
- `channel`: Literal — name of the channel (one of the values above)
|
||||
- `symbolName`: str — instrument symbol name
|
||||
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
|
||||
numeric ``ServerTimeStamp`` in ``Status``)
|
||||
- `data`: channel-specific real-time data.
|
||||
|
||||
Raises:
|
||||
WebSocketException or ValueError:
|
||||
If the WebSocket connection fails or an exception occurs while receiving data.
|
||||
websockets.exceptions.WebSocketException or OSError:
|
||||
Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
|
||||
or ``OSError`` on a network failure).
|
||||
|
||||
Note:
|
||||
Once the connection is established, errors do not raise: a closed connection, invalid JSON
|
||||
or a network error closes the connection and the generator simply ends. If you need a
|
||||
permanent stream, wrap the ``async for`` loop in a reconnect loop. A receive timeout is
|
||||
not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
|
||||
@@ -1458,10 +1509,11 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
... channels=["best-limit", "order-book"],
|
||||
... symbol_names=["فملی"]
|
||||
... ):
|
||||
... print(update["data"])
|
||||
... if update["channel"] == "best-limit":
|
||||
... print(update["symbolName"], update["data"]["1"]["buy_price"])
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
@@ -1473,12 +1525,16 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
),
|
||||
additional_headers=self.__AuthAsyncClient.token
|
||||
) as ws:
|
||||
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try:
|
||||
yield loads(await ws.recv())
|
||||
except :
|
||||
try : yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
|
||||
@@ -1515,9 +1571,19 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
"""
|
||||
Subscribe to **real-time WebSocket updates** for a list of instruments using their ISIN codes.
|
||||
|
||||
This function streams live updates for multiple market channels such as best-limit, order book,
|
||||
last 1-minute OHLCV, aggregate data, institutional vs individual trades, contract information,
|
||||
and fund information.
|
||||
This function streams continuous updates for multiple market channels such as
|
||||
best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs individual trades,
|
||||
contract information, and fund information.
|
||||
|
||||
All requested channels and instruments share a single connection. Every message belongs to
|
||||
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolIsin"]`` to tell
|
||||
them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (for example from another
|
||||
task) to stop it. The check happens each time a message arrives and after a receive
|
||||
timeout (2 seconds without messages), so the stream ends within about 2 seconds at most.
|
||||
The connection is closed automatically when the generator finishes.
|
||||
|
||||
Args:
|
||||
channels (List[str]):
|
||||
@@ -1532,13 +1598,15 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
symbol_isins (List[str]):
|
||||
List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]).
|
||||
event (Event | None, optional):
|
||||
Optional asyncio.Event to control the WebSocket loop.
|
||||
If provided, the loop continues while `event.is_set()` is True.
|
||||
Defaults to a new set Event.
|
||||
Optional asyncio.Event used as a stop switch. It must be set for the stream to run:
|
||||
the loop continues while `event.is_set()` is True.
|
||||
Defaults to a new, already-set Event (the stream then runs until the connection ends).
|
||||
|
||||
Returns:
|
||||
AsyncGenerator:
|
||||
Yields TypedDict objects depending on the channel subscribed:
|
||||
Yields:
|
||||
Union[BestLimit_WS_symbolIsin, OrderBook_WS_symbolIsin, Aggregate_WS_symbolIsin,
|
||||
institutional_vs_individual_WS_symbolIsin, ContractInfo_WS_symbolIsin, FundInfo_WS_symbolIsin,
|
||||
OHLCV_WS_symbolIsin]:
|
||||
One message per update, as a TypedDict that depends on the channel:
|
||||
- **BestLimit_WS_symbolIsin** for 'best-limit'
|
||||
- **OrderBook_WS_symbolIsin** for 'order-book'
|
||||
- **OHLCV_WS_symbolIsin** for 'ohlcv-last-1m'
|
||||
@@ -1548,14 +1616,22 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
- **FundInfo_WS_symbolIsin** for 'fund-info'
|
||||
|
||||
Each yielded object contains:
|
||||
- `channel`: str — channel name
|
||||
- `channel`: Literal — name of the channel (one of the values above)
|
||||
- `symbolIsin`: str — instrument ISIN
|
||||
- `timestamp`: str — server timestamp
|
||||
- `data`: Dict[...] — channel-specific real-time data.
|
||||
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
|
||||
numeric ``ServerTimeStamp`` in ``Status``)
|
||||
- `data`: channel-specific real-time data.
|
||||
|
||||
Raises:
|
||||
WebSocketException or ValueError:
|
||||
If the WebSocket connection fails or an exception occurs during data reception.
|
||||
websockets.exceptions.WebSocketException or OSError:
|
||||
Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
|
||||
or ``OSError`` on a network failure).
|
||||
|
||||
Note:
|
||||
Once the connection is established, errors do not raise: a closed connection, invalid JSON
|
||||
or a network error closes the connection and the generator simply ends. If you need a
|
||||
permanent stream, wrap the ``async for`` loop in a reconnect loop. A receive timeout is
|
||||
not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_AsyncClient(auth_client)
|
||||
@@ -1563,13 +1639,14 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
... channels=["best-limit", "order-book"],
|
||||
... symbol_isins=["IR1234567890"]
|
||||
... ):
|
||||
... print(update["data"])
|
||||
... if update["channel"] == "best-limit":
|
||||
... print(update["symbolIsin"], update["data"]["1"]["buy_price"])
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
|
||||
async with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/tse-ifb/live/data/websocket/symbol/isin?"
|
||||
@@ -1581,8 +1658,12 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try:
|
||||
yield loads(await ws.recv())
|
||||
except :
|
||||
try: yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
@@ -49,7 +49,7 @@ from .__io_types import (
|
||||
class DataEngine_TseIfb_SyncClient:
|
||||
|
||||
"""
|
||||
Synchronous client for interacting with the TSE-IFB (Iranian Securities Exchange) Data Engine API.
|
||||
Synchronous (blocking) client for the TSE-IFB Data Engine API (Tehran Stock Exchange and Iran Fara Bourse).
|
||||
|
||||
This class provides high-level synchronous methods to retrieve live and historical market data,
|
||||
order book information, best-limit quotes, OHLCV data, fund info, corporate actions, and other
|
||||
@@ -66,14 +66,14 @@ class DataEngine_TseIfb_SyncClient:
|
||||
__AuthSyncClient (AuthSyncClient): An instance of `AuthSyncClient` used to perform
|
||||
authorized synchronous HTTP requests and WebSocket connections.
|
||||
|
||||
Examples:
|
||||
Example:
|
||||
>>> auth_client = AuthSyncClient.login(
|
||||
... UserName_or_Email="user@example.com",
|
||||
... Password="secure_password"
|
||||
... )
|
||||
>>> data_client = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth_client)
|
||||
>>> instruments = data_client.instruments_static_info_by_name(["فملی", "خودرو"])
|
||||
>>> print(instruments["Data"]["فملی"]["symbolName"])
|
||||
>>> print(instruments["Data"][0]["symbolName"])
|
||||
>>> for update in data_client.websocket_by_name(
|
||||
... channels=["best-limit", "order-book"],
|
||||
... symbol_names=["فملی"]
|
||||
@@ -81,9 +81,19 @@ class DataEngine_TseIfb_SyncClient:
|
||||
... print(update)
|
||||
|
||||
Notes:
|
||||
- This is the blocking twin of ``DataEngine_TseIfb_AsyncClient``: the endpoints, arguments and
|
||||
return types are identical; only the calling style differs (plain calls instead of ``await``,
|
||||
``threading.Event`` instead of ``asyncio.Event``, a normal generator instead of an async
|
||||
generator).
|
||||
- All network requests are synchronous and return after the server responds.
|
||||
- WebSocket methods yield streaming updates and should be used with `for` loops.
|
||||
- Exceptions (ValueError) are raised when the API returns an error or request fails.
|
||||
- Most methods exist in two variants: ``*_by_name`` (symbol name, e.g. "فملی") and
|
||||
``*_by_isin`` (ISIN code).
|
||||
- REST methods raise ``ValueError`` (carrying the server's ``detail`` message) when the
|
||||
API returns an error.
|
||||
- WebSocket methods ARE supported: they are blocking generators and should be used with `for`
|
||||
loops (ideally in a dedicated thread). Once the connection is established, errors do not
|
||||
raise: the stream simply ends (see ``websocket_by_name``).
|
||||
- Prices are in IRR; commission rates are fractions (``0.001`` means 0.1%).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -118,6 +128,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Search for instruments in a specific market by name, title, or partial text (synchronous).
|
||||
|
||||
Both parameters are keyword-only.
|
||||
|
||||
Args:
|
||||
market (Literal["SecuritiesAndFunds", "TreasuryBonds", "StockOptions", "StockFutures"]):
|
||||
Determines which market group to search in.
|
||||
@@ -130,7 +142,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
Returns:
|
||||
Instruments:
|
||||
A dictionary containing:
|
||||
- Data: A list of matched instruments. Each item is one of:
|
||||
- Data: A list of matched instruments (the type of each item can be
|
||||
recognized from its fields, see ``Instruments``). Each item is one of:
|
||||
* SecuritiesAndFunds
|
||||
* TreasuryBonds
|
||||
* StockOptions
|
||||
@@ -187,8 +200,9 @@ class DataEngine_TseIfb_SyncClient:
|
||||
Returns:
|
||||
Instruments:
|
||||
A dictionary containing:
|
||||
- Data: A mapping of symbol_name → Instrument info.
|
||||
Instrument info is one of:
|
||||
- Data: A list of instruments matching the provided symbol names.
|
||||
Identify each item by its ``symbolName`` field (do not rely on the order).
|
||||
Each item is one of:
|
||||
* SecuritiesAndFunds
|
||||
* TreasuryBonds
|
||||
* StockOptions
|
||||
@@ -205,7 +219,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
>>> result = client.instruments_static_info_by_name(
|
||||
... ["فملی", "خودرو"]
|
||||
... )
|
||||
>>> print(result["Data"]["فملی"]["symbolIsin"])
|
||||
>>> print(result["Data"][0]["symbolIsin"])
|
||||
"""
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/tse-ifb/static/data/instruments/symbol/name',
|
||||
@@ -236,7 +250,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
Instruments:
|
||||
A dictionary containing:
|
||||
- Data: A list of instruments matching the provided ISINs.
|
||||
Each item can be SecuritiesAndFunds, TreasuryBonds,
|
||||
Identify each item by its ``symbolIsin`` field (do not rely on
|
||||
the order). Each item can be SecuritiesAndFunds, TreasuryBonds,
|
||||
StockOptions, StockFutures, or None if not found.
|
||||
- Status: Status information returned by the API.
|
||||
|
||||
@@ -393,7 +408,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their symbol names (synchronous).
|
||||
|
||||
This endpoint returns the top-of-the-book order data, including:
|
||||
This endpoint returns the best limit levels of the order book (up to 6 levels per
|
||||
instrument), each including:
|
||||
- Best bid price, quantity, and order count
|
||||
- Best ask price, quantity, and order count
|
||||
|
||||
@@ -406,8 +422,9 @@ class DataEngine_TseIfb_SyncClient:
|
||||
BestLimitResponse:
|
||||
An object containing:
|
||||
- **Data**:
|
||||
Mapping of symbol_name → BestLimitItem
|
||||
Each BestLimitItem includes:
|
||||
Mapping of symbol_name → best limit levels: a dictionary with up to 6
|
||||
levels ("1" = best ... "6" = deepest).
|
||||
Each level is a BestLimitItem that includes:
|
||||
* buy_order_count
|
||||
* buy_quantity
|
||||
* buy_price
|
||||
@@ -423,7 +440,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
|
||||
>>> bl = client.live_best_limit_by_name(["فملی"])
|
||||
>>> print(bl["Data"]["فملی"]["buy_price"])
|
||||
>>> print(bl["Data"]["فملی"]["1"]["buy_price"])
|
||||
"""
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/tse-ifb/live/data/instruments/best-limit/symbol/name',
|
||||
@@ -446,7 +463,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Retrieve **real-time best-limit (best bid/ask)** data for a list of instruments using their ISIN codes (synchronous).
|
||||
|
||||
This endpoint returns the top-of-book order metrics for each ISIN instrument.
|
||||
This endpoint returns the best limit levels (up to 6 per instrument) for each ISIN instrument.
|
||||
|
||||
Args:
|
||||
symbol_isins (List[str]):
|
||||
@@ -456,8 +473,9 @@ class DataEngine_TseIfb_SyncClient:
|
||||
BestLimitResponse:
|
||||
An object containing:
|
||||
- **Data**:
|
||||
Mapping of symbol_isin → BestLimitItem
|
||||
Each BestLimitItem includes:
|
||||
Mapping of symbol_isin → best limit levels: a dictionary with up to 6
|
||||
levels ("1" = best ... "6" = deepest).
|
||||
Each level is a BestLimitItem that includes:
|
||||
* buy_order_count
|
||||
* buy_quantity
|
||||
* buy_price
|
||||
@@ -473,7 +491,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
|
||||
>>> bl = client.live_best_limit_by_isin(["IRO1XYZ12345"])
|
||||
>>> print(bl["Data"]["IRO1XYZ12345"]["sell_quantity"])
|
||||
>>> print(bl["Data"]["IRO1XYZ12345"]["1"]["sell_quantity"])
|
||||
"""
|
||||
data = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/data-engine/tse-ifb/live/data/instruments/best-limit/symbol/isin',
|
||||
@@ -903,7 +921,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"nav": float,
|
||||
"units": int,
|
||||
"marketCap": int,
|
||||
"as_of": datetime
|
||||
"as_of": datetime # typically an ISO-formatted string in the decoded JSON
|
||||
},
|
||||
...
|
||||
},
|
||||
@@ -950,7 +968,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"nav": float,
|
||||
"units": int,
|
||||
"marketCap": int,
|
||||
"as_of": datetime
|
||||
"as_of": datetime # typically an ISO-formatted string in the decoded JSON
|
||||
},
|
||||
...
|
||||
},
|
||||
@@ -1087,10 +1105,14 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by symbol name (synchronous).
|
||||
|
||||
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
|
||||
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
|
||||
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
|
||||
|
||||
Args:
|
||||
symbol_name (str): Trading symbol name (e.g., "فملی").
|
||||
start_timestamp (int): Unix timestamp for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp for the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
|
||||
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
|
||||
Resolution (Literal): Data resolution. Options:
|
||||
- "1m", "5m", "15m", "30m", "1h" for intraday
|
||||
@@ -1164,10 +1186,14 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Fetch historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument by ISIN code (synchronous).
|
||||
|
||||
All parameters are keyword-only. ``Data`` is a single object (not a mapping keyed by
|
||||
instrument) whose lists (``Date_timestamp``, ``Open``, ``High``, ``Low``, ``Close``,
|
||||
``Volume``) are index-aligned: element ``i`` of every list belongs to the same record.
|
||||
|
||||
Args:
|
||||
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
|
||||
start_timestamp (int): Unix timestamp for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp for the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) for the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) for the end of the requested period.
|
||||
AdjustedPrice (bool): Whether to return adjusted prices (True) or raw prices (False).
|
||||
Resolution (Literal): Data resolution. Options:
|
||||
- "1m", "5m", "15m", "30m", "1h" for intraday
|
||||
@@ -1237,10 +1263,12 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Fetch historical corporate actions (dividends and capital increases) for a given instrument by symbol name (synchronous).
|
||||
|
||||
All parameters are keyword-only.
|
||||
|
||||
Args:
|
||||
symbol_name (str): Trading symbol name (e.g., "فملی").
|
||||
start_timestamp (int): Unix timestamp marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp marking the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
|
||||
|
||||
Returns:
|
||||
CorporateActionResponse: TypedDict with structure:
|
||||
@@ -1248,7 +1276,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
|
||||
"Status": Status
|
||||
}
|
||||
Each item in Data includes fields such as:
|
||||
Each item in Data includes fields such as (use ``corporateAction`` to tell the two
|
||||
kinds of items apart):
|
||||
- Date_timestamp: int
|
||||
- corporateAction: str
|
||||
- symbolName: str
|
||||
@@ -1302,10 +1331,12 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"""
|
||||
Fetch historical corporate actions (dividends and capital increases) for a given instrument by ISIN code (synchronous).
|
||||
|
||||
All parameters are keyword-only.
|
||||
|
||||
Args:
|
||||
symbol_isin (str): Instrument ISIN code (e.g., "IRO1FOLD0001").
|
||||
start_timestamp (int): Unix timestamp marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp marking the end of the requested period.
|
||||
start_timestamp (int): Unix timestamp (in seconds) marking the start of the requested period.
|
||||
end_timestamp (int): Unix timestamp (in seconds) marking the end of the requested period.
|
||||
|
||||
Returns:
|
||||
CorporateActionResponse: TypedDict with structure:
|
||||
@@ -1313,7 +1344,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
"Data": List[Union[DividendAction, CapitalIncreaseAction, None]],
|
||||
"Status": Status
|
||||
}
|
||||
Each item in Data includes fields such as:
|
||||
Each item in Data includes fields such as (use ``corporateAction`` to tell the two
|
||||
kinds of items apart):
|
||||
- Date_timestamp: int
|
||||
- corporateAction: str
|
||||
- symbolName: str
|
||||
@@ -1384,15 +1416,26 @@ class DataEngine_TseIfb_SyncClient:
|
||||
]:
|
||||
|
||||
"""
|
||||
WebSocket streaming is not available in the synchronous version.
|
||||
Subscribe to **real-time WebSocket updates** for a list of instruments by symbol name (synchronous).
|
||||
|
||||
The synchronous client does not support real-time WebSocket subscriptions.
|
||||
Although the method signature exists to maintain interface compatibility,
|
||||
it cannot provide live updates like the asynchronous client.
|
||||
Opens a blocking WebSocket connection and yields continuous updates for multiple market
|
||||
channels such as best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs
|
||||
individual trades, contract information, and fund information.
|
||||
|
||||
All requested channels and instruments share a single connection. Every message belongs to
|
||||
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolName"]`` to tell
|
||||
them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (typically from another thread,
|
||||
since the iterating thread is blocked while waiting) to stop it. The check happens each
|
||||
time a message arrives and after a receive timeout (2 seconds without messages), so the
|
||||
stream ends within about 2 seconds at most. The connection is closed automatically when
|
||||
the generator finishes.
|
||||
|
||||
Args:
|
||||
channels (List[str]):
|
||||
List of channels to subscribe to. Possible values are:
|
||||
List of channels to subscribe to. Possible values:
|
||||
- 'best-limit'
|
||||
- 'order-book'
|
||||
- 'ohlcv-last-1m'
|
||||
@@ -1402,19 +1445,43 @@ class DataEngine_TseIfb_SyncClient:
|
||||
- 'fund-info'
|
||||
symbol_names (List[str]):
|
||||
List of trading symbol names to receive updates for (e.g., ["فملی", "خودرو"]).
|
||||
event (Event | None, optional):
|
||||
Optional event object to mimic the async interface.
|
||||
It has no effect in the synchronous client.
|
||||
event (threading.Event | None, optional):
|
||||
Optional ``threading.Event`` used as a stop switch. It must be set for the stream to run:
|
||||
the loop continues while `event.is_set()` is True.
|
||||
Defaults to a new, already-set Event (the stream then runs until the connection ends).
|
||||
|
||||
Returns:
|
||||
Generator:
|
||||
This generator does not yield any data in the synchronous client.
|
||||
Use `DataEngine_TseIfb_AsyncClient.websocket_by_name` for streaming data.
|
||||
Yields:
|
||||
Union[BestLimit_WS_symbolName, OrderBook_WS_symbolName, Aggregate_WS_symbolName,
|
||||
institutional_vs_individual_WS_symbolName, ContractInfo_WS_symbolName, FundInfo_WS_symbolName,
|
||||
OHLCV_WS_symbolName]:
|
||||
One message per update, as a TypedDict that depends on the channel:
|
||||
- **BestLimit_WS_symbolName** for 'best-limit'
|
||||
- **OrderBook_WS_symbolName** for 'order-book'
|
||||
- **OHLCV_WS_symbolName** for 'ohlcv-last-1m'
|
||||
- **Aggregate_WS_symbolName** for 'aggregate'
|
||||
- **institutional_vs_individual_WS_symbolName** for 'institutional-vs-individual'
|
||||
- **ContractInfo_WS_symbolName** for 'contract-info'
|
||||
- **FundInfo_WS_symbolName** for 'fund-info'
|
||||
|
||||
Each yielded object contains:
|
||||
- `channel`: Literal — name of the channel (one of the values above)
|
||||
- `symbolName`: str — instrument symbol name
|
||||
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
|
||||
numeric ``ServerTimeStamp`` in ``Status``)
|
||||
- `data`: channel-specific real-time data.
|
||||
|
||||
Raises:
|
||||
NotImplementedError:
|
||||
Always raised to indicate that real-time WebSocket streaming
|
||||
is not supported in the synchronous version.
|
||||
websockets.exceptions.WebSocketException or OSError:
|
||||
Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
|
||||
or ``OSError`` on a network failure).
|
||||
|
||||
Note:
|
||||
* This generator blocks the calling thread while waiting for messages. Run it in a
|
||||
dedicated thread if the rest of your program must keep working.
|
||||
* Once the connection is established, errors do not raise: a closed connection, invalid
|
||||
JSON or a network error closes the connection and the generator simply ends. If you need
|
||||
a permanent stream, wrap the ``for`` loop in a reconnect loop.
|
||||
* A receive timeout is not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
|
||||
@@ -1422,13 +1489,14 @@ class DataEngine_TseIfb_SyncClient:
|
||||
... channels=["best-limit", "order-book"],
|
||||
... symbol_names=["فملی"]
|
||||
... ):
|
||||
... print(update) # This will not run; method is not implemented
|
||||
... if update["channel"] == "best-limit":
|
||||
... print(update["symbolName"], update["data"]["1"]["buy_price"])
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
|
||||
with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/tse-ifb/live/data/websocket/symbol/name?"
|
||||
@@ -1440,13 +1508,12 @@ class DataEngine_TseIfb_SyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try :
|
||||
yield loads(ws.recv())
|
||||
except :
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def websocket_by_isin(
|
||||
@@ -1478,15 +1545,26 @@ class DataEngine_TseIfb_SyncClient:
|
||||
None
|
||||
]:
|
||||
"""
|
||||
WebSocket streaming is not available in the synchronous version.
|
||||
Subscribe to **real-time WebSocket updates** for a list of instruments using their ISIN codes (synchronous).
|
||||
|
||||
The synchronous client does not support real-time WebSocket subscriptions
|
||||
by ISIN codes. This method exists to maintain interface consistency with
|
||||
the asynchronous client but does not yield any live updates.
|
||||
Opens a blocking WebSocket connection and yields continuous updates for multiple market
|
||||
channels such as best-limit, order book, last 1-minute OHLCV, aggregate data, institutional vs
|
||||
individual trades, contract information, and fund information.
|
||||
|
||||
All requested channels and instruments share a single connection. Every message belongs to
|
||||
one channel and one instrument, so use ``update["channel"]`` and ``update["symbolIsin"]`` to tell
|
||||
them apart.
|
||||
|
||||
Stopping the stream:
|
||||
The loop runs while ``event`` is set. Call ``event.clear()`` (typically from another thread,
|
||||
since the iterating thread is blocked while waiting) to stop it. The check happens each
|
||||
time a message arrives and after a receive timeout (2 seconds without messages), so the
|
||||
stream ends within about 2 seconds at most. The connection is closed automatically when
|
||||
the generator finishes.
|
||||
|
||||
Args:
|
||||
channels (List[str]):
|
||||
List of channels to subscribe to. Possible values are:
|
||||
List of channels to subscribe to. Possible values:
|
||||
- 'best-limit'
|
||||
- 'order-book'
|
||||
- 'ohlcv-last-1m'
|
||||
@@ -1495,21 +1573,44 @@ class DataEngine_TseIfb_SyncClient:
|
||||
- 'contract-info'
|
||||
- 'fund-info'
|
||||
symbol_isins (List[str]):
|
||||
List of instrument ISIN codes to receive updates for
|
||||
(e.g., ["IR1234567890", "IR0987654321"]).
|
||||
event (Event | None, optional):
|
||||
Optional event object to mimic the async interface.
|
||||
It has no effect in the synchronous client.
|
||||
List of instrument ISIN codes to receive updates for (e.g., ["IR1234567890", "IR0987654321"]).
|
||||
event (threading.Event | None, optional):
|
||||
Optional ``threading.Event`` used as a stop switch. It must be set for the stream to run:
|
||||
the loop continues while `event.is_set()` is True.
|
||||
Defaults to a new, already-set Event (the stream then runs until the connection ends).
|
||||
|
||||
Returns:
|
||||
Generator:
|
||||
This generator does not yield any data in the synchronous client.
|
||||
Use `DataEngine_TseIfb_AsyncClient.websocket_by_isin` for real-time streaming.
|
||||
Yields:
|
||||
Union[BestLimit_WS_symbolIsin, OrderBook_WS_symbolIsin, Aggregate_WS_symbolIsin,
|
||||
institutional_vs_individual_WS_symbolIsin, ContractInfo_WS_symbolIsin, FundInfo_WS_symbolIsin,
|
||||
OHLCV_WS_symbolIsin]:
|
||||
One message per update, as a TypedDict that depends on the channel:
|
||||
- **BestLimit_WS_symbolIsin** for 'best-limit'
|
||||
- **OrderBook_WS_symbolIsin** for 'order-book'
|
||||
- **OHLCV_WS_symbolIsin** for 'ohlcv-last-1m'
|
||||
- **Aggregate_WS_symbolIsin** for 'aggregate'
|
||||
- **institutional_vs_individual_WS_symbolIsin** for 'institutional-vs-individual'
|
||||
- **ContractInfo_WS_symbolIsin** for 'contract-info'
|
||||
- **FundInfo_WS_symbolIsin** for 'fund-info'
|
||||
|
||||
Each yielded object contains:
|
||||
- `channel`: Literal — name of the channel (one of the values above)
|
||||
- `symbolIsin`: str — instrument ISIN
|
||||
- `timestamp`: str — ISO-formatted timestamp of the message (a string, unlike the
|
||||
numeric ``ServerTimeStamp`` in ``Status``)
|
||||
- `data`: channel-specific real-time data.
|
||||
|
||||
Raises:
|
||||
NotImplementedError:
|
||||
Always raised to indicate that WebSocket streaming is not supported
|
||||
in the synchronous client.
|
||||
websockets.exceptions.WebSocketException or OSError:
|
||||
Raised only while connecting (for example ``InvalidStatus`` when authentication fails,
|
||||
or ``OSError`` on a network failure).
|
||||
|
||||
Note:
|
||||
* This generator blocks the calling thread while waiting for messages. Run it in a
|
||||
dedicated thread if the rest of your program must keep working.
|
||||
* Once the connection is established, errors do not raise: a closed connection, invalid
|
||||
JSON or a network error closes the connection and the generator simply ends. If you need
|
||||
a permanent stream, wrap the ``for`` loop in a reconnect loop.
|
||||
* A receive timeout is not an error; the generator just keeps waiting.
|
||||
|
||||
Example:
|
||||
>>> client = DataEngine_TseIfb_SyncClient(auth_client)
|
||||
@@ -1517,13 +1618,14 @@ class DataEngine_TseIfb_SyncClient:
|
||||
... channels=["best-limit", "order-book"],
|
||||
... symbol_isins=["IR1234567890"]
|
||||
... ):
|
||||
... print(update) # This will not run; method is not implemented
|
||||
... if update["channel"] == "best-limit":
|
||||
... print(update["symbolIsin"], update["data"]["1"]["buy_price"])
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
|
||||
with connect(
|
||||
uri=(
|
||||
f"wss://core.hedgetech.ir/data-engine/tse-ifb/live/data/websocket/symbol/isin?"
|
||||
@@ -1535,8 +1637,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try :
|
||||
yield loads(ws.recv())
|
||||
except :
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
@@ -1,8 +1,3 @@
|
||||
from .__requests import (
|
||||
SymbolNames,
|
||||
SymbolIsins,
|
||||
)
|
||||
|
||||
from .__response import(
|
||||
SecuritiesAndFunds,
|
||||
StockFutures,
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from typing import (
|
||||
List,
|
||||
TypedDict
|
||||
)
|
||||
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
|
||||
class SymbolNames(TypedDict):
|
||||
"""
|
||||
Represents a collection of instrument symbol names for batch API requests.
|
||||
|
||||
Attributes:
|
||||
symbol_names (List[str]): A list of instrument symbol names (strings) to be queried.
|
||||
|
||||
Example:
|
||||
>>> symbols: SymbolNames = {"symbol_names": ["ETF001", "FUT002", "STK003"]}
|
||||
>>> symbols["symbol_names"][0]
|
||||
'ETF001'
|
||||
"""
|
||||
symbol_names: List[str]
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
class SymbolIsins(TypedDict):
|
||||
"""
|
||||
Represents a collection of instrument ISIN identifiers for batch API requests.
|
||||
|
||||
Attributes:
|
||||
symbol_isins (List[str]): A list of instrument ISIN codes (strings) to be queried.
|
||||
|
||||
Example:
|
||||
>>> isins: SymbolIsins = {"symbol_isins": ["IR0001234567", "IR0009876543"]}
|
||||
>>> isins["symbol_isins"][1]
|
||||
'IR0009876543'
|
||||
"""
|
||||
symbol_isins: List[str]
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,414 @@
|
||||
# ========================================|======================================== #
|
||||
# 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:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
SendOrder_RequestInfo : dict,
|
||||
AuthASyncClient : AuthAsyncClient,
|
||||
ContractNameOrId : str | int ,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
):
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthASyncClient : AuthAsyncClient,
|
||||
):
|
||||
|
||||
|
||||
self.__AuthASyncClient = AuthASyncClient
|
||||
|
||||
self.Customer_FullName : str | None = None
|
||||
self.Customer_TSEBourseCode : str | None = None
|
||||
self.oms_session : HexUUID | None = None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def Get_Captcha(
|
||||
self,
|
||||
OMS : Literal[
|
||||
'Sahra | Karamad',
|
||||
'Sahra | Charisma',
|
||||
]
|
||||
)-> ImageFile:
|
||||
|
||||
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 :
|
||||
|
||||
|
||||
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_TSEBourseCode = data['Data']['Customer_TSEBourseCode']
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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,405 @@
|
||||
# ========================================|======================================== #
|
||||
# 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:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
SendOrder_RequestInfo : dict,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
ContractNameOrId : str | int ,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
):
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
):
|
||||
|
||||
|
||||
self.__AuthSyncClient = AuthSyncClient
|
||||
|
||||
self.Customer_FullName : str | None = None
|
||||
self.Customer_TSEBourseCode : str | None = None
|
||||
self.oms_session : HexUUID | None = None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def Get_Captcha(
|
||||
self,
|
||||
OMS : Literal[
|
||||
'Sahra | Karamad',
|
||||
'Sahra | Charisma',
|
||||
]
|
||||
)-> ImageFile:
|
||||
|
||||
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 :
|
||||
|
||||
|
||||
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_TSEBourseCode = data['Data']['Customer_TSEBourseCode']
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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']
|
||||
@@ -0,0 +1,8 @@
|
||||
from .__tse_ifb import (
|
||||
EmsEngine_TseIfb_SyncClient,
|
||||
EmsEngine_TseIfb_AsyncClient
|
||||
)
|
||||
from .__ime import (
|
||||
EmsEngine_Ime_AsyncClient,
|
||||
EmsEngine_Ime_SyncClient
|
||||
)
|
||||
@@ -0,0 +1,981 @@
|
||||
# ========================================|======================================== #
|
||||
# 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.
|
||||
|
||||
This class provides methods to send, edit, check status,
|
||||
and delete an order after creation.
|
||||
|
||||
An Order instance is usually created via the ``Buy_by_Name``, ``Sell_by_Name``,
|
||||
``Buy_by_isin`` and ``Sell_by_isin`` methods of `EmsEngine_TseIfb_AsyncClient`.
|
||||
Creating an ``Order`` does NOT send anything to the exchange: you must call
|
||||
``await order.send()``.
|
||||
|
||||
Typical life cycle:
|
||||
1. ``order = await client.Buy_by_Name(...)``: build the order (nothing is sent yet).
|
||||
2. ``await order.send()``: submit it. On success ``OrderId`` is set.
|
||||
3. ``await order.Status()``, ``await order.Edit(...)`` or ``await order.Delete()``:
|
||||
follow, modify or cancel the submitted order.
|
||||
|
||||
Note:
|
||||
``send``, ``Edit``, ``Status`` and ``Delete`` never raise. Every error (a non-200 response,
|
||||
a network failure, an unexpected response body, ...) is swallowed and the method just returns
|
||||
``None`` without changing the order (the catch is a bare ``except``, so even
|
||||
``asyncio.CancelledError`` is swallowed). ``send``, ``Edit`` and ``Delete`` also return
|
||||
``None`` on success, so check the outcome on the attributes (``OrderId``, ``is_deleted``,
|
||||
``OrderStatus``, ``Price``, ``Volume``, ...) or call ``Status()``.
|
||||
|
||||
Attributes:
|
||||
ValidityType (str): Validity type of the order: ``'DAY'`` (valid only for the current
|
||||
trading session), ``'GTC'`` (Good Till Cancelled) or ``'GTD'`` (Good Till Date, valid
|
||||
until ``ValidityDate``). ``'FAK'`` and ``'FOK'`` appear only in the type hint of
|
||||
``Edit``. Updated by ``Edit``.
|
||||
ValidityDate (int): Expiration date of the order. Only meaningful for ``'GTD'``; ``0``
|
||||
otherwise. The format is the one expected by the server (the examples use YYYYMMDD,
|
||||
e.g. ``20271206``).
|
||||
SymbolNameOrIsin (str): Symbol name or ISIN code of the security, depending on the method
|
||||
that created the order.
|
||||
Price (int): Order price, in IRR. Updated by ``Edit``.
|
||||
Volume (int): Total requested order volume. Updated by ``Edit``.
|
||||
is_deleted (bool): ``False`` at first. ``True`` once the order has been deleted
|
||||
(``Delete`` succeeded, or the server reports it as ``'Cancelled'``).
|
||||
OrderId (HexUUID | None): Unique identifier of the order (the server's ``order_uuid``).
|
||||
``None`` until ``send`` succeeds, so ``order.OrderId is not None`` means "was sent".
|
||||
OrderOmsId (str | None): Unique identifier of the order assigned by the OMS. ``None`` until
|
||||
``send`` succeeds.
|
||||
OrderStatus (Literal['Unknown', 'InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
|
||||
Current lifecycle status of the order. It is ``'Unknown'`` until a status is received from
|
||||
the server. ``send`` does not set it; it is updated by ``Status``, ``Delete`` and by the
|
||||
reconciliation done in ``Edit`` / ``Delete``.
|
||||
|
||||
Example:
|
||||
>>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
|
||||
>>> if order is not None:
|
||||
... await order.send()
|
||||
... print(order.OrderId)
|
||||
953097ac6ced45ca8ef205b76ca6faf2
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
SendOrder_RequestInfo : dict,
|
||||
AuthASyncClient : AuthAsyncClient,
|
||||
SymbolNameOrIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
):
|
||||
|
||||
"""
|
||||
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_TseIfb_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, Order_ValidityType, ValidityDate, symbolName | symbolIsin, Price, Volume,
|
||||
InitialOrderId}}``. What is actually sent by ``send`` is this dictionary; ``Price`` and
|
||||
``Volume`` below are only stored on the object for reference. ``InitialOrderId`` is a
|
||||
random hex id generated once when the order is created and reused if ``send`` is called
|
||||
again.
|
||||
AuthASyncClient (AuthAsyncClient): Authenticated client used for all the requests of this
|
||||
order.
|
||||
SymbolNameOrIsin (str): Symbol name or ISIN code of the security.
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Total order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to
|
||||
``'DAY'``. Stored as the ``ValidityType`` attribute.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
"""
|
||||
|
||||
|
||||
self.__AuthASyncClient = AuthASyncClient
|
||||
self.__SendOrder_RequestInfo = SendOrder_RequestInfo
|
||||
|
||||
self.ValidityType : str = Order_ValidityType
|
||||
self.ValidityDate : int = ValidityDate
|
||||
self.SymbolNameOrIsin : str = SymbolNameOrIsin
|
||||
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()`` again 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:
|
||||
If a failed ``send()`` is tried again, the same ``InitialOrderId`` is sent again. Whether the
|
||||
server uses it to de-duplicate is not defined here; after a timeout or network error, keep in
|
||||
mind that the first request may already have reached the exchange.
|
||||
|
||||
Example:
|
||||
>>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
|
||||
>>> 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,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> None:
|
||||
|
||||
"""
|
||||
Edits an existing order asynchronously.
|
||||
|
||||
Sends ``PATCH https://core.hedgetech.ir/ems-engine/tse-ifb/order/edit`` (form data:
|
||||
``order_uuid``, ``Order_ValidityType``, ``ValidityDate``, ``Price``, ``Volume``). Nothing happens
|
||||
if the order has not been sent yet (``OrderId is None``). All arguments are keyword-only and all
|
||||
of them are always sent: pass the current value of whatever you do not want to change (note that
|
||||
``Order_ValidityType`` defaults to ``'DAY'``, so an edit without it turns a GTC/GTD order into a
|
||||
DAY order).
|
||||
|
||||
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``) and ``ValidityDate``
|
||||
from the ``ValidityDate`` argument.
|
||||
* Any other status: the real state is read with ``Status()`` to find out what happened.
|
||||
If the order is still active (``InQueue`` / ``PartiallyFilled``) and the server already
|
||||
holds exactly the requested values (``Price``, ``ValidityType``, ``ValidityDate`` and
|
||||
``ExecutedVolume + RemainedVolume == Volume``), the edit is considered applied and the
|
||||
attributes are updated. If the order is no longer active (``Cancelled``, ``Broken`` or
|
||||
``Settled``), only ``OrderStatus`` is updated. Otherwise nothing changes.
|
||||
|
||||
Args:
|
||||
Price (int): New order price, in IRR.
|
||||
Volume (int): New TOTAL order volume. It includes the part that is already executed (the
|
||||
reconciliation above compares it with ``ExecutedVolume + RemainedVolume``), it is not the
|
||||
remaining volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD', 'FAK', 'FOK']): The new order validity type.
|
||||
Defaults to ``'DAY'``. ``'FAK'`` (Fill And Kill) and ``'FOK'`` (Fill Or Kill) are listed
|
||||
only here; the order creation methods accept ``'DAY'``, ``'GTC'`` and ``'GTD'``.
|
||||
ValidityDate (int): New expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
None: Always. Errors are swallowed. Compare ``Price``, ``Volume``, ``ValidityType`` and
|
||||
``ValidityDate`` with what you requested (or call ``Status()``) to know whether the edit
|
||||
was applied.
|
||||
|
||||
Example:
|
||||
>>> await order.Edit(
|
||||
... Price=105,
|
||||
... Volume=15,
|
||||
... Order_ValidityType='GTD',
|
||||
... ValidityDate=20271206,
|
||||
... )
|
||||
>>> 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/tse-ifb/order/edit',
|
||||
data={
|
||||
'order_uuid' : self.OrderId,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'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.ValidityDate = ValidityDate
|
||||
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['RemainedVolume'] + status_respnse['ExecutedVolume'] == Volume
|
||||
and status_respnse['Price'] == Price
|
||||
and status_respnse['ValidityDate'] == ValidityDate
|
||||
and status_respnse['ValidityType'] == Order_ValidityType
|
||||
):
|
||||
|
||||
self.ValidityType = status_respnse['ValidityType']
|
||||
self.ValidityDate = status_respnse['ValidityDate']
|
||||
self.Price = status_respnse['Price']
|
||||
self.Volume = status_respnse['RemainedVolume'] + status_respnse['ExecutedVolume']
|
||||
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/tse-ifb/order/status`` with the ``order_uuid``.
|
||||
Nothing is sent if the order has not been sent yet (``OrderId is None``). As a side effect, a
|
||||
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``,
|
||||
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/tse-ifb/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/tse-ifb/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/tse-ifb/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_TseIfb_AsyncClient:
|
||||
|
||||
"""
|
||||
Asynchronous EMS Engine client for TSE/IFB markets.
|
||||
|
||||
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_Name(...)`` (or ``Sell_by_Name``, ``Buy_by_isin``,
|
||||
``Sell_by_isin``): build an ``Order``. Nothing is sent yet.
|
||||
4. ``await order.send()``: submit the order. See ``Order`` for editing, status and deletion.
|
||||
|
||||
Attributes:
|
||||
Customer_FullName (str | None): Full name of the logged-in customer. ``None`` until
|
||||
``oms_login`` succeeds.
|
||||
Customer_TSEBourseCode (str | None): TSE bourse code of the customer. ``None`` until
|
||||
``oms_login`` succeeds.
|
||||
oms_session (HexUUID | None): Session token obtained after login. ``None`` until
|
||||
``oms_login`` succeeds. The order creation methods return ``None`` while it is ``None``.
|
||||
|
||||
Example:
|
||||
>>> client = EmsEngine_TseIfb_AsyncClient(AuthASyncClient=auth_client)
|
||||
>>> captcha = await client.Get_Captcha('Omex | Parsian')
|
||||
>>> captcha.show()
|
||||
>>> await client.oms_login(
|
||||
... username="user123",
|
||||
... password="pass123",
|
||||
... captcha_value="abcd",
|
||||
... )
|
||||
>>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
|
||||
>>> await order.send()
|
||||
>>> print(order.OrderId)
|
||||
953097ac6ced45ca8ef205b76ca6faf2
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
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 symbol name or ISIN. 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_TSEBourseCode : str | None = None
|
||||
self.oms_session : HexUUID | None = None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
async def Get_Captcha(
|
||||
self,
|
||||
OMS : Literal[
|
||||
'Omex | Parsian',
|
||||
'Omex | Khobregan',
|
||||
'Sahra | Karamad',
|
||||
'Sahra | NIBB',
|
||||
'Sahra | Charisma',
|
||||
]
|
||||
)-> ImageFile:
|
||||
|
||||
"""
|
||||
Retrieves the CAPTCHA image for the specified OMS asynchronously.
|
||||
|
||||
Sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` with the ``oms`` parameter.
|
||||
The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
|
||||
established by this call: call it with the same client right after ``Get_Captcha``.
|
||||
|
||||
Args:
|
||||
OMS (Literal['Omex | Parsian', 'Omex | Khobregan', 'Sahra | Karamad', 'Sahra | NIBB', '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('Omex | Parsian')
|
||||
>>> captcha.show()
|
||||
"""
|
||||
|
||||
Captcha = await self.__AuthASyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/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/tse-ifb/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_TSEBourseCode`` and ``oms_session``
|
||||
are set from the response. ``oms_session`` is required by the order creation methods and is
|
||||
copied into every order when it is created: orders built before a later re-login keep the old
|
||||
session.
|
||||
|
||||
Args:
|
||||
username (str): OMS username.
|
||||
password (str): OMS password.
|
||||
captcha_value (str): Solved CAPTCHA value (the text of the image from ``Get_Captcha``).
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
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/tse-ifb/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_TSEBourseCode = data['Data']['Customer_TSEBourseCode']
|
||||
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_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new buy order by symbol 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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolName (str): Symbol name of the security (e.g., "اطلس").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
|
||||
|
||||
Example:
|
||||
>>> order = await client.Buy_by_Name(
|
||||
... symbolName="اطلس",
|
||||
... Price=100000,
|
||||
... Volume=10,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... await order.send()
|
||||
"""
|
||||
|
||||
await sleep(0)
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/name',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolName' : symbolName,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
async def Sell_by_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new sell order by symbol 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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolName (str): Symbol name of the security (e.g., "اطلس").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
|
||||
|
||||
Example:
|
||||
>>> order = await client.Sell_by_Name(
|
||||
... symbolName="اطلس",
|
||||
... Price=100000,
|
||||
... Volume=10,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... await order.send()
|
||||
"""
|
||||
|
||||
await sleep(0)
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/name',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolName' : symbolName,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def Buy_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new buy order by ISIN code 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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolIsin (str): ISIN code of the security (e.g., "IRO1FOLD0001").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
|
||||
|
||||
Example:
|
||||
>>> order = await client.Buy_by_isin(
|
||||
... symbolIsin="IRO1FOLD0001",
|
||||
... Price=100000,
|
||||
... Volume=10,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... await order.send()
|
||||
"""
|
||||
|
||||
await sleep(0)
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/isin',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolIsin' : symbolIsin,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def Sell_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new sell order by ISIN code 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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolIsin (str): ISIN code of the security (e.g., "IRO1FOLD0001").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists, else ``None``.
|
||||
|
||||
Example:
|
||||
>>> order = await client.Sell_by_isin(
|
||||
... symbolIsin="IRO1FOLD0001",
|
||||
... Price=100000,
|
||||
... Volume=10,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... await order.send()
|
||||
"""
|
||||
|
||||
await sleep(0)
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/isin',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolIsin' : symbolIsin,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
@@ -0,0 +1,994 @@
|
||||
# ========================================|======================================== #
|
||||
# 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.
|
||||
|
||||
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 usually created via the ``Buy_by_Name``, ``Sell_by_Name``,
|
||||
``Buy_by_isin`` and ``Sell_by_isin`` methods of `EmsEngine_TseIfb_SyncClient`.
|
||||
Creating an ``Order`` does NOT send anything to the exchange: you must call
|
||||
``order.send()``.
|
||||
|
||||
Typical life cycle:
|
||||
1. ``order = client.Buy_by_Name(...)``: build the order (nothing is sent yet).
|
||||
2. ``order.send()``: submit it. On success ``OrderId`` is set.
|
||||
3. ``order.Status()``, ``order.Edit(...)`` or ``order.Delete()``: follow, modify or cancel
|
||||
the submitted order.
|
||||
|
||||
Note:
|
||||
``send``, ``Edit``, ``Status`` and ``Delete`` never raise. Every error (a non-200 response,
|
||||
a network failure, an unexpected response body, ...) is swallowed and the method just returns
|
||||
``None`` without changing the order (the catch is a bare ``except``, so even
|
||||
``KeyboardInterrupt`` is swallowed). ``send``, ``Edit`` and ``Delete`` also return ``None`` on
|
||||
success, so check the outcome on the attributes (``OrderId``, ``is_deleted``, ``OrderStatus``,
|
||||
``Price``, ``Volume``, ...) or call ``Status()``.
|
||||
|
||||
Attributes:
|
||||
ValidityType (str): Validity type of the order: ``'DAY'`` (valid only for the current
|
||||
trading session), ``'GTC'`` (Good Till Cancelled) or ``'GTD'`` (Good Till Date, valid
|
||||
until ``ValidityDate``). ``'FAK'`` and ``'FOK'`` appear only in the type hint of
|
||||
``Edit``. Updated by ``Edit``.
|
||||
ValidityDate (int): Expiration date of the order. Only meaningful for ``'GTD'``; ``0``
|
||||
otherwise. The format is the one expected by the server (the examples use YYYYMMDD,
|
||||
e.g. ``20271206``).
|
||||
SymbolNameOrIsin (str): Symbol name or ISIN code of the security, depending on the method
|
||||
that created the order.
|
||||
Price (int): Order price, in IRR. Updated by ``Edit``.
|
||||
Volume (int): Total requested order volume. Updated by ``Edit``.
|
||||
is_deleted (bool): ``False`` at first. ``True`` once the order has been deleted
|
||||
(``Delete`` succeeded, or the server reports it as ``'Cancelled'``).
|
||||
OrderId (HexUUID | None): Unique identifier of the order (the server's ``order_uuid``).
|
||||
``None`` until ``send`` succeeds, so ``order.OrderId is not None`` means "was sent".
|
||||
OrderOmsId (str | None): Unique identifier of the order assigned by the OMS. ``None`` until
|
||||
``send`` succeeds.
|
||||
OrderStatus (Literal['Unknown', 'InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
|
||||
Current lifecycle status of the order. It is ``'Unknown'`` until a status is received from
|
||||
the server. ``send`` does not set it; it is updated by ``Status``, ``Delete`` and by the
|
||||
reconciliation done in ``Edit`` / ``Delete``.
|
||||
|
||||
Example:
|
||||
>>> order = client.Buy_by_Name(symbolName="اهرم", Price=12000, Volume=1000)
|
||||
>>> if order is not None:
|
||||
... order.send()
|
||||
... print(order.OrderId)
|
||||
953097ac6ced45ca8ef205b76ca6faf2
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
SendOrder_RequestInfo : dict,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
SymbolNameOrIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
ValidityDate : int = 0,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
):
|
||||
|
||||
"""
|
||||
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_TseIfb_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, Order_ValidityType, ValidityDate, symbolName | symbolIsin, Price, Volume,
|
||||
InitialOrderId}}``. What is actually sent by ``send`` is this dictionary; ``Price`` and
|
||||
``Volume`` below are only stored on the object for reference. ``InitialOrderId`` is a
|
||||
random hex id generated once when the order is created and reused if ``send`` is called
|
||||
again.
|
||||
AuthSyncClient (AuthSyncClient): Authenticated client used for all the requests of this
|
||||
order.
|
||||
SymbolNameOrIsin (str): Symbol name or ISIN code of the security.
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Total order volume.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to
|
||||
``'DAY'``. Stored as the ``ValidityType`` attribute.
|
||||
|
||||
Example:
|
||||
>>> order = client.Buy_by_Name(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000
|
||||
... )
|
||||
"""
|
||||
|
||||
self.__AuthSyncClient = AuthSyncClient
|
||||
self.__SendOrder_RequestInfo = SendOrder_RequestInfo
|
||||
|
||||
self.ValidityType : str = Order_ValidityType
|
||||
self.ValidityDate : int = ValidityDate
|
||||
self.SymbolNameOrIsin : str = SymbolNameOrIsin
|
||||
self.Price : int = Price
|
||||
self.Volume : int = Volume
|
||||
self.is_deleted : bool = False
|
||||
self.OrderStatus : Literal[
|
||||
'Unknown',
|
||||
'InQueue',
|
||||
'Cancelled',
|
||||
'Broken',
|
||||
'Settled',
|
||||
'PartiallyFilled',
|
||||
] = 'Unknown'
|
||||
|
||||
self.OrderId : HexUUID | None = None
|
||||
self.OrderOmsId : str | None = None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def send(self)-> None:
|
||||
|
||||
"""
|
||||
Send the order to the trading engine.
|
||||
|
||||
Posts ``SendOrder_RequestInfo`` through ``httpx_Client.post``, but only if the order has not
|
||||
been sent yet (``OrderId is None``). Once it was sent successfully, calling ``send()`` again has
|
||||
no effect, so the same ``Order`` object is never submitted twice. If a call fails, the order stays
|
||||
unsent and ``send()`` can be called again.
|
||||
|
||||
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:
|
||||
If a failed ``send()`` is tried again, the same ``InitialOrderId`` is sent again. Whether the
|
||||
server uses it to de-duplicate is not defined here; after a timeout or network error, keep in
|
||||
mind that the first request may already have reached the exchange.
|
||||
|
||||
Example:
|
||||
>>> order.send()
|
||||
>>> 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,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> None:
|
||||
|
||||
"""
|
||||
Edit an existing order.
|
||||
|
||||
Sends ``PATCH https://core.hedgetech.ir/ems-engine/tse-ifb/order/edit`` (form data:
|
||||
``order_uuid``, ``Order_ValidityType``, ``ValidityDate``, ``Price``, ``Volume``). Nothing happens
|
||||
if the order has not been sent yet (``OrderId is None``). All arguments are keyword-only and all
|
||||
of them are always sent: pass the current value of whatever you do not want to change (note that
|
||||
``Order_ValidityType`` defaults to ``'DAY'``, so an edit without it turns a GTC/GTD order into a
|
||||
DAY order).
|
||||
|
||||
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``) and ``ValidityDate``
|
||||
from the ``ValidityDate`` argument.
|
||||
* Any other status: the real state is read with ``Status()`` to find out what happened.
|
||||
If the order is still active (``InQueue`` / ``PartiallyFilled``) and the server already
|
||||
holds exactly the requested values (``Price``, ``ValidityType``, ``ValidityDate`` and
|
||||
``ExecutedVolume + RemainedVolume == Volume``), the edit is considered applied and the
|
||||
attributes are updated. If the order is no longer active (``Cancelled``, ``Broken`` or
|
||||
``Settled``), only ``OrderStatus`` is updated. Otherwise nothing changes.
|
||||
|
||||
Args:
|
||||
Price (int): New order price, in IRR.
|
||||
Volume (int): New TOTAL order volume. It includes the part that is already executed (the
|
||||
reconciliation above compares it with ``ExecutedVolume + RemainedVolume``), it is not the
|
||||
remaining volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD', 'FAK', 'FOK']): The new order validity type.
|
||||
Defaults to ``'DAY'``. ``'FAK'`` (Fill And Kill) and ``'FOK'`` (Fill Or Kill) are listed
|
||||
only here; the order creation methods accept ``'DAY'``, ``'GTC'`` and ``'GTD'``.
|
||||
ValidityDate (int): New expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
None: Always. Errors are swallowed (nothing is raised). Compare ``Price``, ``Volume``,
|
||||
``ValidityType`` and ``ValidityDate`` with what you requested (or call ``Status()``) to
|
||||
know whether the edit was applied.
|
||||
|
||||
Example:
|
||||
>>> order.Edit(
|
||||
... Price=105,
|
||||
... Volume=15,
|
||||
... Order_ValidityType='GTD',
|
||||
... ValidityDate=20271206,
|
||||
... )
|
||||
>>> 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/tse-ifb/order/edit',
|
||||
data={
|
||||
'order_uuid' : self.OrderId,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'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.ValidityDate = ValidityDate
|
||||
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['RemainedVolume'] + status_respnse['ExecutedVolume'] == Volume
|
||||
and status_respnse['Price'] == Price
|
||||
and status_respnse['ValidityDate'] == ValidityDate
|
||||
and status_respnse['ValidityType'] == Order_ValidityType
|
||||
):
|
||||
|
||||
self.ValidityType = status_respnse['ValidityType']
|
||||
self.ValidityDate = status_respnse['ValidityDate']
|
||||
self.Price = status_respnse['Price']
|
||||
self.Volume = status_respnse['RemainedVolume'] + status_respnse['ExecutedVolume']
|
||||
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:
|
||||
|
||||
"""
|
||||
Retrieve the current status of the order.
|
||||
|
||||
This method queries the EMS Engine and returns detailed execution and lifecycle information of
|
||||
the order. It sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/order/status`` with the
|
||||
``order_uuid``. This method requires a valid ``OrderId``: nothing is sent if the order has not
|
||||
been sent yet. As a side effect, a successful call updates ``self.OrderStatus`` from the response
|
||||
(the other attributes, such as ``Price`` and ``Volume``, are not touched).
|
||||
|
||||
Returns:
|
||||
OrderStatus | None: The ``Data`` part of the server's reply when the HTTP status is ``200``,
|
||||
a dictionary with the following keys. ``None`` if the order has not been sent, the status
|
||||
is not ``200`` or any error occurred (network and server errors are silently ignored).
|
||||
|
||||
- order_uuid (HexUUID): Unique identifier of the order.
|
||||
- order_status (Literal['InQueue', 'PartiallyFilled', 'Cancelled', 'Broken', 'Settled']):
|
||||
Current lifecycle state of the order:
|
||||
|
||||
* ``InQueue``: Order is waiting for execution (active).
|
||||
* ``PartiallyFilled``: Part of the order has been executed, the rest is still
|
||||
waiting (active).
|
||||
* ``Cancelled``: Order was cancelled (final).
|
||||
* ``Broken``: Order was rejected or failed (final).
|
||||
* ``Settled``: Order fully executed (final).
|
||||
- Price (int): Order price, in IRR.
|
||||
- Volume (int): Total requested volume.
|
||||
- RemainedVolume (int): Remaining unexecuted volume.
|
||||
- ExecutedVolume (int): Total executed volume.
|
||||
- OrderSide (Literal['Buy', 'Sell']): Side of the order.
|
||||
- ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type.
|
||||
- ValidityDate (int): Expiration date (for GTD orders, ``0`` otherwise).
|
||||
|
||||
Example:
|
||||
>>> status = order.Status()
|
||||
>>> print(status["order_status"])
|
||||
Settled
|
||||
>>> print(status["ExecutedVolume"])
|
||||
1000
|
||||
>>> if status["RemainedVolume"] == 0:
|
||||
... print("Order fully executed")
|
||||
Order fully executed
|
||||
>>> print(status)
|
||||
{
|
||||
"order_uuid": "953097ac6ced45ca8ef205b76ca6faf2",
|
||||
"order_status": "Settled",
|
||||
"Price": 12000,
|
||||
"Volume": 1000,
|
||||
"RemainedVolume": 0,
|
||||
"ExecutedVolume": 1000,
|
||||
"OrderSide": "Buy",
|
||||
"ValidityType": "DAY",
|
||||
"ValidityDate": 0
|
||||
}
|
||||
"""
|
||||
|
||||
try :
|
||||
|
||||
if self.OrderId is not None:
|
||||
|
||||
status_respnse = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/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 :
|
||||
|
||||
"""
|
||||
Cancel/Delete the order.
|
||||
|
||||
Sends ``DELETE https://core.hedgetech.ir/ems-engine/tse-ifb/order/delete`` with the
|
||||
``order_uuid``. Nothing is sent if the order has not been sent yet (``OrderId is None``).
|
||||
|
||||
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 (nothing is raised). After a successful deletion
|
||||
``is_deleted`` becomes ``True``; check it (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/tse-ifb/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_TseIfb_SyncClient:
|
||||
|
||||
"""
|
||||
Synchronous (blocking) EMS Engine client for TSE/IFB markets.
|
||||
|
||||
This client manages authentication, OMS login,
|
||||
and order creation.
|
||||
|
||||
Typical workflow:
|
||||
1. ``captcha = client.Get_Captcha(OMS)``: get the CAPTCHA image and read its value.
|
||||
2. ``client.oms_login(username=..., password=..., captcha_value=...)``: log into the OMS.
|
||||
This sets ``oms_session``.
|
||||
3. ``order = client.Buy_by_Name(...)`` (or ``Sell_by_Name``, ``Buy_by_isin``,
|
||||
``Sell_by_isin``): build an ``Order``. Nothing is sent yet.
|
||||
4. ``order.send()``: submit the order. See ``Order`` for editing, status and deletion.
|
||||
|
||||
Attributes:
|
||||
Customer_FullName (str | None): Full name of the logged-in customer. ``None`` until
|
||||
``oms_login`` succeeds.
|
||||
Customer_TSEBourseCode (str | None): TSE bourse code of the customer. ``None`` until
|
||||
``oms_login`` succeeds.
|
||||
oms_session (HexUUID | None): Session token obtained after login. ``None`` until
|
||||
``oms_login`` succeeds. The order creation methods return ``None`` while it is ``None``.
|
||||
|
||||
Example:
|
||||
>>> client = EmsEngine_TseIfb_SyncClient(AuthSyncClient=auth_client)
|
||||
>>> captcha = client.Get_Captcha('Omex | Parsian')
|
||||
>>> captcha.show()
|
||||
>>> client.oms_login(
|
||||
... username="user123",
|
||||
... password="pass123",
|
||||
... captcha_value="abcd",
|
||||
... )
|
||||
>>> order = client.Buy_by_Name(symbolName="اهرم", Price=12000, Volume=1000)
|
||||
>>> order.send()
|
||||
>>> print(order.OrderId)
|
||||
953097ac6ced45ca8ef205b76ca6faf2
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
):
|
||||
"""
|
||||
Create the EMS Engine client. Nothing is sent to the server.
|
||||
|
||||
Args:
|
||||
AuthSyncClient (AuthSyncClient): An already authenticated ``AuthSyncClient``. Its
|
||||
``httpx_Client`` is used for every request (it also keeps the cookies of the CAPTCHA /
|
||||
OMS login session, so use the same client for ``Get_Captcha`` and ``oms_login``).
|
||||
"""
|
||||
|
||||
|
||||
self.__AuthSyncClient = AuthSyncClient
|
||||
|
||||
self.Customer_FullName : str | None = None
|
||||
self.Customer_TSEBourseCode : str | None = None
|
||||
self.oms_session : HexUUID | None = None
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def Get_Captcha(
|
||||
self,
|
||||
OMS : Literal[
|
||||
'Omex | Parsian',
|
||||
'Omex | Khobregan',
|
||||
'Sahra | Karamad',
|
||||
'Sahra | NIBB',
|
||||
'Sahra | Charisma',
|
||||
]
|
||||
)-> ImageFile:
|
||||
|
||||
"""
|
||||
Fetch captcha image for OMS login.
|
||||
|
||||
Sends ``GET https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` with the ``oms`` parameter.
|
||||
The OMS name is not sent again by ``oms_login``, so ``oms_login`` relies on the session
|
||||
established by this call: call it with the same client right after ``Get_Captcha``.
|
||||
|
||||
Args:
|
||||
OMS (Literal['Omex | Parsian', 'Omex | Khobregan', 'Sahra | Karamad', 'Sahra | NIBB', '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:
|
||||
>>> img = client.Get_Captcha("Omex | Parsian")
|
||||
>>> img.show()
|
||||
"""
|
||||
|
||||
Captcha = self.__AuthSyncClient.httpx_Client.get(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/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 :
|
||||
"""
|
||||
Authenticate user in OMS system.
|
||||
|
||||
Sends ``POST https://core.hedgetech.ir/ems-engine/tse-ifb/oms/login`` (form data: ``username``,
|
||||
``Password``, ``Captcha_Value``). Call ``Get_Captcha`` first, with the same client. All arguments
|
||||
are keyword-only.
|
||||
|
||||
On success (HTTP ``200``) ``Customer_FullName``, ``Customer_TSEBourseCode`` and ``oms_session``
|
||||
are set from the response. ``oms_session`` is required by the order creation methods and is
|
||||
copied into every order when it is created: orders built before a later re-login keep the old
|
||||
session.
|
||||
|
||||
Args:
|
||||
username (str): Trading account username.
|
||||
password (str): Trading account password.
|
||||
captcha_value (str): Captcha solution (the text of the image from ``Get_Captcha``).
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
ValueError: If authentication 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/tse-ifb/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_TSEBourseCode = data['Data']['Customer_TSEBourseCode']
|
||||
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_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a buy order using symbol 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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolName (str): Trading symbol name (e.g., "اهرم").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
|
||||
``None``.
|
||||
|
||||
Example:
|
||||
>>> order = client.Buy_by_Name(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... order.send()
|
||||
"""
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/name',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolName' : symbolName,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
def Sell_by_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a sell order using symbol 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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolName (str): Trading symbol name (e.g., "اهرم").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
|
||||
``None``.
|
||||
|
||||
Example:
|
||||
>>> order = client.Sell_by_Name(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... order.send()
|
||||
"""
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/name',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolName' : symbolName,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def Buy_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a buy order using symbol ISIN.
|
||||
|
||||
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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidBuyVolume`` / ``maxValidBuyVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolIsin (str): Trading symbol ISIN code (e.g., "IRO1FOLD0001").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
|
||||
``None``.
|
||||
|
||||
Example:
|
||||
>>> order = client.Buy_by_isin(
|
||||
... symbolIsin="IRO1FOLD0001",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... order.send()
|
||||
"""
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/isin',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolIsin' : symbolIsin,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def Sell_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
'GTD', # Good Till Date
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a sell order using symbol ISIN.
|
||||
|
||||
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 (for example ``minAllowedPrice`` / ``maxAllowedPrice`` and
|
||||
``minValidSellVolume`` / ``maxValidSellVolume`` from the static instrument info).
|
||||
|
||||
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:
|
||||
symbolIsin (str): Trading symbol ISIN code (e.g., "IRO1FOLD0001").
|
||||
Price (int): Order price, in IRR.
|
||||
Volume (int): Order volume.
|
||||
Order_ValidityType (Literal['DAY', 'GTC', 'GTD']): Order validity type. Defaults to ``'DAY'``:
|
||||
``'DAY'`` is valid only for the current trading session, ``'GTC'`` (Good Till Cancelled)
|
||||
stays active until cancelled and ``'GTD'`` (Good Till Date) stays active until
|
||||
``ValidityDate``.
|
||||
ValidityDate (int): Expiration date, used when the validity type is ``'GTD'``. Defaults to
|
||||
``0``.
|
||||
|
||||
Returns:
|
||||
Order | None: A new, not yet sent ``Order`` if an OMS session exists (logged in), otherwise
|
||||
``None``.
|
||||
|
||||
Example:
|
||||
>>> order = client.Sell_by_isin(
|
||||
... symbolIsin="IRO1FOLD0001",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType='DAY',
|
||||
... ValidityDate=0,
|
||||
... )
|
||||
>>> if order is not None:
|
||||
... order.send()
|
||||
"""
|
||||
|
||||
if self.oms_session is not None:
|
||||
|
||||
return Order(
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume,
|
||||
SendOrder_RequestInfo = {
|
||||
'url' : 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/isin',
|
||||
'data' : {
|
||||
'oms_session' : self.oms_session,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'symbolIsin' : symbolIsin,
|
||||
'Price' : Price,
|
||||
'Volume' : Volume,
|
||||
'InitialOrderId' : uuid4().hex,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
@@ -0,0 +1,2 @@
|
||||
from .__SyncClient import EmsEngine_TseIfb_SyncClient
|
||||
from .__AsyncClient import EmsEngine_TseIfb_AsyncClient
|
||||
@@ -0,0 +1,4 @@
|
||||
from .__response import (
|
||||
OrderStatus,
|
||||
HexUUID,
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
# ========================================|======================================== #
|
||||
# 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']):
|
||||
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','PartiallyFilled','Cancelled','Broken','Settled']
|
||||
Price : int
|
||||
Volume : int
|
||||
RemainedVolume : int
|
||||
ExecutedVolume : int
|
||||
OrderSide : Literal['Buy','Sell']
|
||||
ValidityType : Literal['DAY','GTC','GTD']
|
||||
ValidityDate : int
|
||||
@@ -1,149 +1,376 @@
|
||||
# HedgeTech Python SDK
|
||||
|
||||
HedgeTech Python SDK is a professional, lightweight, and modular Python package designed to provide seamless access to HedgeTech services. The SDK is crafted for developers, data analysts, and algorithmic traders who want to interact with the Tehran Stock Exchange (TSE & IFB) using a clean, reliable, and easy-to-use API. It supports both synchronous and asynchronous workflows, offering maximum flexibility and performance for different application scenarios.
|
||||
HedgeTech Python SDK is a professional, lightweight, and modular Python
|
||||
package designed to provide seamless access to HedgeTech services. The
|
||||
SDK is crafted for developers, data analysts, and algorithmic traders
|
||||
who want to interact with the Tehran Stock Exchange (TSE & IFB) using a
|
||||
clean, reliable, and easy-to-use API.
|
||||
|
||||
> **Note:** This SDK requires Python >= 3.10 and is currently in Beta. Some APIs may change in future releases, but it is stable enough for daily use.
|
||||
It supports both synchronous and asynchronous workflows, offering
|
||||
maximum flexibility and performance for different application scenarios.
|
||||
|
||||
> **Note:** This SDK requires Python >= 3.10 and is production-ready.
|
||||
> Development Status: **5 - Production/Stable**.
|
||||
> The public APIs are stable and safe for long-term use.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Features
|
||||
|
||||
* Secure authentication with both async and sync clients.
|
||||
* Real-time and historical market data retrieval from TSE & IFB.
|
||||
* Modular and maintainable architecture, designed to support multiple engines (DataEngine engines, WebSocket clients, etc.).
|
||||
* Structured request and response types for robust data handling.
|
||||
* Fully asynchronous support for high-performance applications.
|
||||
* Easy to integrate into trading bots, analytics pipelines, dashboards, or WebSocket feeds.
|
||||
- Secure authentication with async and sync clients.
|
||||
- Real-time and historical market data from TSE & IFB.
|
||||
- Full EMS Engine order lifecycle management.
|
||||
- Modular architecture (Auth, DataEngine, EMSEngine).
|
||||
- Structured request/response types.
|
||||
- High-performance asyncio support.
|
||||
- Easy integration with trading bots and dashboards.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Installation
|
||||
|
||||
Install HedgeTech SDK via PyPI:
|
||||
Install via PyPI:
|
||||
|
||||
```
|
||||
``` bash
|
||||
pip install HedgeTech
|
||||
```
|
||||
|
||||
### Updating the Package
|
||||
### Update
|
||||
|
||||
To update HedgeTech SDK to the latest version in your environment, use:
|
||||
|
||||
```
|
||||
``` bash
|
||||
pip install --upgrade HedgeTech
|
||||
```
|
||||
|
||||
## Usage
|
||||
------------------------------------------------------------------------
|
||||
|
||||
The SDK exposes all major clients through the top-level modules, so you generally do **not** need to import internal implementation files directly.
|
||||
## Package Structure
|
||||
|
||||
### Authentication
|
||||
HedgeTech/
|
||||
├── Auth/
|
||||
├── DataEngine/
|
||||
├── EMSEngine/
|
||||
└── __init__.py
|
||||
|
||||
> **Note:** Make sure to use the matching async or sync Auth client depending on your workflow.
|
||||
------------------------------------------------------------------------
|
||||
|
||||
#### Async Authentication
|
||||
## Authentication
|
||||
|
||||
```python
|
||||
All services require authentication.
|
||||
|
||||
> Use matching Sync/Async clients.
|
||||
|
||||
### Async Authentication
|
||||
|
||||
``` python
|
||||
from HedgeTech.Auth import AuthAsyncClient
|
||||
|
||||
auth_async_client = await AuthAsyncClient.login(
|
||||
UserName_or_Email='<YOUR UserName_or_Email>',
|
||||
Password='<YOUR Password>'
|
||||
UserName_or_Email="user@example.com",
|
||||
Password="password"
|
||||
)
|
||||
|
||||
print(auth_async_client.token)
|
||||
```
|
||||
|
||||
#### Sync Authentication
|
||||
### Sync Authentication
|
||||
|
||||
```python
|
||||
``` python
|
||||
from HedgeTech.Auth import AuthSyncClient
|
||||
|
||||
auth_sync_client = AuthSyncClient.login(
|
||||
UserName_or_Email='<YOUR UserName_or_Email>',
|
||||
Password='<YOUR Password>'
|
||||
UserName_or_Email="user@example.com",
|
||||
Password="password"
|
||||
)
|
||||
|
||||
print(auth_sync_client.token)
|
||||
```
|
||||
|
||||
### DataEngine / TSE IFB
|
||||
------------------------------------------------------------------------
|
||||
|
||||
The DataEngine is designed to support multiple engines in a modular way. Each engine provides its own async and sync clients, structured request and response types, and can be integrated with other engines such as WebSocket clients.
|
||||
## DataEngine (Market Data)
|
||||
|
||||
> **Important Note on Sync vs Async:** All clients have the **same method names and behavior** in both Sync and Async versions. The only difference is how they execute: Sync runs in a blocking manner, while Async requires `await` and an event loop. This design allows you to switch between Sync and Async without changing the logic or input/output of your code.
|
||||
The DataEngine module provides unified access to:
|
||||
|
||||
#### Async Data Client
|
||||
- Live market data
|
||||
- Historical OHLCV
|
||||
- Order books
|
||||
- Best limits
|
||||
- WebSocket streams
|
||||
|
||||
```python
|
||||
All engines follow identical Sync/Async APIs.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### Async Data Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.DataEngine import DataEngine_TseIfb_AsyncClient
|
||||
|
||||
client = DataEngine_TseIfb_AsyncClient(auth_async_client)
|
||||
|
||||
data = await client.live_best_limit_by_isin(
|
||||
symbol_isins=['IRT1AHRM0001','IRO1IKCO0001']
|
||||
symbol_isins=["IRT1AHRM0001","IRO1IKCO0001"]
|
||||
)
|
||||
|
||||
print(data)
|
||||
|
||||
# websocket Example
|
||||
|
||||
async for update in client.websocket_by_name(
|
||||
channels=["best-limit", "order-book"],
|
||||
channels=["best-limit","order-book"],
|
||||
symbol_names=["فملی","اطلس"]
|
||||
):
|
||||
|
||||
print(update["data"])
|
||||
```
|
||||
|
||||
#### Sync Data Client
|
||||
------------------------------------------------------------------------
|
||||
|
||||
```python
|
||||
### Sync Data Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.DataEngine import DataEngine_TseIfb_SyncClient
|
||||
|
||||
client = DataEngine_TseIfb_SyncClient(auth_sync_client)
|
||||
|
||||
data = client.historical_ohlcv_by_name(
|
||||
symbolName='مهرگان',
|
||||
symbolName="مهرگان",
|
||||
start_timestamp=0,
|
||||
end_timestamp='1763411432',
|
||||
end_timestamp="1763411432",
|
||||
AdjustedPrice=True,
|
||||
Resolution='D'
|
||||
Resolution="D"
|
||||
)
|
||||
|
||||
print(data)
|
||||
|
||||
# websocket Example
|
||||
|
||||
for update in client.websocket_by_isin(
|
||||
channels=["best-limit", "order-book"],
|
||||
channels=["best-limit","order-book"],
|
||||
symbol_isins=["IR1234567890"]
|
||||
):
|
||||
|
||||
print(update["data"])
|
||||
```
|
||||
|
||||
## Important Notes for Users
|
||||
------------------------------------------------------------------------
|
||||
|
||||
* This SDK requires Python >=3.10.
|
||||
* The SDK is currently in **Beta** — APIs may change in future releases, but it is usable for most workflows.
|
||||
* Always install dependencies with the specified versions to avoid compatibility issues.
|
||||
* Async clients require an asyncio event loop.
|
||||
* All main clients are exposed through top-level modules; you do not need to access internal files.
|
||||
* Keywords and classifiers are chosen to make the SDK easy to find for developers working in finance, trading, and data analysis.
|
||||
## EMSEngine (Order Management)
|
||||
|
||||
The EMSEngine module handles complete order management.
|
||||
|
||||
Supported markets: - TSE - IFB
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### EMSEngine Features
|
||||
|
||||
- Buy/Sell by Name or ISIN
|
||||
- Edit Orders
|
||||
- Cancel/Delete Orders
|
||||
- Real-time Status
|
||||
- Async/Sync Compatibility
|
||||
- Order Object Lifecycle
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Order Lifecycle
|
||||
|
||||
1. Create Order
|
||||
2. Send
|
||||
3. Monitor Status
|
||||
4. Edit (Optional)
|
||||
5. Settle or Delete
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Async Trading Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.EMSEngine import EmsEngine_TseIfb_AsyncClient
|
||||
|
||||
ems = EmsEngine_TseIfb_AsyncClient(auth_async_client)
|
||||
|
||||
captcha = await ems.Get_Captcha("Omex | Parsian")
|
||||
captcha.show()
|
||||
|
||||
await ems.oms_login(
|
||||
username="user",
|
||||
password="pass",
|
||||
captcha_value="1234"
|
||||
)
|
||||
|
||||
order = await ems.Buy_by_Name(
|
||||
symbolName="اطلس",
|
||||
Price=100000,
|
||||
Volume=10
|
||||
)
|
||||
|
||||
await order.send()
|
||||
|
||||
status = await order.Status()
|
||||
print(status)
|
||||
|
||||
await order.Edit(Price=105000, Volume=12)
|
||||
|
||||
await order.Delete()
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Sync Trading Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.EMSEngine import EmsEngine_TseIfb_SyncClient
|
||||
|
||||
ems = EmsEngine_TseIfb_SyncClient(auth_sync_client)
|
||||
|
||||
captcha = ems.Get_Captcha("Omex | Parsian")
|
||||
captcha.show()
|
||||
|
||||
ems.oms_login(
|
||||
username="user",
|
||||
password="pass",
|
||||
captcha_value="1234"
|
||||
)
|
||||
|
||||
order = ems.Sell_by_Name(
|
||||
symbolName="فملی",
|
||||
Price=50000,
|
||||
Volume=5
|
||||
)
|
||||
|
||||
order.send()
|
||||
|
||||
status = order.Status()
|
||||
print(status)
|
||||
|
||||
order.Edit(Price=52000, Volume=6)
|
||||
|
||||
order.Delete()
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Unified API Design
|
||||
|
||||
All Sync and Async clients share:
|
||||
|
||||
- Same method names
|
||||
- Same parameters
|
||||
- Same return types
|
||||
|
||||
Only execution model differs.
|
||||
|
||||
This enables seamless switching between modes.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Invalid credentials raise ValueError
|
||||
- Network errors should be handled by user
|
||||
- Failed requests may return None
|
||||
|
||||
Recommended: wrap calls in try/except.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Performance
|
||||
|
||||
- Non-blocking Async I/O
|
||||
- Connection pooling
|
||||
- Optimized request batching
|
||||
- Suitable for HFT and Algo Trading
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Security
|
||||
|
||||
- JWT Authentication
|
||||
- Encrypted Transport (HTTPS)
|
||||
- No password storage
|
||||
- Session isolation
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Refresh tokens regularly
|
||||
- Monitor order status
|
||||
- Avoid duplicate send()
|
||||
- Validate inputs
|
||||
- Log critical operations
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Modules Overview
|
||||
|
||||
### HedgeTech.Auth
|
||||
|
||||
Handles authentication for all HedgeTech clients. The async (`AuthAsyncClient`) and sync (`AuthSyncClient`) clients are exposed through the top-level Auth module.
|
||||
Provides:
|
||||
|
||||
- AuthAsyncClient
|
||||
- AuthSyncClient
|
||||
- Token management
|
||||
- Session handling
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### HedgeTech.DataEngine
|
||||
|
||||
Handles interactions with the Tehran Stock Exchange IFB and other engines. Provides:
|
||||
Provides:
|
||||
|
||||
* Async and sync clients for fetching market data.
|
||||
* Structured request and response types for predictable and robust data handling.
|
||||
* Modular design that allows integration of additional engines, such as WebSocket clients or future data engines, without modifying the main interface.
|
||||
- Market data APIs
|
||||
- Historical data
|
||||
- WebSocket feeds
|
||||
- Modular engine design
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### HedgeTech.EMSEngine
|
||||
|
||||
Provides:
|
||||
|
||||
- EmsEngine_TseIfb_AsyncClient
|
||||
- EmsEngine_TseIfb_SyncClient
|
||||
- Order class
|
||||
- Lifecycle management
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Roadmap
|
||||
|
||||
- Auto session refresh
|
||||
- Smart retry system
|
||||
- Risk control module
|
||||
- Order batching
|
||||
- Metrics & Monitoring
|
||||
- Strategy framework
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome contributions from the community! Please follow standard Python coding conventions, write clear documentation for any new features, and submit pull requests for improvements or bug fixes.
|
||||
We welcome contributions.
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Follow PEP8
|
||||
- Add tests
|
||||
- Update documentation
|
||||
- Submit Pull Requests
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the **Apache License 2.0**. See the LICENSE file for full details.
|
||||
Licensed under Apache License 2.0.
|
||||
|
||||
See LICENSE file.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Support
|
||||
|
||||
For questions or issues, please open a GitHub issue or contact the HedgeTech team directly. We aim to provide timely support and guidance for all developers using the SDK.
|
||||
GitHub Issues: https://gitea.hedgetech.ir/HedgeTech/HedgeTech/issues
|
||||
|
||||
Email: info@hedgetech.ir
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
© 2026 HedgeTech. All rights reserved.
|
||||
+8
-3
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "HedgeTech"
|
||||
version = "0.1.0"
|
||||
version = "0.4.0b0"
|
||||
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,6 +28,8 @@ classifiers = [
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Programming Language :: Python :: 3.14",
|
||||
"Programming Language :: Python :: 3.15",
|
||||
|
||||
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
@@ -54,9 +56,12 @@ dependencies = [
|
||||
"zstd<=1.5.7.2",
|
||||
"PyJWT<=2.10.1",
|
||||
"websockets<=15.0.1",
|
||||
"pillow<=12.0.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://hedgetech.ir/landing/"
|
||||
Documentation = "https://github.com/HedgeTech-ir/HedgeTech/blob/main/README.md"
|
||||
Repository = "https://github.com/HedgeTech-ir/HedgeTech"
|
||||
Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md"
|
||||
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
|
||||
Store = https://store.hedgetech.ir/
|
||||
LinkedIn = https://www.linkedin.com/company/hedgetech-ir/
|
||||
Reference in new issue
Block a user