Compare commits

..
17 Commits
12 changed files with 1897 additions and 243 deletions

No files matched your search

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,
+107 -57
View File
@@ -118,20 +118,24 @@ class Order:
'953097ac6ced45ca8ef205b76ca6faf2'
"""
if self.OrderId is None :
try :
SendOrder_Response = await self.__AuthASyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
if self.OrderId is None :
match SendOrder_Response.status_code :
SendOrder_Response = await self.__AuthASyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
case 200 :
match SendOrder_Response.status_code :
self.OrderId = SendOrder_Response.json()['Data']['order_uuid']
return None
case 200 :
case _ : return None
self.OrderId = SendOrder_Response.json()['Data']['order_uuid']
return None
else : return None
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
async def Edit(
@@ -169,40 +173,49 @@ class Order:
Example
-------
>>> await order.Edit(Price=105, Volume=15)
>>> await order.Edit(
Price = 105,
Volume = 15,
Order_ValidityType = 'GTD',
ValidityDate = 20271206
)
"""
if self.OrderId is not None:
try :
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
}
)
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:
match Edit_response.status_code:
case 200:
case 200:
Edit_response = Edit_response.json()
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.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']
return None
return None
case _ : return None
case _ : return None
else : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
@@ -241,23 +254,26 @@ class Order:
'ValidityDate': 0
}
"""
try :
if self.OrderId is not None:
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}
)
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 :
match status_respnse.status_code :
case 200:
case 200:
return status_respnse.json()['Data']
return status_respnse.json()['Data']
case _ : return None
case _ : return None
else : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
@@ -279,24 +295,28 @@ class Order:
True
"""
if self.OrderId is not None:
try :
Delete_respnse = await self.__AuthASyncClient.httpx_Client.delete(
url= 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/delete',
params={'order_uuid' : self.OrderId}
)
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 :
match Delete_respnse.status_code :
case 200:
case 200:
self.is_deleted = True
return None
self.is_deleted = True
return None
case _ : return None
case _ : return None
else : return None
else : return None
except : return None
# ================================================================================= #
@@ -364,6 +384,7 @@ class EmsEngine_TseIfb_AsyncClient:
OMS : Literal[
'Omex | Parsian',
'Sahra | Karamad',
'Sahra | NIBB',
]
)-> ImageFile:
@@ -405,6 +426,7 @@ class EmsEngine_TseIfb_AsyncClient:
async def oms_login(
self,
*,
username: str,
password: str,
captcha_value: str,
@@ -433,7 +455,11 @@ class EmsEngine_TseIfb_AsyncClient:
Example
-------
>>> await client.oms_login("user123", "pass123", "abcd")
>>> await client.oms_login(
username = "user123",
password = "pass123",
captcha_value = "abcd"
)
>>> print(client.oms_session)
'session_token_here'
"""
@@ -509,7 +535,13 @@ class EmsEngine_TseIfb_AsyncClient:
Example
-------
>>> order = await client.Buy_by_Name(symbolName="اطلس", Price=100000, Volume=10)
>>> order = await client.Buy_by_Name(
symbolName="اطلس",
Price=100000,
Volume=10,
Order_ValidityType = 'DAY',
ValidityDate = 0
)
>>> await order.send()
"""
@@ -581,7 +613,13 @@ class EmsEngine_TseIfb_AsyncClient:
Example
-------
>>> order = await client.Sell_by_Name(symbolName="اطلس", Price=100000, Volume=10)
>>> order = await client.Sell_by_Name(
symbolName="اطلس",
Price=100000,
Volume=10,
Order_ValidityType = 'DAY',
ValidityDate = 0
)
>>> await order.send()
"""
@@ -652,7 +690,13 @@ class EmsEngine_TseIfb_AsyncClient:
Example
-------
>>> order = await client.Buy_by_isin(symbolIsin="اطلس", Price=100000, Volume=10)
>>> order = await client.Buy_by_isin(
symbolName="اطلس",
Price=100000,
Volume=10,
Order_ValidityType = 'DAY',
ValidityDate = 0
)
>>> await order.send()
"""
@@ -723,7 +767,13 @@ class EmsEngine_TseIfb_AsyncClient:
Example
-------
>>> order = await client.Sell_by_isin(symbolIsin="اطلس", Price=100000, Volume=10)
>>> order = await client.Sell_by_isin(
symbolName="اطلس",
Price=100000,
Volume=10,
Order_ValidityType = 'DAY',
ValidityDate = 0
)
>>> await order.send()
"""
+92 -57
View File
@@ -122,20 +122,24 @@ class Order:
'0xA23F...'
"""
if self.OrderId is None :
try :
SendOrder_Response = self.__AuthSyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
if self.OrderId is None :
match SendOrder_Response.status_code :
SendOrder_Response = self.__AuthSyncClient.httpx_Client.post(**self.__SendOrder_RequestInfo)
case 200 :
match SendOrder_Response.status_code :
self.OrderId = SendOrder_Response.json()['Data']['order_uuid']
return None
case 200 :
case _ : return None
self.OrderId = SendOrder_Response.json()['Data']['order_uuid']
return None
else : return None
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
@@ -181,40 +185,49 @@ class Order:
Examples
--------
>>> order.Edit(Price=12500, Volume=800)
>>> order.Edit(
Price = 105,
Volume = 15,
Order_ValidityType = 'GTD',
ValidityDate = 20271206
)
"""
if self.OrderId is not None:
try :
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
}
)
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:
match Edit_response.status_code:
case 200:
case 200:
Edit_response = Edit_response.json()
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.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']
return None
return None
case _ : return None
case _ : return None
else : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
@@ -305,22 +318,26 @@ class Order:
}
"""
if self.OrderId is not None:
try :
status_respnse = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/status',
params={'order_uuid' : self.OrderId}
)
if self.OrderId is not None:
match status_respnse.status_code :
status_respnse = self.__AuthSyncClient.httpx_Client.get(
url='https://core.hedgetech.ir/ems-engine/tse-ifb/order/status',
params={'order_uuid' : self.OrderId}
)
case 200:
match status_respnse.status_code :
return status_respnse.json()['Data']
case 200:
case _ : return None
return status_respnse.json()['Data']
else : return None
case _ : return None
else : return None
except : return None
# +--------------------------------------------------------------------------------------+ #
@@ -346,24 +363,28 @@ class Order:
True
"""
if self.OrderId is not None:
try :
Delete_respnse = self.__AuthSyncClient.httpx_Client.delete(
url= 'https://core.hedgetech.ir/ems-engine/tse-ifb/order/delete',
params={'order_uuid' : self.OrderId}
)
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 :
match Delete_respnse.status_code :
case 200:
case 200:
self.is_deleted = True
return None
self.is_deleted = True
return None
case _ : return None
case _ : return None
else : return None
else : return None
except : return None
# ================================================================================= #
@@ -396,6 +417,7 @@ class EmsEngine_TseIfb_SyncClient:
OMS : Literal[
'Omex | Parsian',
'Sahra | Karamad',
'Sahra | NIBB',
]
)-> ImageFile:
@@ -436,6 +458,7 @@ class EmsEngine_TseIfb_SyncClient:
def oms_login(
self,
*,
username: str,
password: str,
captcha_value: str,
@@ -465,7 +488,11 @@ class EmsEngine_TseIfb_SyncClient:
Examples
--------
>>> client.oms_login("user1", "pass123", "A7B9")
>>> client.oms_login(
username = "user123",
password = "pass123",
captcha_value = "abcd"
)
"""
response = self.__AuthSyncClient.httpx_Client.post(
@@ -542,7 +569,9 @@ class EmsEngine_TseIfb_SyncClient:
>>> order = client.Buy_by_Name(
... symbolName="اهرم",
... Price=12000,
... Volume=1000
... Volume=1000,
... Order_ValidityType = 'DAY',
... ValidityDate = 0
... )
>>> order.send()
"""
@@ -615,7 +644,9 @@ class EmsEngine_TseIfb_SyncClient:
>>> order = client.Sell_by_Name(
... symbolName="اهرم",
... Price=12000,
... Volume=1000
... Volume=1000,
... Order_ValidityType = 'DAY',
... ValidityDate = 0
... )
>>> order.send()
"""
@@ -686,7 +717,9 @@ class EmsEngine_TseIfb_SyncClient:
>>> order = client.Buy_by_isin(
... symbolName="اهرم",
... Price=12000,
... Volume=1000
... Volume=1000,
... Order_ValidityType = 'DAY',
... ValidityDate = 0
... )
>>> order.send()
"""
@@ -757,7 +790,9 @@ class EmsEngine_TseIfb_SyncClient:
>>> order = client.Sell_by_isin(
... symbolName="اهرم",
... Price=12000,
... Volume=1000
... Volume=1000,
... Order_ValidityType = 'DAY',
... ValidityDate = 0
... )
>>> order.send()
"""
+289 -62
View File
@@ -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
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "HedgeTech"
version = "0.2.2b0"
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"