Compare commits
22
Commits
0.2.1b1
...
ecc1070f1c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecc1070f1c | ||
|
|
126eab66f7 | ||
|
|
8a5f3142ef | ||
|
|
9cfd36a891 | ||
|
|
034c9a50ea | ||
|
|
17bea4f2a3 | ||
|
|
747b257432 | ||
|
|
e6bd5852c2 | ||
|
|
88359c882f | ||
|
|
420ebda323 | ||
|
|
83314e0074 | ||
|
|
f6132f8044 | ||
|
|
2b4e532708 | ||
|
|
db1001111a | ||
|
|
f3a9dd214b | ||
|
|
07ca759248 | ||
|
|
c9799fbd7f | ||
|
|
22f8ea17d6 | ||
|
|
440c7947cc | ||
|
|
312f230b08 | ||
|
|
aa4d4bbabb | ||
|
|
569a36edaa |
No files matched your search
@@ -2,6 +2,7 @@
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from .__utils import RetriableAsyncClient
|
||||
from httpx import (
|
||||
AsyncClient ,
|
||||
Timeout ,
|
||||
@@ -126,18 +127,21 @@ class AuthAsyncClient:
|
||||
headers = {'origin' : 'https://core.hedgetech.ir'}
|
||||
headers.update(token)
|
||||
|
||||
httpx_Client = AsyncClient(
|
||||
httpx_Client = RetriableAsyncClient(
|
||||
client = AsyncClient(
|
||||
verify=True ,
|
||||
http1=False ,
|
||||
http2=True ,
|
||||
headers=headers,
|
||||
cookies=httpx_Client.cookies,
|
||||
timeout=Timeout(
|
||||
connect=.5,
|
||||
read=1,
|
||||
write=1,
|
||||
pool=.5,
|
||||
connect=.250,
|
||||
read=1.5,
|
||||
write=1.5,
|
||||
pool=.250,
|
||||
),
|
||||
),
|
||||
retries= 10
|
||||
)
|
||||
|
||||
return cls(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from .__utils import RetriableSyncClient
|
||||
from httpx import (
|
||||
Client ,
|
||||
Timeout ,
|
||||
@@ -129,23 +130,26 @@ class AuthSyncClient:
|
||||
headers = {'origin' : 'https://core.hedgetech.ir'}
|
||||
headers.update(token)
|
||||
|
||||
httpx_Client = Client(
|
||||
httpx_Client = RetriableSyncClient(
|
||||
client = Client(
|
||||
verify=True ,
|
||||
http1=False ,
|
||||
http2=True ,
|
||||
headers=headers,
|
||||
cookies=httpx_Client.cookies,
|
||||
timeout=Timeout(
|
||||
connect=.5,
|
||||
read=1,
|
||||
write=1,
|
||||
pool=.5,
|
||||
connect=.250,
|
||||
read=1.5,
|
||||
write=1.5,
|
||||
pool=.250,
|
||||
),
|
||||
),
|
||||
retries= 10
|
||||
)
|
||||
|
||||
return cls(
|
||||
httpx_Client = httpx_Client,
|
||||
token = login_res.json()
|
||||
token = token
|
||||
)
|
||||
|
||||
else :
|
||||
|
||||
@@ -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 *
|
||||
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,12 @@
|
||||
# Imports #
|
||||
# ========================================|======================================== #
|
||||
|
||||
from asyncio import Event
|
||||
from asyncio import (
|
||||
Event,
|
||||
wait_for,
|
||||
TimeoutError,
|
||||
sleep,
|
||||
)
|
||||
from websockets.asyncio.client import connect
|
||||
from json import loads
|
||||
from HedgeTech.Auth import AuthAsyncClient
|
||||
@@ -1461,7 +1466,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
... print(update["data"])
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
@@ -1476,9 +1481,13 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try:
|
||||
yield loads(await ws.recv())
|
||||
except :
|
||||
try : yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
|
||||
@@ -1566,7 +1575,7 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
... print(update["data"])
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
@@ -1581,8 +1590,12 @@ class DataEngine_TseIfb_AsyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try:
|
||||
yield loads(await ws.recv())
|
||||
except :
|
||||
try: yield loads(await wait_for(ws.recv(), timeout=2))
|
||||
|
||||
except TimeoutError:
|
||||
await sleep(0)
|
||||
continue
|
||||
|
||||
except Exception:
|
||||
await ws.close()
|
||||
break
|
||||
@@ -1425,7 +1425,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
... print(update) # This will not run; method is not implemented
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
@@ -1440,13 +1440,12 @@ class DataEngine_TseIfb_SyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try :
|
||||
yield loads(ws.recv())
|
||||
except :
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def websocket_by_isin(
|
||||
@@ -1520,7 +1519,7 @@ class DataEngine_TseIfb_SyncClient:
|
||||
... print(update) # This will not run; method is not implemented
|
||||
"""
|
||||
|
||||
if event is None :
|
||||
if not isinstance(event,Event):
|
||||
event = Event()
|
||||
event.set()
|
||||
|
||||
@@ -1535,8 +1534,8 @@ class DataEngine_TseIfb_SyncClient:
|
||||
|
||||
while event.is_set():
|
||||
|
||||
try :
|
||||
yield loads(ws.recv())
|
||||
except :
|
||||
try : yield loads(ws.recv(timeout=2))
|
||||
except TimeoutError : continue
|
||||
except Exception:
|
||||
ws.close()
|
||||
break
|
||||
@@ -9,6 +9,7 @@ from typing import (
|
||||
Dict,
|
||||
Optional,
|
||||
TypedDict,
|
||||
Literal,
|
||||
)
|
||||
|
||||
# ========================================|======================================== #
|
||||
@@ -37,7 +38,15 @@ class WebsocketBase_symbolIsin(TypedDict):
|
||||
>>> message["symbolIsin"]
|
||||
'IR0001234567'
|
||||
"""
|
||||
channel: str
|
||||
channel: Literal[
|
||||
"best-limit",
|
||||
"order-book",
|
||||
"ohlcv-last-1m",
|
||||
"aggregate",
|
||||
"institutional-vs-individual",
|
||||
"contract-info",
|
||||
"fund-info",
|
||||
]
|
||||
symbolIsin: str
|
||||
timestamp: str
|
||||
|
||||
@@ -64,7 +73,15 @@ class WebsocketBase_symbolName(TypedDict):
|
||||
>>> message["symbolName"]
|
||||
'ETF001'
|
||||
"""
|
||||
channel: str
|
||||
channel: Literal[
|
||||
"best-limit",
|
||||
"order-book",
|
||||
"ohlcv-last-1m",
|
||||
"aggregate",
|
||||
"institutional-vs-individual",
|
||||
"contract-info",
|
||||
"fund-info",
|
||||
]
|
||||
symbolName: str
|
||||
timestamp: str
|
||||
|
||||
@@ -734,7 +751,6 @@ class Instruments(TypedDict):
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
|
||||
class BestLimitItem(TypedDict):
|
||||
"""
|
||||
Represents the best limit order information at a given price level for a financial instrument.
|
||||
@@ -766,39 +782,6 @@ class BestLimitItem(TypedDict):
|
||||
sell_quantity: int
|
||||
sell_price: int
|
||||
|
||||
|
||||
class BestLimit(TypedDict):
|
||||
"""
|
||||
Represents the aggregated best limit orders for multiple instruments.
|
||||
|
||||
The structure is a nested dictionary where the first key is typically a symbol
|
||||
identifier (ISIN or symbolName) and the second key represents the order level or priority.
|
||||
|
||||
Attributes:
|
||||
items (Dict[str, Dict[str, BestLimitItem]]): Nested dictionary of BestLimitItem objects.
|
||||
- Outer key: Instrument identifier (e.g., ISIN or symbolName)
|
||||
- Inner key: Price level or order priority
|
||||
- Value: BestLimitItem for that level
|
||||
|
||||
Example:
|
||||
>>> best_limit: BestLimit = {
|
||||
... "ETF001": {
|
||||
... "1": {
|
||||
... "buy_order_count": 5,
|
||||
... "buy_quantity": 1000,
|
||||
... "buy_price": 12000,
|
||||
... "sell_order_count": 3,
|
||||
... "sell_quantity": 800,
|
||||
... "sell_price": 12100
|
||||
... }
|
||||
... }
|
||||
... }
|
||||
>>> best_limit["ETF001"]["1"]["sell_quantity"]
|
||||
800
|
||||
"""
|
||||
items: Dict[str, Dict[str, BestLimitItem]]
|
||||
|
||||
|
||||
class BestLimitResponse(TypedDict):
|
||||
"""
|
||||
Response structure for best limit orders from a REST API call.
|
||||
@@ -810,7 +793,18 @@ class BestLimitResponse(TypedDict):
|
||||
|
||||
Example:
|
||||
>>> response: BestLimitResponse = {
|
||||
... "Data": best_limit,
|
||||
... "Data": {
|
||||
... "ETF001": {
|
||||
... "1": {
|
||||
... "buy_order_count": 5,
|
||||
... "buy_quantity": 1000,
|
||||
... "buy_price": 12000,
|
||||
... "sell_order_count": 3,
|
||||
... "sell_quantity": 800,
|
||||
... "sell_price": 12100
|
||||
... },
|
||||
... },
|
||||
... },
|
||||
... "Status": {
|
||||
... "State": True,
|
||||
... "ServerTimeStamp": 1700350200.0,
|
||||
@@ -825,7 +819,13 @@ class BestLimitResponse(TypedDict):
|
||||
>>> response["Status"]["State"]
|
||||
True
|
||||
"""
|
||||
Data: BestLimit
|
||||
Data: Dict[
|
||||
str,
|
||||
Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem
|
||||
]
|
||||
]
|
||||
Status: Status
|
||||
|
||||
|
||||
@@ -867,7 +867,10 @@ class BestLimit_WS_symbolIsin(WebsocketBase_symbolIsin):
|
||||
>>> ws_data["data"]["1"]["sell_price"]
|
||||
12100
|
||||
"""
|
||||
data: Dict[str, BestLimitItem]
|
||||
data: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem,
|
||||
]
|
||||
|
||||
|
||||
class BestLimit_WS_symbolName(WebsocketBase_symbolName):
|
||||
@@ -908,7 +911,10 @@ class BestLimit_WS_symbolName(WebsocketBase_symbolName):
|
||||
>>> ws_data["data"]["2"]["buy_price"]
|
||||
11950
|
||||
"""
|
||||
data: Dict[str, BestLimitItem]
|
||||
data: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem,
|
||||
]
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@@ -1628,7 +1634,10 @@ class OverviewSecuritiesAndFunds(SecuritiesAndFunds):
|
||||
>>> overview["FundInfo"]["nav"]
|
||||
12500.0
|
||||
"""
|
||||
BestLimit: Dict[str, BestLimitItem]
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem,
|
||||
]
|
||||
Aggregate: Aggregate
|
||||
institutional_vs_individual: institutional_vs_individual
|
||||
FundInfo: FundInfo
|
||||
@@ -1649,7 +1658,10 @@ class OverviewTreasuryBonds(TreasuryBonds):
|
||||
FundInfo (FundInfo)
|
||||
ContractInfo (ContractInfo)
|
||||
"""
|
||||
BestLimit: Dict[str, BestLimitItem]
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem,
|
||||
]
|
||||
Aggregate: Aggregate
|
||||
institutional_vs_individual: institutional_vs_individual
|
||||
FundInfo: FundInfo
|
||||
@@ -1670,7 +1682,10 @@ class OverviewStockOptions(StockOptions):
|
||||
FundInfo (FundInfo)
|
||||
ContractInfo (ContractInfo)
|
||||
"""
|
||||
BestLimit: Dict[str, BestLimitItem]
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem,
|
||||
]
|
||||
Aggregate: Aggregate
|
||||
institutional_vs_individual: institutional_vs_individual
|
||||
FundInfo: FundInfo
|
||||
@@ -1691,7 +1706,10 @@ class OverviewStockFuturess(StockFutures):
|
||||
FundInfo (FundInfo)
|
||||
ContractInfo (ContractInfo)
|
||||
"""
|
||||
BestLimit: Dict[str, BestLimitItem]
|
||||
BestLimit: Dict[
|
||||
Literal['1','2','3','4','5','6',],
|
||||
BestLimitItem,
|
||||
]
|
||||
Aggregate: Aggregate
|
||||
institutional_vs_individual: institutional_vs_individual
|
||||
FundInfo: FundInfo
|
||||
@@ -1728,7 +1746,8 @@ class OverviewResponse:
|
||||
True
|
||||
"""
|
||||
Data : Dict[
|
||||
str,Optional[
|
||||
str,
|
||||
Optional[
|
||||
Union[
|
||||
OverviewSecuritiesAndFunds,
|
||||
OverviewTreasuryBonds,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from .__tse_ifb import (
|
||||
EmsEngine_TseIfb_SyncClient,
|
||||
EmsEngine_TseIfb_ASyncClient
|
||||
EmsEngine_TseIfb_AsyncClient
|
||||
)
|
||||
@@ -13,17 +13,31 @@ 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,
|
||||
*,
|
||||
order_uuid : HexUUID,
|
||||
SendOrder_RequestInfo : dict,
|
||||
AuthASyncClient : AuthAsyncClient,
|
||||
SymbolNameOrIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -32,13 +46,47 @@ class Order:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
SymbolNameOrIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
):
|
||||
|
||||
"""
|
||||
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.__order_uuid : HexUUID = order_uuid
|
||||
self.__SendOrder_RequestInfo = SendOrder_RequestInfo
|
||||
|
||||
self.ValidityType : str = Order_ValidityType
|
||||
self.ValidityDate : int = ValidityDate
|
||||
self.SymbolNameOrIsin : str = SymbolNameOrIsin
|
||||
@@ -46,12 +94,55 @@ class Order:
|
||||
self.Volume : int = Volume
|
||||
self.is_deleted : bool = False
|
||||
|
||||
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
|
||||
@@ -60,14 +151,44 @@ class Order:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> 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.__order_uuid,
|
||||
'order_uuid' : self.OrderId,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'Price' : Price,
|
||||
@@ -82,27 +203,64 @@ class Order:
|
||||
|
||||
Edit_response = Edit_response.json()
|
||||
|
||||
self.__order_uuid = Edit_response['Data']['order_uuid']
|
||||
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']
|
||||
|
||||
case 400:
|
||||
return None
|
||||
|
||||
raise ValueError(Edit_response.json()['detail']['Status']['Description']['en'])
|
||||
case _ : return None
|
||||
|
||||
case _ :
|
||||
else : return None
|
||||
|
||||
raise ValueError(Edit_response.text)
|
||||
except : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
@property
|
||||
async def Status(self)-> OrderStatus:
|
||||
|
||||
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.__order_uuid}
|
||||
params={'order_uuid' : self.OrderId}
|
||||
)
|
||||
|
||||
match status_respnse.status_code :
|
||||
@@ -111,23 +269,39 @@ class Order:
|
||||
|
||||
return status_respnse.json()['Data']
|
||||
|
||||
case 400:
|
||||
case _ : return None
|
||||
|
||||
raise ValueError(status_respnse.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(status_respnse.text)
|
||||
else : return None
|
||||
|
||||
except : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@property
|
||||
async def Delete(self)-> bool :
|
||||
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.__order_uuid}
|
||||
params={'order_uuid' : self.OrderId}
|
||||
)
|
||||
|
||||
|
||||
@@ -136,31 +310,71 @@ class Order:
|
||||
case 200:
|
||||
|
||||
self.is_deleted = True
|
||||
return None
|
||||
|
||||
case 400:
|
||||
case _ : return None
|
||||
|
||||
raise ValueError(Delete_respnse.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(Delete_respnse.text)
|
||||
else : return None
|
||||
|
||||
except : return None
|
||||
|
||||
# ================================================================================= #
|
||||
|
||||
class EmsEngine_TseIfb_ASyncClient:
|
||||
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 : str | None = None
|
||||
self.oms_session : HexUUID | None = None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@@ -170,9 +384,34 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
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 }
|
||||
@@ -187,11 +426,44 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
|
||||
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={
|
||||
@@ -227,6 +499,9 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
async def Buy_by_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -235,14 +510,55 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = await self.__AuthASyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/name',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -250,33 +566,10 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@@ -284,6 +577,9 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
async def Sell_by_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -292,14 +588,55 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = await self.__AuthASyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/name',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -307,38 +644,19 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def Buy_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -347,14 +665,55 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = await self.__AuthASyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/isin',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -362,39 +721,19 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
async def Sell_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -403,14 +742,55 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = await self.__AuthASyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/isin',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -418,32 +798,10 @@ class EmsEngine_TseIfb_ASyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthASyncClient=self.__AuthASyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@@ -20,11 +20,25 @@ from io import BytesIO
|
||||
|
||||
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,
|
||||
*,
|
||||
order_uuid : HexUUID,
|
||||
SendOrder_RequestInfo : dict,
|
||||
AuthSyncClient : AuthSyncClient,
|
||||
SymbolNameOrIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
ValidityDate : int = 0,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -32,14 +46,46 @@ class Order:
|
||||
'FAK', # Fill And Kill
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
SymbolNameOrIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
):
|
||||
|
||||
"""
|
||||
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.__order_uuid : HexUUID = order_uuid
|
||||
self.__SendOrder_RequestInfo = SendOrder_RequestInfo
|
||||
|
||||
self.ValidityType : str = Order_ValidityType
|
||||
self.ValidityDate : int = ValidityDate
|
||||
self.SymbolNameOrIsin : str = SymbolNameOrIsin
|
||||
@@ -47,12 +93,61 @@ class Order:
|
||||
self.Volume : int = Volume
|
||||
self.is_deleted : bool = False
|
||||
|
||||
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
|
||||
@@ -61,14 +156,51 @@ class Order:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> 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.__order_uuid,
|
||||
'order_uuid' : self.OrderId,
|
||||
'Order_ValidityType' : Order_ValidityType,
|
||||
'ValidityDate' : ValidityDate,
|
||||
'Price' : Price,
|
||||
@@ -83,29 +215,116 @@ class Order:
|
||||
|
||||
Edit_response = Edit_response.json()
|
||||
|
||||
self.__order_uuid = Edit_response['Data']['order_uuid']
|
||||
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']
|
||||
|
||||
case 400:
|
||||
return None
|
||||
|
||||
raise ValueError(Edit_response.json()['detail']['Status']['Description']['en'])
|
||||
case _ : return None
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(Edit_response.text)
|
||||
else : return None
|
||||
|
||||
except : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@property
|
||||
def Status(self)-> OrderStatus:
|
||||
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.__order_uuid}
|
||||
params={'order_uuid' : self.OrderId}
|
||||
)
|
||||
|
||||
match status_respnse.status_code :
|
||||
@@ -114,22 +333,43 @@ class Order:
|
||||
|
||||
return status_respnse.json()['Data']
|
||||
|
||||
case 400:
|
||||
case _ : return None
|
||||
|
||||
raise ValueError(status_respnse.json()['detail']['Status']['Description']['en'])
|
||||
else : return None
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(status_respnse.text)
|
||||
except : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@property
|
||||
def Delete(self)-> bool :
|
||||
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.__order_uuid}
|
||||
params={'order_uuid' : self.OrderId}
|
||||
)
|
||||
|
||||
|
||||
@@ -138,20 +378,25 @@ class Order:
|
||||
case 200:
|
||||
|
||||
self.is_deleted = True
|
||||
return None
|
||||
|
||||
case 400:
|
||||
case _ : return None
|
||||
|
||||
raise ValueError(Delete_respnse.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(Delete_respnse.text)
|
||||
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,
|
||||
@@ -172,9 +417,34 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
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 }
|
||||
@@ -188,10 +458,42 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
|
||||
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',
|
||||
@@ -230,6 +532,9 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
def Buy_by_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -238,14 +543,51 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = self.__AuthSyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/name',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -253,32 +595,10 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
else : return None
|
||||
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
@@ -287,6 +607,9 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
def Sell_by_Name(
|
||||
self,
|
||||
*,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -295,14 +618,51 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolName : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = self.__AuthSyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/name',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -310,38 +670,19 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolName,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def Buy_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -350,14 +691,51 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = self.__AuthSyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/buy/isin',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -365,39 +743,19 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
def Sell_by_isin(
|
||||
self,
|
||||
*,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
Order_ValidityType : Literal[
|
||||
'DAY',
|
||||
'GTC', # Good Till Cancelled
|
||||
@@ -406,14 +764,51 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'FOK', # Fill Or Kill
|
||||
] = 'DAY',
|
||||
ValidityDate : int = 0,
|
||||
symbolIsin : str,
|
||||
Price : int,
|
||||
Volume :int,
|
||||
)-> Order:
|
||||
)-> Order | None:
|
||||
|
||||
order_response = self.__AuthSyncClient.httpx_Client.post(
|
||||
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/new/sell/isin',
|
||||
data={
|
||||
"""
|
||||
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,
|
||||
@@ -421,32 +816,10 @@ class EmsEngine_TseIfb_SyncClient:
|
||||
'Price' : Price,
|
||||
'Volume' : Volume
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
match order_response.status_code:
|
||||
|
||||
|
||||
case 200:
|
||||
|
||||
order_response = order_response.json()
|
||||
|
||||
return Order(
|
||||
order_uuid=order_response['Data']['order_uuid'],
|
||||
AuthSyncClient=self.__AuthSyncClient,
|
||||
Order_ValidityType=Order_ValidityType,
|
||||
ValidityDate=ValidityDate,
|
||||
SymbolNameOrIsin = symbolIsin,
|
||||
Price=Price,
|
||||
Volume=Volume
|
||||
)
|
||||
|
||||
case 400:
|
||||
|
||||
raise ValueError(order_response.json()['detail']['Status']['Description']['en'])
|
||||
|
||||
case _ :
|
||||
|
||||
raise ValueError(order_response.text)
|
||||
else : return None
|
||||
|
||||
# +--------------------------------------------------------------------------------------+ #
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
from .__SyncClient import EmsEngine_TseIfb_SyncClient
|
||||
from .__AsyncClient import EmsEngine_TseIfb_ASyncClient
|
||||
from .__AsyncClient import EmsEngine_TseIfb_AsyncClient
|
||||
@@ -1,149 +1,376 @@
|
||||
# HedgeTech Python SDK
|
||||
|
||||
HedgeTech Python SDK is a professional, lightweight, and modular Python package designed to provide seamless access to HedgeTech services. The SDK is crafted for developers, data analysts, and algorithmic traders who want to interact with the Tehran Stock Exchange (TSE & IFB) using a clean, reliable, and easy-to-use API. It supports both synchronous and asynchronous workflows, offering maximum flexibility and performance for different application scenarios.
|
||||
HedgeTech Python SDK is a professional, lightweight, and modular Python
|
||||
package designed to provide seamless access to HedgeTech services. The
|
||||
SDK is crafted for developers, data analysts, and algorithmic traders
|
||||
who want to interact with the Tehran Stock Exchange (TSE & IFB) using a
|
||||
clean, reliable, and easy-to-use API.
|
||||
|
||||
> **Note:** This SDK requires Python >= 3.10 and is currently in Beta. Some APIs may change in future releases, but it is stable enough for daily use.
|
||||
It supports both synchronous and asynchronous workflows, offering
|
||||
maximum flexibility and performance for different application scenarios.
|
||||
|
||||
> **Note:** This SDK requires Python >= 3.10 and is production-ready.
|
||||
> Development Status: **5 - Production/Stable**.
|
||||
> The public APIs are stable and safe for long-term use.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Features
|
||||
|
||||
* Secure authentication with both async and sync clients.
|
||||
* Real-time and historical market data retrieval from TSE & IFB.
|
||||
* Modular and maintainable architecture, designed to support multiple engines (DataEngine engines, WebSocket clients, etc.).
|
||||
* Structured request and response types for robust data handling.
|
||||
* Fully asynchronous support for high-performance applications.
|
||||
* Easy to integrate into trading bots, analytics pipelines, dashboards, or WebSocket feeds.
|
||||
- Secure authentication with async and sync clients.
|
||||
- Real-time and historical market data from TSE & IFB.
|
||||
- Full EMS Engine order lifecycle management.
|
||||
- Modular architecture (Auth, DataEngine, EMSEngine).
|
||||
- Structured request/response types.
|
||||
- High-performance asyncio support.
|
||||
- Easy integration with trading bots and dashboards.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Installation
|
||||
|
||||
Install HedgeTech SDK via PyPI:
|
||||
Install via PyPI:
|
||||
|
||||
```
|
||||
pip install HedgeTech
|
||||
``` bash
|
||||
pip install git+https://gitea.hedgetech.ir/HedgeTech/HedgeTech
|
||||
```
|
||||
|
||||
### Updating the Package
|
||||
### Update
|
||||
|
||||
To update HedgeTech SDK to the latest version in your environment, use:
|
||||
|
||||
```
|
||||
pip install --upgrade HedgeTech
|
||||
``` bash
|
||||
pip install --upgrade --force-reinstall git+https://gitea.hedgetech.ir/HedgeTech/HedgeTech
|
||||
```
|
||||
|
||||
## Usage
|
||||
------------------------------------------------------------------------
|
||||
|
||||
The SDK exposes all major clients through the top-level modules, so you generally do **not** need to import internal implementation files directly.
|
||||
## Package Structure
|
||||
|
||||
### Authentication
|
||||
HedgeTech/
|
||||
├── Auth/
|
||||
├── DataEngine/
|
||||
├── EMSEngine/
|
||||
└── __init__.py
|
||||
|
||||
> **Note:** Make sure to use the matching async or sync Auth client depending on your workflow.
|
||||
------------------------------------------------------------------------
|
||||
|
||||
#### Async Authentication
|
||||
## Authentication
|
||||
|
||||
```python
|
||||
All services require authentication.
|
||||
|
||||
> Use matching Sync/Async clients.
|
||||
|
||||
### Async Authentication
|
||||
|
||||
``` python
|
||||
from HedgeTech.Auth import AuthAsyncClient
|
||||
|
||||
auth_async_client = await AuthAsyncClient.login(
|
||||
UserName_or_Email='<YOUR UserName_or_Email>',
|
||||
Password='<YOUR Password>'
|
||||
UserName_or_Email="user@example.com",
|
||||
Password="password"
|
||||
)
|
||||
|
||||
print(auth_async_client.token)
|
||||
```
|
||||
|
||||
#### Sync Authentication
|
||||
### Sync Authentication
|
||||
|
||||
```python
|
||||
``` python
|
||||
from HedgeTech.Auth import AuthSyncClient
|
||||
|
||||
auth_sync_client = AuthSyncClient.login(
|
||||
UserName_or_Email='<YOUR UserName_or_Email>',
|
||||
Password='<YOUR Password>'
|
||||
UserName_or_Email="user@example.com",
|
||||
Password="password"
|
||||
)
|
||||
|
||||
print(auth_sync_client.token)
|
||||
```
|
||||
|
||||
### DataEngine / TSE IFB
|
||||
------------------------------------------------------------------------
|
||||
|
||||
The DataEngine is designed to support multiple engines in a modular way. Each engine provides its own async and sync clients, structured request and response types, and can be integrated with other engines such as WebSocket clients.
|
||||
## DataEngine (Market Data)
|
||||
|
||||
> **Important Note on Sync vs Async:** All clients have the **same method names and behavior** in both Sync and Async versions. The only difference is how they execute: Sync runs in a blocking manner, while Async requires `await` and an event loop. This design allows you to switch between Sync and Async without changing the logic or input/output of your code.
|
||||
The DataEngine module provides unified access to:
|
||||
|
||||
#### Async Data Client
|
||||
- Live market data
|
||||
- Historical OHLCV
|
||||
- Order books
|
||||
- Best limits
|
||||
- WebSocket streams
|
||||
|
||||
```python
|
||||
All engines follow identical Sync/Async APIs.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### Async Data Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.DataEngine import DataEngine_TseIfb_AsyncClient
|
||||
|
||||
client = DataEngine_TseIfb_AsyncClient(auth_async_client)
|
||||
|
||||
data = await client.live_best_limit_by_isin(
|
||||
symbol_isins=['IRT1AHRM0001','IRO1IKCO0001']
|
||||
symbol_isins=["IRT1AHRM0001","IRO1IKCO0001"]
|
||||
)
|
||||
|
||||
print(data)
|
||||
|
||||
# websocket Example
|
||||
|
||||
async for update in client.websocket_by_name(
|
||||
channels=["best-limit", "order-book"],
|
||||
channels=["best-limit","order-book"],
|
||||
symbol_names=["فملی","اطلس"]
|
||||
):
|
||||
|
||||
print(update["data"])
|
||||
```
|
||||
|
||||
#### Sync Data Client
|
||||
------------------------------------------------------------------------
|
||||
|
||||
```python
|
||||
### Sync Data Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.DataEngine import DataEngine_TseIfb_SyncClient
|
||||
|
||||
client = DataEngine_TseIfb_SyncClient(auth_sync_client)
|
||||
|
||||
data = client.historical_ohlcv_by_name(
|
||||
symbolName='مهرگان',
|
||||
symbolName="مهرگان",
|
||||
start_timestamp=0,
|
||||
end_timestamp='1763411432',
|
||||
end_timestamp="1763411432",
|
||||
AdjustedPrice=True,
|
||||
Resolution='D'
|
||||
Resolution="D"
|
||||
)
|
||||
|
||||
print(data)
|
||||
|
||||
# websocket Example
|
||||
|
||||
for update in client.websocket_by_isin(
|
||||
channels=["best-limit", "order-book"],
|
||||
channels=["best-limit","order-book"],
|
||||
symbol_isins=["IR1234567890"]
|
||||
):
|
||||
|
||||
print(update["data"])
|
||||
```
|
||||
|
||||
## Important Notes for Users
|
||||
------------------------------------------------------------------------
|
||||
|
||||
* This SDK requires Python >=3.10.
|
||||
* The SDK is currently in **Beta** — APIs may change in future releases, but it is usable for most workflows.
|
||||
* Always install dependencies with the specified versions to avoid compatibility issues.
|
||||
* Async clients require an asyncio event loop.
|
||||
* All main clients are exposed through top-level modules; you do not need to access internal files.
|
||||
* Keywords and classifiers are chosen to make the SDK easy to find for developers working in finance, trading, and data analysis.
|
||||
## EMSEngine (Order Management)
|
||||
|
||||
The EMSEngine module handles complete order management.
|
||||
|
||||
Supported markets: - TSE - IFB
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### EMSEngine Features
|
||||
|
||||
- Buy/Sell by Name or ISIN
|
||||
- Edit Orders
|
||||
- Cancel/Delete Orders
|
||||
- Real-time Status
|
||||
- Async/Sync Compatibility
|
||||
- Order Object Lifecycle
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Order Lifecycle
|
||||
|
||||
1. Create Order
|
||||
2. Send
|
||||
3. Monitor Status
|
||||
4. Edit (Optional)
|
||||
5. Settle or Delete
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Async Trading Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.EMSEngine import EmsEngine_TseIfb_AsyncClient
|
||||
|
||||
ems = EmsEngine_TseIfb_AsyncClient(auth_async_client)
|
||||
|
||||
captcha = await ems.Get_Captcha("Omex | Parsian")
|
||||
captcha.show()
|
||||
|
||||
await ems.oms_login(
|
||||
username="user",
|
||||
password="pass",
|
||||
captcha_value="1234"
|
||||
)
|
||||
|
||||
order = await ems.Buy_by_Name(
|
||||
symbolName="اطلس",
|
||||
Price=100000,
|
||||
Volume=10
|
||||
)
|
||||
|
||||
await order.send()
|
||||
|
||||
status = await order.Status()
|
||||
print(status)
|
||||
|
||||
await order.Edit(Price=105000, Volume=12)
|
||||
|
||||
await order.Delete()
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Sync Trading Example
|
||||
|
||||
``` python
|
||||
from HedgeTech.EMSEngine import EmsEngine_TseIfb_SyncClient
|
||||
|
||||
ems = EmsEngine_TseIfb_SyncClient(auth_sync_client)
|
||||
|
||||
captcha = ems.Get_Captcha("Omex | Parsian")
|
||||
captcha.show()
|
||||
|
||||
ems.oms_login(
|
||||
username="user",
|
||||
password="pass",
|
||||
captcha_value="1234"
|
||||
)
|
||||
|
||||
order = ems.Sell_by_Name(
|
||||
symbolName="فملی",
|
||||
Price=50000,
|
||||
Volume=5
|
||||
)
|
||||
|
||||
order.send()
|
||||
|
||||
status = order.Status()
|
||||
print(status)
|
||||
|
||||
order.Edit(Price=52000, Volume=6)
|
||||
|
||||
order.Delete()
|
||||
```
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Unified API Design
|
||||
|
||||
All Sync and Async clients share:
|
||||
|
||||
- Same method names
|
||||
- Same parameters
|
||||
- Same return types
|
||||
|
||||
Only execution model differs.
|
||||
|
||||
This enables seamless switching between modes.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Invalid credentials raise ValueError
|
||||
- Network errors should be handled by user
|
||||
- Failed requests may return None
|
||||
|
||||
Recommended: wrap calls in try/except.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Performance
|
||||
|
||||
- Non-blocking Async I/O
|
||||
- Connection pooling
|
||||
- Optimized request batching
|
||||
- Suitable for HFT and Algo Trading
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Security
|
||||
|
||||
- JWT Authentication
|
||||
- Encrypted Transport (HTTPS)
|
||||
- No password storage
|
||||
- Session isolation
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Refresh tokens regularly
|
||||
- Monitor order status
|
||||
- Avoid duplicate send()
|
||||
- Validate inputs
|
||||
- Log critical operations
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Modules Overview
|
||||
|
||||
### HedgeTech.Auth
|
||||
|
||||
Handles authentication for all HedgeTech clients. The async (`AuthAsyncClient`) and sync (`AuthSyncClient`) clients are exposed through the top-level Auth module.
|
||||
Provides:
|
||||
|
||||
- AuthAsyncClient
|
||||
- AuthSyncClient
|
||||
- Token management
|
||||
- Session handling
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### HedgeTech.DataEngine
|
||||
|
||||
Handles interactions with the Tehran Stock Exchange IFB and other engines. Provides:
|
||||
Provides:
|
||||
|
||||
* Async and sync clients for fetching market data.
|
||||
* Structured request and response types for predictable and robust data handling.
|
||||
* Modular design that allows integration of additional engines, such as WebSocket clients or future data engines, without modifying the main interface.
|
||||
- Market data APIs
|
||||
- Historical data
|
||||
- WebSocket feeds
|
||||
- Modular engine design
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
### HedgeTech.EMSEngine
|
||||
|
||||
Provides:
|
||||
|
||||
- EmsEngine_TseIfb_AsyncClient
|
||||
- EmsEngine_TseIfb_SyncClient
|
||||
- Order class
|
||||
- Lifecycle management
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Roadmap
|
||||
|
||||
- Auto session refresh
|
||||
- Smart retry system
|
||||
- Risk control module
|
||||
- Order batching
|
||||
- Metrics & Monitoring
|
||||
- Strategy framework
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome contributions from the community! Please follow standard Python coding conventions, write clear documentation for any new features, and submit pull requests for improvements or bug fixes.
|
||||
We welcome contributions.
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Follow PEP8
|
||||
- Add tests
|
||||
- Update documentation
|
||||
- Submit Pull Requests
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the **Apache License 2.0**. See the LICENSE file for full details.
|
||||
Licensed under Apache License 2.0.
|
||||
|
||||
See LICENSE file.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
## Support
|
||||
|
||||
For questions or issues, please open a GitHub issue or contact the HedgeTech team directly. We aim to provide timely support and guidance for all developers using the SDK.
|
||||
GitHub Issues: https://gitea.hedgetech.ir/HedgeTech/HedgeTech/issues
|
||||
|
||||
Email: info@hedgetech.ir
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
© 2026 HedgeTech. All rights reserved.
|
||||
+4
-4
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "HedgeTech"
|
||||
version = "0.2.0b1"
|
||||
version = "0.2.5"
|
||||
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"
|
||||
@@ -33,7 +33,7 @@ classifiers = [
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
|
||||
"Development Status :: 4 - Beta",
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: Financial and Insurance Industry",
|
||||
@@ -59,5 +59,5 @@ dependencies = [
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://hedgetech.ir/landing/"
|
||||
Documentation = "https://github.com/HedgeTech-ir/HedgeTech/blob/main/README.md"
|
||||
Repository = "https://github.com/HedgeTech-ir/HedgeTech"
|
||||
Documentation = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md"
|
||||
Repository = "https://gitea.hedgetech.ir/HedgeTech/HedgeTech"
|
||||
Reference in new issue
Block a user