Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
a592139f25 | ||
|
|
ad75e49165 | ||
|
|
98938e074b | ||
|
|
c1bad73a1f | ||
|
|
e2c69bd3af | ||
|
|
3012cba332 | ||
|
|
785f5ead28 | ||
|
|
8ee4a0ad9b | ||
|
|
0bda01a33e | ||
|
|
82fb01c8be | ||
|
|
aff75d2175 | ||
|
|
ebc7f080b2 | ||
|
|
7198bb5ba7 | ||
|
|
929a3d95f0 | ||
|
|
4b4db162ec | ||
|
|
b802599674 | ||
|
|
d8deba13e8 | ||
|
|
0218899d5a | ||
|
|
5a72ba634f | ||
|
|
937ebd2eac | ||
|
|
fa3712a7d5 | ||
|
|
57db8d7c79 | ||
|
|
a2a6b16aba | ||
|
|
a26dc814ea | ||
|
|
a151a22f7b | ||
|
|
aaadfcd3cd | ||
|
|
0c6278c6dc | ||
|
|
972217337a | ||
|
|
56f0f0389e | ||
|
|
cf40d7200a | ||
|
|
822b4a67c2 | ||
|
|
bb9adb77ee | ||
|
|
8132c73110 | ||
|
|
2657d0f4f6 | ||
|
|
885644c0c7 | ||
|
|
98d98c09ab | ||
|
|
9560e764b6 | ||
|
|
d834a4a00a | ||
|
|
45a01ff7f6 | ||
|
|
27dbc4cb36 | ||
|
|
6797cfe325 | ||
|
|
3e6688cc70 | ||
|
|
8e54971730 | ||
|
|
8d38af517e |
No files matched your search
+4
-1
@@ -207,4 +207,7 @@ marimo/_lsp/
|
||||
__marimo__/
|
||||
*.env*
|
||||
*.ipynb
|
||||
requirements.txt
|
||||
requirements.txt
|
||||
*test*.py
|
||||
|
||||
.vscode
|
||||
@@ -0,0 +1,154 @@
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from .__utils import RetriableAsyncClient
|
||||
from httpx import (
|
||||
AsyncClient ,
|
||||
Timeout ,
|
||||
)
|
||||
from jwt import decode
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
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,
|
||||
and make authorized HTTP requests using an `httpx.AsyncClient`.
|
||||
|
||||
Attributes:
|
||||
httpx_Client (AsyncClient): An instance of `httpx.AsyncClient` configured with authentication headers.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'.
|
||||
|
||||
Example:
|
||||
>>> client = await AuthAsyncClient.login(
|
||||
... UserName_or_Email="user@example.com",
|
||||
... Password="secure_password"
|
||||
... )
|
||||
>>> client.token['Authorization'][:10]
|
||||
'eyJ0eXAiOi'
|
||||
>>> client.Permissions # Decoded JWT payload
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
httpx_Client:AsyncClient,
|
||||
token:dict[str,str],
|
||||
):
|
||||
"""
|
||||
Initialize the AuthAsyncClient with an existing httpx.AsyncClient and authentication token.
|
||||
|
||||
Args:
|
||||
httpx_Client (AsyncClient): Preconfigured AsyncClient for making authorized requests.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens.
|
||||
"""
|
||||
|
||||
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.
|
||||
|
||||
Raises:
|
||||
ValueError: If the JWT cannot be decoded.
|
||||
"""
|
||||
|
||||
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,
|
||||
*,
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Raises:
|
||||
ValueError: If the login attempt fails (e.g., wrong credentials).
|
||||
|
||||
Example:
|
||||
>>> client = await AuthAsyncClient.login(
|
||||
... UserName_or_Email="user@example.com",
|
||||
... Password="secure_password"
|
||||
... )
|
||||
>>> 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={
|
||||
'UserName_or_Email' : UserName_or_Email,
|
||||
'Password' : Password
|
||||
}
|
||||
)
|
||||
|
||||
if login_res.status_code == 201:
|
||||
|
||||
token = login_res.json()
|
||||
headers = {'origin' : 'https://core.hedgetech.ir'}
|
||||
headers.update(token)
|
||||
|
||||
httpx_Client = RetriableAsyncClient(
|
||||
client = AsyncClient(
|
||||
verify=True ,
|
||||
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'))
|
||||
@@ -0,0 +1,157 @@
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from .__utils import RetriableSyncClient
|
||||
from httpx import (
|
||||
Client ,
|
||||
Timeout ,
|
||||
)
|
||||
from jwt import decode
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
|
||||
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,
|
||||
and make authorized HTTP requests using an `httpx.Client`.
|
||||
|
||||
Attributes:
|
||||
httpx_Client (Client): An instance of `httpx.Client` configured with authentication headers.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens, typically including 'Authorization'.
|
||||
|
||||
Example:
|
||||
>>> client = AuthSyncClient.login(
|
||||
... UserName_or_Email="user@example.com",
|
||||
... Password="secure_password"
|
||||
... )
|
||||
>>> client.token['Authorization'][:10]
|
||||
'eyJ0eXAiOi'
|
||||
>>> client.Permissions # Decoded JWT payload
|
||||
{'sub': 'user_id', 'exp': 1700350200, ...}
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
httpx_Client:Client,
|
||||
token:dict[str,str],
|
||||
):
|
||||
"""
|
||||
Initialize the AuthSyncClient with an existing httpx.Client and authentication token.
|
||||
|
||||
Args:
|
||||
httpx_Client (Client): Preconfigured Client for making authorized requests.
|
||||
token (dict[str, str]): Dictionary containing authentication tokens.
|
||||
"""
|
||||
|
||||
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.
|
||||
|
||||
Raises:
|
||||
ValueError: If the JWT cannot be decoded.
|
||||
"""
|
||||
|
||||
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,
|
||||
*,
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Raises:
|
||||
ValueError: If the login attempt fails (e.g., wrong credentials).
|
||||
|
||||
Example:
|
||||
>>> client = AuthSyncClient.login(
|
||||
... UserName_or_Email="user@example.com",
|
||||
... Password="secure_password"
|
||||
... )
|
||||
>>> 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={
|
||||
'UserName_or_Email' : UserName_or_Email,
|
||||
'Password' : Password
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if login_res.status_code == 201:
|
||||
|
||||
token = login_res.json()
|
||||
headers = {'origin' : 'https://core.hedgetech.ir'}
|
||||
headers.update(token)
|
||||
|
||||
httpx_Client = RetriableSyncClient(
|
||||
client = Client(
|
||||
verify=True ,
|
||||
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'))
|
||||
@@ -0,0 +1,2 @@
|
||||
from .__AuthSyncClient import AuthSyncClient
|
||||
from .__AuthAsyncClient import AuthAsyncClient
|
||||
@@ -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,349 @@
|
||||
# ========================================|======================================== #
|
||||
# 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:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthAsyncClient : AuthAsyncClient,
|
||||
):
|
||||
|
||||
self.__AuthAsyncClient = AuthAsyncClient
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def search_contracts(
|
||||
self,
|
||||
market : Literal[
|
||||
"IMEDepositCertificate",
|
||||
"IMEFutures",
|
||||
"IMEOption",
|
||||
],
|
||||
Search_char : str,
|
||||
)-> Contracts :
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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 :
|
||||
|
||||
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:
|
||||
|
||||
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 :
|
||||
|
||||
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:
|
||||
|
||||
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 :
|
||||
|
||||
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
|
||||
]:
|
||||
|
||||
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
|
||||
]:
|
||||
|
||||
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,339 @@
|
||||
# ========================================|======================================== #
|
||||
# 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:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
):
|
||||
|
||||
self.__AuthSyncClient = AuthSyncClient
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def search_contracts(
|
||||
self,
|
||||
market : Literal[
|
||||
"IMEDepositCertificate",
|
||||
"IMEFutures",
|
||||
"IMEOption",
|
||||
],
|
||||
Search_char : str,
|
||||
)-> Contracts :
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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:
|
||||
|
||||
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 :
|
||||
|
||||
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:
|
||||
|
||||
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 :
|
||||
|
||||
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:
|
||||
|
||||
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 :
|
||||
|
||||
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
|
||||
]:
|
||||
|
||||
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
|
||||
]:
|
||||
|
||||
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
@@ -0,0 +1,8 @@
|
||||
from .__tse_ifb import (
|
||||
DataEngine_TseIfb_SyncClient,
|
||||
DataEngine_TseIfb_AsyncClient
|
||||
)
|
||||
from .__ime import (
|
||||
DataEngine_Ime_SyncClient,
|
||||
DataEngine_Ime_AsyncClient
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
from .__SyncClient import DataEngine_TseIfb_SyncClient
|
||||
from .__AsyncClient import DataEngine_TseIfb_AsyncClient
|
||||
@@ -0,0 +1,34 @@
|
||||
from .__response import(
|
||||
SecuritiesAndFunds,
|
||||
StockFutures,
|
||||
StockOptions,
|
||||
TreasuryBonds,
|
||||
Instruments,
|
||||
|
||||
BestLimitResponse,
|
||||
OrderBookResponse,
|
||||
AggregateResponse,
|
||||
Institutional_vs_IndividualItemResponse,
|
||||
ContractInfoResponse,
|
||||
FundInfoResponse,
|
||||
OHLCVLast1mResponse,
|
||||
OverviewResponse,
|
||||
|
||||
OHLCVResponse,
|
||||
CorporateActionResponse,
|
||||
|
||||
BestLimit_WS_symbolIsin,
|
||||
BestLimit_WS_symbolName,
|
||||
OrderBook_WS_symbolIsin,
|
||||
OrderBook_WS_symbolName,
|
||||
Aggregate_WS_symbolIsin,
|
||||
Aggregate_WS_symbolName,
|
||||
institutional_vs_individual_WS_symbolIsin,
|
||||
institutional_vs_individual_WS_symbolName,
|
||||
ContractInfo_WS_symbolIsin,
|
||||
ContractInfo_WS_symbolName,
|
||||
FundInfo_WS_symbolIsin,
|
||||
FundInfo_WS_symbolName,
|
||||
OHLCV_WS_symbolIsin,
|
||||
OHLCV_WS_symbolName,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,4 @@
|
||||
from .__tse_ifb import (
|
||||
EmsEngine_TseIfb_SyncClient,
|
||||
EmsEngine_TseIfb_AsyncClient
|
||||
)
|
||||
@@ -0,0 +1,856 @@
|
||||
# ========================================|======================================== #
|
||||
# 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
|
||||
|
||||
# ========================================|======================================== #
|
||||
# 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
|
||||
`EmsEngine_TseIfb_AsyncClient` methods.
|
||||
"""
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
):
|
||||
|
||||
"""
|
||||
Represents a stock order in the EMS Engine for TSE IFB.
|
||||
|
||||
This class allows sending, editing, deleting, and checking the status
|
||||
of a stock order using an asynchronous client.
|
||||
|
||||
Attributes
|
||||
----------
|
||||
ValidityType : str
|
||||
Type of order validity ('DAY', 'GTC', 'GTD', 'FAK', 'FOK').
|
||||
ValidityDate : int
|
||||
Expiration date of the order (for 'GTD' type).
|
||||
SymbolNameOrIsin : str
|
||||
Symbol name or ISIN code of the security.
|
||||
Price : int
|
||||
Order price.
|
||||
Volume : int
|
||||
Order volume.
|
||||
is_deleted : bool
|
||||
True if the order has been deleted.
|
||||
OrderId : HexUUID | None
|
||||
Unique identifier of the order after submission.
|
||||
|
||||
Methods
|
||||
-------
|
||||
send()
|
||||
Sends the order asynchronously to the EMS engine.
|
||||
Edit(Order_ValidityType, ValidityDate, Price, Volume)
|
||||
Edits the existing order asynchronously.
|
||||
Status()
|
||||
Retrieves the current status of the order asynchronously.
|
||||
Delete()
|
||||
Deletes the order asynchronously.
|
||||
"""
|
||||
|
||||
|
||||
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[
|
||||
None,
|
||||
'InQueue' ,
|
||||
'Cancelled',
|
||||
'Broken',
|
||||
'Settled',
|
||||
]
|
||||
|
||||
self.OrderId : HexUUID | None = None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def send(self)-> None:
|
||||
|
||||
"""
|
||||
Sends the order to the EMS engine asynchronously.
|
||||
|
||||
If the order has not been sent before, it posts the request
|
||||
using the provided AuthAsyncClient.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
|
||||
>>> await order.send()
|
||||
>>> 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 :
|
||||
|
||||
self.OrderId = SendOrder_Response.json()['Data']['order_uuid']
|
||||
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.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
Order_ValidityType : str
|
||||
The new order validity type.
|
||||
ValidityDate : int
|
||||
New expiration date if validity type is 'GTD'.
|
||||
Price : int
|
||||
New order price.
|
||||
Volume : int
|
||||
New order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> await order.Edit(
|
||||
Price = 105,
|
||||
Volume = 15,
|
||||
Order_ValidityType = 'GTD',
|
||||
ValidityDate = 20271206
|
||||
)
|
||||
"""
|
||||
|
||||
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.OrderId = Edit_response['Data']['order_uuid']
|
||||
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']
|
||||
self.OrderStatus = 'InQueue'
|
||||
return None
|
||||
|
||||
case _ :
|
||||
|
||||
status_respnse = await self.Status()
|
||||
|
||||
if status_respnse and (
|
||||
status_respnse['order_status'] == '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 = 'InQueue'
|
||||
return None
|
||||
|
||||
elif status_respnse and status_respnse['order_status'] != '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.
|
||||
|
||||
Returns
|
||||
-------
|
||||
OrderStatus | None
|
||||
A dictionary containing the current order status with the following keys:
|
||||
- order_uuid: HexUUID, unique identifier of the order.
|
||||
- order_status: 'InQueue' | 'Cancelled' | 'Broken' | 'Settled'
|
||||
- Price: int, the order price.
|
||||
- Volume: int, the original order volume.
|
||||
- RemainedVolume: int, volume remaining unexecuted.
|
||||
- ExecutedVolume: int, executed volume.
|
||||
- OrderSide: 'Buy' | 'Sell', the order side.
|
||||
- ValidityType: 'DAY' | 'GTC' | 'GTD', the type of order validity.
|
||||
- ValidityDate: int, expiration date if applicable.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> 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
|
||||
}
|
||||
"""
|
||||
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 the order asynchronously.
|
||||
|
||||
Sets `is_deleted` to True if successful.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
AuthASyncClient : AuthAsyncClient,
|
||||
):
|
||||
|
||||
"""
|
||||
Asynchronous client for interacting with the EMS Engine (TSE IFB).
|
||||
|
||||
Provides methods for logging in, retrieving CAPTCHA, and creating buy/sell orders
|
||||
by symbol name or ISIN.
|
||||
|
||||
Attributes
|
||||
----------
|
||||
Customer_FullName : str | None
|
||||
Full name of the logged-in customer.
|
||||
Customer_TSEBourseCode : str | None
|
||||
TSE bourse code of the customer.
|
||||
oms_session : HexUUID | None
|
||||
Session token obtained after login.
|
||||
|
||||
Methods
|
||||
-------
|
||||
Get_Captcha(OMS)
|
||||
Retrieves the login CAPTCHA image asynchronously.
|
||||
|
||||
oms_login(username, password, captcha_value)
|
||||
Logs into the OMS asynchronously.
|
||||
|
||||
Buy_by_Name(Order_ValidityType, ValidityDate, symbolName, Price, Volume)
|
||||
Creates a new buy order by symbol name asynchronously.
|
||||
|
||||
Sell_by_Name(Order_ValidityType, ValidityDate, symbolName, Price, Volume)
|
||||
Creates a new sell order by symbol name asynchronously.
|
||||
|
||||
Buy_by_isin(Order_ValidityType, ValidityDate, symbolIsin, Price, Volume)
|
||||
Creates a new buy order by ISIN asynchronously.
|
||||
|
||||
Sell_by_isin(Order_ValidityType, ValidityDate, symbolIsin, Price, Volume)
|
||||
Creates a new sell order by ISIN asynchronously.
|
||||
"""
|
||||
|
||||
self.__AuthASyncClient = AuthASyncClient
|
||||
|
||||
self.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',
|
||||
'Sahra | Karamad',
|
||||
'Sahra | NIBB',
|
||||
]
|
||||
)-> ImageFile:
|
||||
|
||||
"""
|
||||
Retrieves the CAPTCHA image for the specified OMS asynchronously.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
OMS : str
|
||||
OMS identifier ('Omex | Parsian' or 'Sahra | Karamad').
|
||||
|
||||
Returns
|
||||
-------
|
||||
ImageFile
|
||||
The CAPTCHA image object.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If the request fails or returns an error.
|
||||
|
||||
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.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
username : str
|
||||
OMS username.
|
||||
password : str
|
||||
OMS password.
|
||||
captcha_value : str
|
||||
Solved CAPTCHA value.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If login fails or CAPTCHA is invalid.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> await client.oms_login(
|
||||
username = "user123",
|
||||
password = "pass123",
|
||||
captcha_value = "abcd"
|
||||
)
|
||||
>>> print(client.oms_session)
|
||||
'session_token_here'
|
||||
"""
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new buy order by symbol name asynchronously.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
Order_ValidityType : str
|
||||
Order validity type.
|
||||
ValidityDate : int
|
||||
Expiration date if validity type is 'GTD'.
|
||||
symbolName : str
|
||||
Symbol name of the security.
|
||||
Price : int
|
||||
Order price.
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
A new Order instance if OMS session exists, else None.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> order = await client.Buy_by_Name(
|
||||
symbolName="اطلس",
|
||||
Price=100000,
|
||||
Volume=10,
|
||||
Order_ValidityType = 'DAY',
|
||||
ValidityDate = 0
|
||||
)
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new sell order by symbol name asynchronously.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
Order_ValidityType : str
|
||||
Order validity type.
|
||||
ValidityDate : int
|
||||
Expiration date if validity type is 'GTD'.
|
||||
symbolName : str
|
||||
Symbol name of the security.
|
||||
Price : int
|
||||
Order price.
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
A new Order instance if OMS session exists, else None.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> order = await client.Sell_by_Name(
|
||||
symbolName="اطلس",
|
||||
Price=100000,
|
||||
Volume=10,
|
||||
Order_ValidityType = 'DAY',
|
||||
ValidityDate = 0
|
||||
)
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new buy order by symbol isin asynchronously.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
Order_ValidityType : str
|
||||
Order validity type.
|
||||
ValidityDate : int
|
||||
Expiration date if validity type is 'GTD'.
|
||||
symbolIsin : str
|
||||
Symbol name of the security.
|
||||
Price : int
|
||||
Order price.
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
A new Order instance if OMS session exists, else None.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> order = await client.Buy_by_isin(
|
||||
symbolName="اطلس",
|
||||
Price=100000,
|
||||
Volume=10,
|
||||
Order_ValidityType = 'DAY',
|
||||
ValidityDate = 0
|
||||
)
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Creates a new sell order by symbol isin asynchronously.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
Order_ValidityType : str
|
||||
Order validity type.
|
||||
ValidityDate : int
|
||||
Expiration date if validity type is 'GTD'.
|
||||
symbolIsin : str
|
||||
Symbol name of the security.
|
||||
Price : int
|
||||
Order price.
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
A new Order instance if OMS session exists, else None.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> order = await client.Sell_by_isin(
|
||||
symbolName="اطلس",
|
||||
Price=100000,
|
||||
Volume=10,
|
||||
Order_ValidityType = 'DAY',
|
||||
ValidityDate = 0
|
||||
)
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@@ -0,0 +1,874 @@
|
||||
# ========================================|======================================== #
|
||||
# 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
|
||||
|
||||
# ========================================|======================================== #
|
||||
# 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
|
||||
`EmsEngine_TseIfb_SyncClient` methods.
|
||||
"""
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
):
|
||||
|
||||
"""
|
||||
Initialize a new Order object.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
SendOrder_RequestInfo : dict
|
||||
HTTP request configuration for sending the order.
|
||||
|
||||
AuthSyncClient : AuthSyncClient
|
||||
Authenticated HTTP client.
|
||||
|
||||
Order_ValidityType : Literal
|
||||
Order validity type.
|
||||
|
||||
ValidityDate : int
|
||||
Expiration date (for GTD orders).
|
||||
|
||||
SymbolNameOrIsin : str
|
||||
Symbol name or ISIN code.
|
||||
|
||||
Price : int
|
||||
Order price.
|
||||
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> 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[
|
||||
None,
|
||||
'InQueue' ,
|
||||
'Cancelled',
|
||||
'Broken',
|
||||
'Settled',
|
||||
]
|
||||
|
||||
self.OrderId : HexUUID | None = None
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def send(self)-> None:
|
||||
|
||||
"""
|
||||
Send the order to the trading engine.
|
||||
|
||||
This method submits the order to EMS Engine
|
||||
and assigns OrderId on success.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Notes
|
||||
-----
|
||||
- Can be called only once.
|
||||
- Subsequent calls have no effect.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> order.send()
|
||||
>>> print(order.OrderId)
|
||||
'0xA23F...'
|
||||
"""
|
||||
|
||||
try :
|
||||
|
||||
if self.OrderId is None :
|
||||
|
||||
SendOrder_Response = self.__AuthSyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
|
||||
|
||||
match SendOrder_Response.status_code :
|
||||
|
||||
case 200 :
|
||||
|
||||
self.OrderId = SendOrder_Response.json()['Data']['order_uuid']
|
||||
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.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
Order_ValidityType : Literal
|
||||
New validity type.
|
||||
|
||||
ValidityDate : int
|
||||
New expiration date.
|
||||
|
||||
Price : int
|
||||
New order price.
|
||||
|
||||
Volume : int
|
||||
New order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Raises
|
||||
------
|
||||
None
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> order.Edit(
|
||||
Price = 105,
|
||||
Volume = 15,
|
||||
Order_ValidityType = 'GTD',
|
||||
ValidityDate = 20271206
|
||||
)
|
||||
"""
|
||||
|
||||
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.OrderId = Edit_response['Data']['order_uuid']
|
||||
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']
|
||||
self.OrderStatus = 'InQueue'
|
||||
return None
|
||||
|
||||
case _ :
|
||||
|
||||
status_respnse = self.Status()
|
||||
|
||||
if status_respnse and (
|
||||
status_respnse['order_status'] == '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 = 'InQueue'
|
||||
return None
|
||||
|
||||
elif status_respnse and status_respnse['order_status'] != '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.
|
||||
|
||||
Returns
|
||||
-------
|
||||
OrderStatus | None
|
||||
A dictionary containing order status information.
|
||||
|
||||
On success, the returned object contains the following fields:
|
||||
|
||||
- order_uuid : HexUUID
|
||||
Unique identifier of the order.
|
||||
|
||||
- order_status : Literal['InQueue', 'Cancelled', 'Broken', 'Settled']
|
||||
Current lifecycle state of the order.
|
||||
|
||||
* InQueue : Order is waiting for execution.
|
||||
* Cancelled : Order was cancelled.
|
||||
* Broken : Order was rejected or failed.
|
||||
* Settled : Order fully executed.
|
||||
|
||||
- Price : int
|
||||
Order price.
|
||||
|
||||
- Volume : int
|
||||
Total requested volume.
|
||||
|
||||
- RemainedVolume : int
|
||||
Remaining unexecuted volume.
|
||||
|
||||
- ExecutedVolume : int
|
||||
Total executed volume.
|
||||
|
||||
- OrderSide : Literal['Buy', 'Sell']
|
||||
Side of the order.
|
||||
|
||||
- ValidityType : Literal['DAY', 'GTC', 'GTD']
|
||||
Order validity type.
|
||||
|
||||
- ValidityDate : int
|
||||
Expiration date (for GTD orders).
|
||||
|
||||
Returns None if the request fails or if the order
|
||||
has not been sent yet.
|
||||
|
||||
Raises
|
||||
------
|
||||
None
|
||||
|
||||
Notes
|
||||
-----
|
||||
- This method requires a valid OrderId.
|
||||
- If OrderId is None, None is returned.
|
||||
- Network or server errors are silently ignored.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> status = order.Status()
|
||||
>>> print(status["order_status"])
|
||||
'Settled'
|
||||
|
||||
>>> print(status["ExecutedVolume"])
|
||||
1000
|
||||
|
||||
>>> if status["RemainedVolume"] == 0:
|
||||
... print("Order fully executed")
|
||||
|
||||
Example Output
|
||||
--------------
|
||||
{
|
||||
"order_uuid": "0xA91F23BC...",
|
||||
"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 request to EMS Engine.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Notes
|
||||
-----
|
||||
After deletion, `is_deleted` becomes True.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> 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 EMS Engine client for TSE/IFB markets.
|
||||
|
||||
This client manages authentication, OMS login,
|
||||
and order creation.
|
||||
"""
|
||||
|
||||
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[
|
||||
'Omex | Parsian',
|
||||
'Sahra | Karamad',
|
||||
'Sahra | NIBB',
|
||||
]
|
||||
)-> ImageFile:
|
||||
|
||||
"""
|
||||
Fetch captcha image for OMS login.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
OMS : Literal
|
||||
OMS provider name.
|
||||
|
||||
Returns
|
||||
-------
|
||||
ImageFile
|
||||
Captcha image.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If server returns error.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> 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.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
username : str
|
||||
Trading account username.
|
||||
|
||||
password : str
|
||||
Trading account password.
|
||||
|
||||
captcha_value : str
|
||||
Captcha solution.
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If authentication fails.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> client.oms_login(
|
||||
username = "user123",
|
||||
password = "pass123",
|
||||
captcha_value = "abcd"
|
||||
)
|
||||
"""
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a buy order using symbol name.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
symbolName : str
|
||||
Trading symbol name.
|
||||
|
||||
Price : int
|
||||
Order price.
|
||||
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
Order instance if logged in, otherwise None.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> order = client.Buy_by_Name(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType = 'DAY',
|
||||
... ValidityDate = 0
|
||||
... )
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a sell order using symbol name.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
symbolName : str
|
||||
Trading symbol name.
|
||||
|
||||
Price : int
|
||||
Order price.
|
||||
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
Order instance if logged in, otherwise None.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> order = client.Sell_by_Name(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType = 'DAY',
|
||||
... ValidityDate = 0
|
||||
... )
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a buy order using symbol isin.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
symbolIsin : str
|
||||
Trading symbol isin.
|
||||
|
||||
Price : int
|
||||
Order price.
|
||||
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
Order instance if logged in, otherwise None.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> order = client.Buy_by_isin(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType = 'DAY',
|
||||
... ValidityDate = 0
|
||||
... )
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
)-> Order | None:
|
||||
|
||||
"""
|
||||
Create a sell order using symbol isin.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
symbolIsin : str
|
||||
Trading symbol isin.
|
||||
|
||||
Price : int
|
||||
Order price.
|
||||
|
||||
Volume : int
|
||||
Order volume.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Order | None
|
||||
Order instance if logged in, otherwise None.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> order = client.Sell_by_isin(
|
||||
... symbolName="اهرم",
|
||||
... Price=12000,
|
||||
... Volume=1000,
|
||||
... Order_ValidityType = 'DAY',
|
||||
... ValidityDate = 0
|
||||
... )
|
||||
>>> 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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,29 @@
|
||||
# ========================================|======================================== #
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from typing import (
|
||||
NewType,
|
||||
TypedDict,
|
||||
Literal,
|
||||
)
|
||||
|
||||
# ========================================|======================================== #
|
||||
# Class Definitions #
|
||||
# ========================================|======================================== #
|
||||
|
||||
HexUUID = NewType("HexUUID", str)
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
class OrderStatus(TypedDict):
|
||||
|
||||
order_uuid : HexUUID
|
||||
order_status : Literal['InQueue','Cancelled','Broken','Settled']
|
||||
Price : int
|
||||
Volume : int
|
||||
RemainedVolume : int
|
||||
ExecutedVolume : int
|
||||
OrderSide : Literal['Buy','Sell']
|
||||
ValidityType : Literal['DAY','GTC','GTD']
|
||||
ValidityDate : int
|
||||
Whitespace-only changes.
@@ -1 +1,376 @@
|
||||
HedgeTech
|
||||
# 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.
|
||||
|
||||
> **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 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 via PyPI:
|
||||
|
||||
``` bash
|
||||
pip install HedgeTech
|
||||
```
|
||||
|
||||
### Update
|
||||
|
||||
``` bash
|
||||
pip install --upgrade HedgeTech
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Package Structure
|
||||
|
||||
HedgeTech/
|
||||
├── Auth/
|
||||
├── DataEngine/
|
||||
├── EMSEngine/
|
||||
└── __init__.py
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Authentication
|
||||
|
||||
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="user@example.com",
|
||||
Password="password"
|
||||
)
|
||||
|
||||
print(auth_async_client.token)
|
||||
```
|
||||
|
||||
### Sync Authentication
|
||||
|
||||
``` python
|
||||
from HedgeTech.Auth import AuthSyncClient
|
||||
|
||||
auth_sync_client = AuthSyncClient.login(
|
||||
UserName_or_Email="user@example.com",
|
||||
Password="password"
|
||||
)
|
||||
|
||||
print(auth_sync_client.token)
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## DataEngine (Market Data)
|
||||
|
||||
The DataEngine module provides unified access to:
|
||||
|
||||
- Live market data
|
||||
- Historical OHLCV
|
||||
- Order books
|
||||
- Best limits
|
||||
- WebSocket streams
|
||||
|
||||
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"]
|
||||
)
|
||||
|
||||
print(data)
|
||||
|
||||
async for update in client.websocket_by_name(
|
||||
channels=["best-limit","order-book"],
|
||||
symbol_names=["فملی","اطلس"]
|
||||
):
|
||||
print(update["data"])
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### 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="مهرگان",
|
||||
start_timestamp=0,
|
||||
end_timestamp="1763411432",
|
||||
AdjustedPrice=True,
|
||||
Resolution="D"
|
||||
)
|
||||
|
||||
print(data)
|
||||
|
||||
for update in client.websocket_by_isin(
|
||||
channels=["best-limit","order-book"],
|
||||
symbol_isins=["IR1234567890"]
|
||||
):
|
||||
print(update["data"])
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## 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
|
||||
|
||||
Provides:
|
||||
|
||||
- AuthAsyncClient
|
||||
- AuthSyncClient
|
||||
- Token management
|
||||
- Session handling
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### HedgeTech.DataEngine
|
||||
|
||||
Provides:
|
||||
|
||||
- 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.
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Follow PEP8
|
||||
- Add tests
|
||||
- Update documentation
|
||||
- Submit Pull Requests
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## License
|
||||
|
||||
Licensed under Apache License 2.0.
|
||||
|
||||
See LICENSE file.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Support
|
||||
|
||||
GitHub Issues: https://gitea.hedgetech.ir/HedgeTech/HedgeTech/issues
|
||||
|
||||
Email: info@hedgetech.ir
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
© 2026 HedgeTech. All rights reserved.
|
||||
+34
-11
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "HedgeTech"
|
||||
version = "0.0.0"
|
||||
description = "Core SDK for integrating with HedgeTech trading and market data APIs"
|
||||
version = "0.3.1b2"
|
||||
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"
|
||||
license = { file = "LICENSE" }
|
||||
@@ -15,26 +15,49 @@ authors = [
|
||||
]
|
||||
|
||||
keywords = [
|
||||
"hedge", "finance", "trading", "oms", "api",
|
||||
"market-data", "execution", "orderbook",
|
||||
"algo-trading", "async", "sdk"
|
||||
"hedge", "finance", "financial-markets", "stocks", "equities",
|
||||
"trading", "algo-trading", "algorithmic-trading", "automated-trading",
|
||||
"oms", "order-management-system", "execution", "orderbook", "real-time",
|
||||
"high-frequency", "portfolio-management", "risk-management",
|
||||
"market-data", "exchange-api", "sdk", "python", "async", "websocket"
|
||||
]
|
||||
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
|
||||
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
"Development Status :: 3 - Alpha",
|
||||
|
||||
"Development Status :: 4 - Beta",
|
||||
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: Financial and Insurance Industry",
|
||||
"Topic :: Software Development :: Libraries"
|
||||
|
||||
"Topic :: Office/Business :: Financial",
|
||||
"Topic :: Scientific/Engineering :: Information Analysis",
|
||||
"Topic :: System :: Networking",
|
||||
"Topic :: Internet :: WWW/HTTP",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
|
||||
"Framework :: AsyncIO",
|
||||
"Typing :: Typed"
|
||||
]
|
||||
|
||||
dependencies = [
|
||||
"httpx[http2]==0.28.1",
|
||||
"httpx[http2]<=0.28.1",
|
||||
"brotli<=1.2.0",
|
||||
"zstd<=1.5.7.2",
|
||||
"PyJWT<=2.10.1",
|
||||
"websockets<=15.0.1",
|
||||
"pillow<=12.0.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/HedgeTech-ir/HedgeTech"
|
||||
Documentation = "https://github.com/HedgeTech-ir/HedgeTech/blob/main/README.md"
|
||||
Repository = "https://github.com/HedgeTech-ir/HedgeTech"
|
||||
Homepage = "https://hedgetech.ir/landing/"
|
||||
Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md"
|
||||
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
|
||||
Reference in new issue
Block a user