HedgeTech Python SDK
Market data, live streaming and order execution for the Iranian capital & commodity markets — one SDK for core.hedgetech.ir.
Overview · Installation · Quick Start · Data Engine · EMS · Algo-Trading Tutorial · Support
Table of Contents
- Overview
- Architecture & Package Map
- Installation
- Quick Start
- Authentication (
Auth) - Data Engine — IME (Iran Mercantile Exchange)
- Data Engine — TSE-IFB (Tehran Stock Exchange & Iran Fara Bourse)
- Live Streaming with WebSockets
- EMS Engine — Order Execution
- Algorithmic Trading Tutorial
- Data Conventions
- Error Handling & Reliability
- API Reference (Cheat-Sheet)
- Support & Contact
- Disclaimer
1. Overview
The HedgeTech SDK is the official Python client for the HedgeTech Core platform (core.hedgetech.ir). It gives algorithmic-trading developers a single, typed, consistent interface to:
| Capability | What you get |
|---|---|
| Authentication | JWT login, authenticated HTTP/2 client with automatic retries |
| Data Engine (IME) | Static metadata, live snapshots and live WebSocket streams for IME futures, options and deposit certificates |
| Data Engine (TSE-IFB) | Static metadata, live snapshots, order book, OHLCV (live & historical), corporate actions and WebSocket streams for stocks, funds, treasury bonds, stock options and stock futures |
| EMS Engine | Broker (OMS) login with CAPTCHA, then send / edit / query / cancel orders on IME and TSE-IFB |
Highlights
- Async and sync twins. Every client exists as an
…AsyncClient(built onasyncio) and a…SyncClient(blocking). Endpoints, arguments and return types are identical — only the calling style differs. - Fully typed responses. All responses are
TypedDicts, so your IDE auto-completes every field. - By name or by ID. Nearly every endpoint has a
*_by_namevariant and a*_by_id(IME) /*_by_isin(TSE-IFB) variant. - Streaming built in. WebSocket methods are plain generators (
async for/for) with a built-in stop switch. - Production-minded HTTP stack. HTTP/2, strict TLS verification, short timeouts and up to 10 automatic retries.
Who is this for? Quant developers, trading-bot authors and fintech teams who need low-friction access to Iranian market data and order routing from Python.
2. Architecture & Package Map
flowchart LR
A[Your strategy] --> B[AuthAsyncClient / AuthSyncClient]
B -->|JWT + HTTP/2 client| C[Data Engine IME]
B --> D[Data Engine TSE-IFB]
B --> E[EMS Engine IME]
B --> F[EMS Engine TSE-IFB]
C & D & E & F --> G[(core.hedgetech.ir)]
Everything starts with an authenticated Auth client. You create it once and hand it to every other client; they reuse its HTTP session and token.
| Client class | Async | Sync | Purpose |
|---|---|---|---|
AuthAsyncClient / AuthSyncClient |
✅ | ✅ | Login, token, authenticated HTTP client |
DataEngine_Ime_AsyncClient / …_SyncClient |
✅ | ✅ | IME market data (REST + WebSocket) |
DataEngine_TseIfb_AsyncClient / …_SyncClient |
✅ | ✅ | TSE-IFB market data (REST + WebSocket) |
EmsEngine_Ime_AsyncClient / …_SyncClient |
✅ | ✅ | IME order execution |
EmsEngine_TseIfb_AsyncClient / …_SyncClient |
✅ | ✅ | TSE-IFB order execution |
Order |
✅ | ✅ | A single order: send, Edit, Status, Delete |
Which flavour should I use?
- Use the Async clients for bots that watch many instruments, stream data and place orders concurrently (recommended for trading systems).
- Use the Sync clients for scripts, notebooks, research and simple cron-style jobs.
3. Installation
Requirements
- Python 3.10 or newer (the SDK uses
matchstatements andX | Ytype unions) - Network access to
core.hedgetech.ir(HTTPS and WSS) - A HedgeTech account (see Support & Contact)
Install
pip install hedgetech
The SDK depends on httpx (with HTTP/2 support), websockets, PyJWT and Pillow. They are installed automatically; to install them by hand:
pip install "httpx[http2]" websockets PyJWT Pillow
Imports used throughout this guide
from HedgeTech.Auth import AuthAsyncClient, AuthSyncClient
from HedgeTech.Data.IME import DataEngine_Ime_AsyncClient, DataEngine_Ime_SyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient, DataEngine_TseIfb_SyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_AsyncClient, EmsEngine_Ime_SyncClient
from HedgeTech.EMS.TseIfb import EmsEngine_TseIfb_AsyncClient, EmsEngine_TseIfb_SyncClient
4. Quick Start
Async
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient
async def main():
# 1) Log in once.
auth = await AuthAsyncClient.login(
UserName_or_Email="user@example.com",
Password="secure_password",
)
# 2) Create the data client.
data = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)
# 3) Ask for the best bid/ask of a symbol.
response = await data.live_best_limit_by_name(["فملی"])
level_1 = response["Data"]["فملی"]["1"]
print("bid:", level_1["buy_price"], "ask:", level_1["sell_price"])
asyncio.run(main())
Sync
from HedgeTech.Auth import AuthSyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_SyncClient
auth = AuthSyncClient.login(
UserName_or_Email="user@example.com",
Password="secure_password",
)
data = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth)
response = data.live_best_limit_by_name(["فملی"])
level_1 = response["Data"]["فملی"]["1"]
print("bid:", level_1["buy_price"], "ask:", level_1["sell_price"])
Note. Keyword arguments are the safest way to call every method: a few sync methods are keyword-only, and the async/sync twins otherwise share the same signatures.
5. Authentication (Auth)
AuthAsyncClient.login(...) / AuthSyncClient.login(...) sends your credentials to POST https://core.hedgetech.ir/auth/user/token/issue. On success (HTTP 201) the server returns a JWT, and the SDK builds an authenticated client for you.
auth = await AuthAsyncClient.login(
UserName_or_Email="user@example.com",
Password="secure_password",
)
auth.token["Authorization"][:10] # 'eyJ0eXAiOi'
auth.Permissions # decoded JWT claims, e.g. {'sub': ..., 'exp': ...}
auth.httpx_Client # the authenticated HTTP client (retry-wrapped)
What the login builds for you
| Property | Value |
|---|---|
| HTTP client | RetriableAsyncClient / RetriableSyncClient — up to 10 retries |
| Protocol | HTTP/2 only, TLS verification enabled |
| Timeouts | connect 0.25 s, read 1.5 s, write 1.5 s, pool 0.25 s |
| Headers | the token returned by the server + origin: https://core.hedgetech.ir |
| Cookies | the cookies set at login are kept |
Good to know
- No automatic token refresh. When the JWT expires, requests start to fail. Call
login(...)again and recreate your clients with the new auth object. Permissionsis for display only. It is decoded without verifying the signature or the expiry, so never use it for security decisions.UpdatePermissionis a property. Readingauth.UpdatePermission(no parentheses) re-decodesauth.token.- Errors. A failed login (status other than
201) raisesValueErrorcarrying the server'sdetail. Network failures are raised byhttpxunchanged.
try:
auth = await AuthAsyncClient.login(UserName_or_Email="user", Password="wrong")
except ValueError as error:
print("Login failed:", error)
6. Data Engine — IME (Iran Mercantile Exchange)
DataEngine_Ime_AsyncClient / DataEngine_Ime_SyncClient wrap core.hedgetech.ir/data-engine/ime.
ime = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
The endpoints fall into three families:
| Family | Methods | Returns |
|---|---|---|
| Static data (rarely changes) | search_contracts, contracts_static_info_by_name, contracts_static_info_by_id |
Contracts |
| Live snapshots (one REST call) | live_overview_*, live_best_limit_*, live_aggregate_*, live_contract_info_*, live_allowed_price_range_* |
…Response |
| Live streams (WebSocket) | websocket_by_name, websocket_by_id |
generator of messages |
Every REST method except search_contracts comes in two flavours: *_by_name (contractName, e.g. "KASH05C170") and *_by_id (contractId; int values are accepted).
Step 1 — Find contracts
result = await ime.search_contracts(
market="IMEOption", # "IMEOption" | "IMEFutures" | "IMEDepositCertificate"
Search_char="KASH05C",
)
names = [item["contractName"] for item in result["Data"] if item]
Step 2 — Read static metadata
info = await ime.contracts_static_info_by_name(["KASH05C170"])
contract = info["Data"][0] # None if the contract was not found
print(contract["strikePrice"], contract["ExpirationDate"], contract["csize"])
print(contract["buyCommission"], contract["sellCommission"]) # fractions: 0.0025 = 0.25 %
Step 3 — Take live snapshots
names = ["KASH05C170", "KASH05P170"]
best = await ime.live_best_limit_by_name(names) # 3 depth levels
agg = await ime.live_aggregate_by_name(names) # OHLC, volume, last price...
price_rng = await ime.live_allowed_price_range_by_name(names) # min/max allowed price
oi = await ime.live_contract_info_by_name(names) # open interest
everything = await ime.live_overview_by_name(names) # static + all of the above
best["Data"]["KASH05C170"]["1"] # {'buy_quantity', 'buy_price', 'sell_quantity', 'sell_price'}
agg["Data"]["KASH05C170"]["last_price"]
price_rng["Data"]["KASH05C170"] # {'minAllowedPrice', 'maxAllowedPrice'}
oi["Data"]["KASH05C170"]["open_interest"]
| Snapshot | Key fields |
|---|---|
BestLimit (levels "1"–"3") |
buy_quantity, buy_price, sell_quantity, sell_price |
Aggregate |
date, time, trade_count, total_volume, total_value, closing_price, last_price, low_price, high_price, open_price, previous_close |
AllowedPriceRange |
minAllowedPrice, maxAllowedPrice |
ContractInfo |
open_interest, open_interest_changes |
Step 4 — Stream live data
See Live Streaming with WebSockets.
Sync usage
ime = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
best = ime.live_best_limit_by_name(["KASH05C170"])
7. Data Engine — TSE-IFB (Tehran Stock Exchange & Iran Fara Bourse)
DataEngine_TseIfb_AsyncClient / DataEngine_TseIfb_SyncClient wrap core.hedgetech.ir/data-engine/tse-ifb.
tse = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)
| Family | Methods |
|---|---|
| Static data | search_instruments, instruments_static_info_by_name, instruments_static_info_by_isin |
| Live snapshots | live_overview_*, live_best_limit_*, live_order_book_*, live_aggregate_*, live_institutional_vs_individual_*, live_contract_info_*, live_fund_info_*, live_ohlcv_last1m_* |
| Historical | historical_ohlcv_*, historical_corporateactions_* |
| Live streams | websocket_by_name, websocket_by_isin |
Every method above (except search_instruments) comes in *_by_name and *_by_isin flavours.
Search and static info
found = await tse.search_instruments(
market="SecuritiesAndFunds", # | "TreasuryBonds" | "StockOptions" | "StockFutures"
Search_char="فولاد",
)
print(found["Data"][0]["symbolName"])
info = await tse.instruments_static_info_by_name(["فملی", "خودرو"])
for item in info["Data"]:
if item: # None when a symbol was not found
print(item["symbolName"], item["minAllowedPrice"], item["maxAllowedPrice"])
Live snapshots
symbols = ["فملی", "خودرو"]
best = await tse.live_best_limit_by_name(symbols) # 6 depth levels
book = await tse.live_order_book_by_name(symbols) # full order book
agg = await tse.live_aggregate_by_name(symbols)
flows = await tse.live_institutional_vs_individual_by_name(symbols)
ohlcv = await tse.live_ohlcv_last1m_by_name(symbols) # last 1-minute candle
fund = await tse.live_fund_info_by_name(["اهرم"]) # NAV, units, market cap
deriv = await tse.live_contract_info_by_name(["<option or futures symbol>"]) # open interest, margins
best["Data"]["فملی"]["1"]["buy_price"]
| Snapshot | Key fields |
|---|---|
BestLimit (levels "1"–"6") |
buy_order_count, buy_quantity, buy_price, sell_order_count, sell_quantity, sell_price |
OrderBook |
Buy and Sell lists of {price, quantity, count} |
Aggregate |
same fields as IME Aggregate |
institutional_vs_individual |
buy_count_*, buy_volume_*, sell_count_*, sell_volume_* for individual / institution |
ContractInfo |
open_interest, initial_margin, required_margin |
FundInfo |
nav, units, marketCap, as_of |
OHLCV_live |
open, high, low, close, volume |
Historical data
import time
now = int(time.time())
candles = await tse.historical_ohlcv_by_name(
symbol_name="فملی",
start_timestamp=now - 90 * 24 * 3600, # Unix seconds
end_timestamp=now,
AdjustedPrice=True,
Resolution="D", # "1m","5m","15m","30m","1h","D","W","M"
)
data = candles["Data"] # one object; the lists are index-aligned
for ts, o, h, l, c, v in zip(
data["Date_timestamp"], data["Open"], data["High"],
data["Low"], data["Close"], data["Volume"],
):
print(ts, o, h, l, c, v)
actions = await tse.historical_corporateactions_by_name(
symbol_name="فملی",
start_timestamp=now - 5 * 365 * 24 * 3600,
end_timestamp=now,
)
for action in actions["Data"]:
print(action["corporateAction"], action["تاریخ"])
Historical methods take keyword-only arguments.
Datais a single object whose lists (Date_timestamp,Open,High,Low,Close,Volume) line up by index.
Sync usage
tse = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth)
info = tse.instruments_static_info_by_name(["فملی"])
8. Live Streaming with WebSockets
Streaming methods are generators. They open one WebSocket connection, yield each decoded message, and close the connection when the generator finishes.
| Client | Method | Message structure |
|---|---|---|
| IME | websocket_by_name(contract_names, event=None) |
{"channel": "IME Stream", "contractName", "timestamp", "data": {BestLimit, Aggregate, AllowedPriceRange, ContractInfo}} |
| IME | websocket_by_id(contract_ids, event=None) |
same, keyed by contractId |
| TSE-IFB | websocket_by_name(channels, symbol_names, event=None) |
{"channel", "symbolName", "timestamp", "data"} — one channel per message |
| TSE-IFB | websocket_by_isin(channels, symbol_isins, event=None) |
same, keyed by symbolIsin |
TSE-IFB channels: 'best-limit', 'order-book', 'ohlcv-last-1m', 'aggregate', 'institutional-vs-individual', 'contract-info', 'fund-info'.
timestamp is an ISO-formatted string.
Async stream with a stop switch
import asyncio
async def watch(ime):
stop = asyncio.Event()
stop.set() # the stream runs while the event is set
async for message in ime.websocket_by_name(["KASH05C170"], event=stop):
best = message["data"]["BestLimit"]["1"]
print(message["contractName"], best["buy_price"], best["sell_price"])
if best["buy_price"] >= 36000:
stop.clear() # ends the stream within ~2 seconds
TSE-IFB, several channels at once
async for update in tse.websocket_by_name(
channels=["best-limit", "aggregate"],
symbol_names=["فملی", "خودرو"],
):
if update["channel"] == "best-limit":
print(update["symbolName"], update["data"]["1"]["buy_price"])
elif update["channel"] == "aggregate":
print(update["symbolName"], update["data"]["last_price"])
Sync stream
The sync twins are blocking generators. Use threading.Event as the stop switch and, ideally, run them in a dedicated thread.
import threading
stop = threading.Event()
stop.set()
for message in ime_sync.websocket_by_name(["KASH05C170"], event=stop):
print(message["contractName"], message["data"]["Aggregate"]["last_price"])
Behavior you must know
- Stopping. The loop runs while
event.is_set(). Callevent.clear()to stop; it takes effect within about 2 seconds (the receive timeout). - Silent end after connect. Once connected, any error (closed connection, invalid JSON, network error) closes the connection and the generator ends without raising. A receive timeout is not an error.
- Connect errors do raise. For example, an authentication failure at connect time raises a
websocketsexception. - Reconnect loop. For a permanent stream, wrap the stream in a loop:
async def resilient_stream(ime, names, stop):
while stop.is_set():
try:
async for message in ime.websocket_by_name(names, event=stop):
yield message
except Exception as error: # connect-time failures
print("connect failed:", error)
await asyncio.sleep(1) # back-off, then reconnect
9. EMS Engine — Order Execution
The EMS Engine routes orders to your broker's OMS (order-management system). The flow is the same for IME and TSE-IFB:
sequenceDiagram
participant You
participant EMS as EmsEngine client
participant Core as core.hedgetech.ir
You->>EMS: Get_Captcha(OMS)
EMS->>Core: GET .../oms/login
Core-->>You: CAPTCHA image
You->>EMS: oms_login(username, password, captcha_value)
EMS->>Core: POST .../oms/login
Core-->>EMS: oms_session
You->>EMS: Buy_by_...() (builds an Order, nothing sent)
You->>EMS: order.send()
EMS->>Core: POST .../order/new/...
Core-->>You: OrderId
You->>EMS: order.Status() / Edit() / Delete()
9.1 Log in to the OMS
ems = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth)
captcha = await ems.Get_Captcha("Sahra | Karamad") # PIL image
captcha.show() # or captcha.save("captcha.png")
await ems.oms_login(
username="user123",
password="pass123",
captcha_value=input("CAPTCHA: "),
)
print(ems.Customer_FullName, ems.oms_session)
- Call
Get_Captchaandoms_loginwith the same client: the OMS name is not sent again at login; the session created byGet_Captchais used. Get_Captcha/oms_loginraiseValueErroron failure (a wrong CAPTCHA or wrong credentials give HTTP400with the server's message).- IME supports
'Sahra | Karamad'and'Sahra | Charisma'. TSE-IFB supports'Omex | Parsian','Omex | Khobregan','Sahra | Karamad','Sahra | NIBB'and'Sahra | Charisma'. - Constructor argument names differ between clients: async EMS clients take
AuthASyncClient=, sync EMS clients takeAuthSyncClient=.
9.2 Build, send, follow and cancel an order
Buy_by_* / Sell_by_* only build an Order. Nothing reaches the exchange until you call order.send().
| Client | Order-building methods |
|---|---|
| IME | Buy_by_ContractName, Sell_by_ContractName, Buy_by_ContractId, Sell_by_ContractId |
| TSE-IFB | Buy_by_Name, Sell_by_Name, Buy_by_isin, Sell_by_isin (accept Order_ValidityType and ValidityDate) |
order = await ems.Buy_by_ContractName(contractName="KASH05C170", Price=35_000, Volume=10)
if order is None:
raise RuntimeError("No OMS session — log in first")
await order.send() # submit
print(order.OrderId, order.OrderOmsId) # None if the send failed
status = await order.Status() # dict, or None on failure
print(status["order_status"], status["ExecutedVolume"], status["RemainedVolume"])
await order.Edit(Price=35_500, Volume=10) # Volume = new TOTAL volume
await order.Delete()
print(order.is_deleted, order.OrderStatus)
9.3 Order lifecycle & statuses
order_status |
Meaning | State |
|---|---|---|
InQueue |
accepted, waiting in the market queue | active |
PartiallyFilled |
partly executed | active |
Cancelled |
cancelled | final |
Broken |
broken / terminated by the system | final |
Settled |
fully executed | final |
order.OrderStatus starts as 'Unknown' and is updated by Status(), Delete() and the reconciliation inside Edit() / Delete().
9.4 Critical behavior of Order
send,Edit,StatusandDeletenever raise. Any error (non-200 response, network failure, unexpected body) is swallowed and the method returnsNone.send,EditandDeletealso returnNoneon success — so always check the outcome on the attributes (OrderId,is_deleted,OrderStatus,Price,Volume) or callStatus().
send()submits only ifOrderId is None. Only HTTP200counts as success. After a failure you can callsend()again; the sameInitialOrderIdis sent. If a network error happened, the first request may already have reached the exchange — verify before retrying blindly.Edit()sends all arguments every time. On TSE-IFB,Order_ValidityTypedefaults to'DAY', so an edit without it turns a GTC/GTD order into a DAY order — pass the current validity to keep it.Volumeis the new total volume (including the executed part).- After a non-200 response,
Edit()andDelete()read the real state withStatus()and reconcile the attributes, because the order may have changed state (filled, cancelled) in the meantime. Status()also updatesorder.OrderStatus.- Orders keep the session they were built with. If you log in again, rebuild your orders.
9.5 TSE-IFB specifics
ems = EmsEngine_TseIfb_AsyncClient(AuthASyncClient=auth)
order = await ems.Buy_by_Name(
symbolName="اطلس",
Price=100_000,
Volume=10,
Order_ValidityType="GTD", # 'DAY' (default) | 'GTC' | 'GTD'
ValidityDate=20271206, # used for GTD
)
await order.send()
Verify the ValidityDate format expected by your OMS before going live.
9.6 Sync version
ems = EmsEngine_Ime_SyncClient(AuthSyncClient=auth)
captcha = ems.Get_Captcha("Sahra | Karamad")
ems.oms_login(username="user123", password="pass123", captcha_value="abcd")
order = ems.Buy_by_ContractName(contractName="KASH05C170", Price=35_000, Volume=10)
order.send()
10. Algorithmic Trading Tutorial
This section walks from idea to a running bot. The examples are educational: they omit margin, taxes, exercise fees and risk limits that a real system must model. See the Disclaimer.
The shape of every trading bot
┌──────────┐ ┌────────────┐ ┌───────────┐ ┌──────────┐ ┌─────────────┐
│ Login │ → │ Market data│ → │ Signal │ → │ Risk │ → │ Execution │
│ (Auth) │ │ (Data Eng.)│ │ (yours) │ │ checks │ │ (EMS Engine)│
└──────────┘ └────────────┘ └───────────┘ └──────────┘ └─────────────┘
↑ │
└────────────── Status() feedback ◄────────────┘
Tutorial 1 — Research: moving-average crossover on historical data (TSE-IFB)
Goal: compute a signal offline before risking money.
import time
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient
def sma(values, window):
return [
sum(values[i - window + 1 : i + 1]) / window if i >= window - 1 else None
for i in range(len(values))
]
async def main():
auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
tse = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)
now = int(time.time())
candles = await tse.historical_ohlcv_by_name(
symbol_name="فملی",
start_timestamp=now - 365 * 24 * 3600,
end_timestamp=now,
AdjustedPrice=True, # adjusted prices avoid false signals around corporate actions
Resolution="D",
)
closes = candles["Data"]["Close"]
fast, slow = sma(closes, 10), sma(closes, 30)
position = 0
for i in range(1, len(closes)):
if None in (fast[i], slow[i], fast[i - 1], slow[i - 1]):
continue
crossed_up = fast[i - 1] <= slow[i - 1] and fast[i] > slow[i]
crossed_down = fast[i - 1] >= slow[i - 1] and fast[i] < slow[i]
if crossed_up and position == 0:
position = 1
print("BUY ", candles["Data"]["Date_timestamp"][i], closes[i])
elif crossed_down and position == 1:
position = 0
print("SELL", candles["Data"]["Date_timestamp"][i], closes[i])
asyncio.run(main())
Tutorial 2 — Live monitoring: best bid/ask spread watcher (IME)
Goal: stream a contract and react when the spread tightens.
import asyncio
async def spread_watcher(ime, contract_name: str, max_spread: int):
stop = asyncio.Event()
stop.set()
async for message in ime.websocket_by_name([contract_name], event=stop):
level_1 = message["data"]["BestLimit"]["1"]
bid, ask = level_1["buy_price"], level_1["sell_price"]
if bid <= 0 or ask <= 0: # empty side of the book
continue
spread = ask - bid
print(f"{message['timestamp']} bid={bid} ask={ask} spread={spread}")
if spread <= max_spread:
print("Spread is tight — candidate for a limit order.")
stop.clear()
Tutorial 3 — Risk-aware execution: place an order inside the allowed price range (IME)
Goal: never send a price the exchange will reject.
async def safe_buy(ime, ems, contract_name: str, desired_price: int, volume: int):
# 1) Static limits for this contract
static = (await ime.contracts_static_info_by_name([contract_name]))["Data"][0]
if static is None or not static["canBuy"]:
return None
if not (static["minValidBuyVolume"] <= volume <= static["maxValidBuyVolume"]):
raise ValueError("Volume outside the valid range")
# 2) Today's allowed price band
band = (await ime.live_allowed_price_range_by_name([contract_name]))["Data"][contract_name]
price = max(band["minAllowedPrice"], min(desired_price, band["maxAllowedPrice"]))
# 3) Build and send
order = await ems.Buy_by_ContractName(
contractName=contract_name, Price=int(price), Volume=volume
)
if order is None:
raise RuntimeError("Log in to the OMS first")
await order.send()
if order.OrderId is None: # send() never raises — check the attribute!
raise RuntimeError("Order was not accepted")
return order
Tutorial 4 — Order management loop: chase the market, then cancel
Goal: keep a limit order at the best bid, and give up after a deadline.
import time
ACTIVE = ("InQueue", "PartiallyFilled")
async def chase_bid(ime, ems, contract_name: str, volume: int, give_up_after: float = 60.0):
started = time.monotonic()
best = (await ime.live_best_limit_by_name([contract_name]))["Data"][contract_name]["1"]
order = await ems.Buy_by_ContractName(
contractName=contract_name, Price=best["buy_price"], Volume=volume
)
if order is None:
return None
await order.send()
if order.OrderId is None:
return order
while time.monotonic() - started < give_up_after:
status = await order.Status()
if status is None or status["order_status"] not in ACTIVE:
break # filled, cancelled, or unreadable
best = (await ime.live_best_limit_by_name([contract_name]))["Data"][contract_name]["1"]
if best["buy_price"] != status["Price"]:
await order.Edit(Price=best["buy_price"], Volume=status["Volume"])
await asyncio.sleep(1)
if order.OrderStatus in ACTIVE or order.OrderStatus == "Unknown":
await order.Delete()
return order
Use the range check from Tutorial 3 to choose the first price in real code. Note that
Edit()only changes an order that was successfully sent and swallows its own errors, so the loop re-readsStatus()every round.
Tutorial 5 — Strategy sketch: scanning IME options for box-spread edges
A long box spread on strikes K1 < K2 combines a bull call spread and a bear put spread; at expiry it pays K2 − K1 per unit regardless of the underlying price (for European-style options). A short box is the opposite side. A scanner compares the net premium plus commissions against K2 − K1.
from collections import defaultdict
async def scan_long_boxes(ime, search_text: str):
# 1) Static metadata for the chain
found = await ime.search_contracts(market="IMEOption", Search_char=search_text)
options = [o for o in found["Data"] if o]
# 2) Group calls/puts by (expiry, strike)
chain = defaultdict(dict)
for o in options:
chain[o["ExpirationDate"]][(o["optionType"], o["strikePrice"])] = o
# 3) Live best bid/ask for every contract in one request
names = [o["contractName"] for o in options]
quotes = (await ime.live_best_limit_by_name(names))["Data"]
def ask(o): return quotes[o["contractName"]]["1"]["sell_price"]
def bid(o): return quotes[o["contractName"]]["1"]["buy_price"]
results = []
for expiry, legs in chain.items():
strikes = sorted({k for (_, k) in legs})
for i, k1 in enumerate(strikes):
for k2 in strikes[i + 1 :]:
c1, c2 = legs.get(("Call", k1)), legs.get(("Call", k2))
p1, p2 = legs.get(("Put", k1)), legs.get(("Put", k2))
if not all((c1, c2, p1, p2)):
continue
# Long box: buy C1, sell C2, sell P1, buy P2 (cross the spread)
prices = (ask(c1), bid(c2), bid(p1), ask(p2))
if min(prices) <= 0: # an empty side of a book
continue
premium = ask(c1) - bid(c2) - bid(p1) + ask(p2)
fees = (
ask(c1) * c1["buyCommission"] + bid(c2) * c2["sellCommission"]
+ bid(p1) * p1["sellCommission"] + ask(p2) * p2["buyCommission"]
)
edge = (k2 - k1) - premium - fees # per unit, before margin/tax/time value
results.append((edge, expiry, k1, k2))
return sorted(results, reverse=True)
Before trading any such signal in production, also model initial/required margin (initialMargin, requiredMargin), exercise fees and taxes (ExerciseFeePhysical, ExerciseFeeCash, ExerciseSellTax), contract size (csize), the time value of money until ExpirationDate, liquidity at each depth level, and the risk that one leg fills while another does not.
Tutorial 6 — Putting it together: a minimal live bot skeleton
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.IME import DataEngine_Ime_AsyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_AsyncClient
CONTRACT = "KASH05C170"
MAX_SPREAD = 200
async def main():
auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
ime = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
ems = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth)
# OMS login (needs a human for the CAPTCHA)
(await ems.Get_Captcha("Sahra | Karamad")).show()
await ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))
stop = asyncio.Event()
stop.set()
order = None
async for message in ime.websocket_by_name([CONTRACT], event=stop):
level_1 = message["data"]["BestLimit"]["1"]
bid, ask = level_1["buy_price"], level_1["sell_price"]
if bid <= 0 or ask <= 0:
continue
if order is None and ask - bid <= MAX_SPREAD:
order = await ems.Buy_by_ContractName(contractName=CONTRACT, Price=bid, Volume=1)
await order.send()
if order.OrderId is None:
order = None # not accepted; try again later
else:
print("Order sent:", order.OrderId)
stop.clear() # one order, then stop
if order is not None:
print(await order.Status())
asyncio.run(main())
Production checklist
- Re-login on token expiry. The SDK does not refresh tokens.
- Reconnect loop around every WebSocket (streams end silently on error).
- Verify every order via attributes /
Status()— order methods swallow errors. - Idempotency. After a network error on
send(), check whether the order exists before resending. - Respect limits. Use
minAllowedPrice/maxAllowedPriceandmin/maxValid{Buy,Sell}Volumefrom static info. - Guard empty books. A price of
0usually means an empty side. - Kill-switch. Wire an
Eventso you can stop streams and cancel open orders on demand. - Log everything (
OrderId,OrderOmsId, timestamps, status transitions). - Paper-trade first with the data clients only, then go live with small volume.
11. Data Conventions
| Topic | Convention |
|---|---|
| Prices | Integers/floats in IRR (Rial) |
| Commissions, margins, taxes | Fractions (0.0025 = 0.25 %) |
ServerTimeStamp (in Status) |
Unix timestamp as a float |
WebSocket timestamp |
ISO-formatted string |
| Historical timestamps | Unix timestamps in seconds |
| Best-limit depth | 3 levels on IME, 6 levels on TSE-IFB (keys "1", "2", …) |
| Missing instruments | None entries inside Data lists |
| Response envelope | {"Data": ..., "Status": {...}} |
The Status section of every REST response:
| Field | Meaning |
|---|---|
State |
True on success |
ServerTimeStamp |
Server time (Unix float) |
Version, Author |
API metadata |
Description |
{"fa": ..., "en": ...} human-readable message |
StatusCode |
Numeric status |
12. Error Handling & Reliability
| Where | What you get |
|---|---|
| Any REST data method | ValueError with the server's detail when the HTTP status is not a success |
login |
ValueError (status ≠ 201); httpx exceptions for network errors |
Get_Captcha, oms_login |
ValueError (message from detail.Status.Description.en or raw text) |
Order.send / Edit / Status / Delete |
Never raise — they return None; check attributes |
| WebSocket connect | websockets exceptions (e.g. auth failure) |
| WebSocket after connect | Generator ends silently |
Recommended pattern
async def safe_call(coro):
try:
return await coro
except ValueError as error: # API-level error with the server's message
print("API error:", error)
except Exception as error: # network / TLS / timeout
print("Transport error:", error)
Timeouts are short by design (connect 0.25 s, read 1.5 s) to fit trading latency budgets, and the client retries up to 10 times. If you call large endpoints over slow links, expect occasional timeouts and plan for them.
The bare
exceptblocks insideOrderalso catch cancellation (asyncio.CancelledErrorin async clients,KeyboardInterruptin sync clients). Plan your shutdown logic around the stop-Eventpattern rather than relying on task cancellation.
13. API Reference (Cheat-Sheet)
Auth
| Call | Returns |
|---|---|
await AuthAsyncClient.login(UserName_or_Email, Password) / AuthSyncClient.login(...) |
authenticated client |
auth.token, auth.httpx_Client, auth.Permissions |
token dict, HTTP client, decoded claims |
IME Data Engine
| Method | Endpoint family |
|---|---|
search_contracts(market, Search_char) |
static |
contracts_static_info_by_name(contract_names) / …_by_id(contract_ids) |
static |
live_overview_by_name / _by_id |
live |
live_best_limit_by_name / _by_id |
live |
live_aggregate_by_name / _by_id |
live |
live_contract_info_by_name / _by_id |
live |
live_allowed_price_range_by_name / _by_id |
live |
websocket_by_name(contract_names, event) / websocket_by_id(contract_ids, event) |
stream |
TSE-IFB Data Engine
| Method | Endpoint family |
|---|---|
search_instruments(market, Search_char) |
static |
instruments_static_info_by_name(symbol_names) / …_by_isin(symbol_isins) |
static |
live_overview_*, live_best_limit_*, live_order_book_*, live_aggregate_* |
live |
live_institutional_vs_individual_*, live_contract_info_*, live_fund_info_*, live_ohlcv_last1m_* |
live |
historical_ohlcv_by_name / _by_isin |
historical |
historical_corporateactions_by_name / _by_isin |
historical |
websocket_by_name(channels, symbol_names, event) / websocket_by_isin(channels, symbol_isins, event) |
stream |
EMS Engine
| Client | Methods |
|---|---|
| Both | Get_Captcha(OMS), oms_login(username, password, captcha_value) |
| IME | Buy_by_ContractName, Sell_by_ContractName, Buy_by_ContractId, Sell_by_ContractId |
| TSE-IFB | Buy_by_Name, Sell_by_Name, Buy_by_isin, Sell_by_isin |
Order |
send(), Edit(Price, Volume[, Order_ValidityType, ValidityDate]), Status(), Delete() |
Client attributes after OMS login: Customer_FullName, Customer_IMEBourseCode (IME) or Customer_TSEBourseCode (TSE-IFB), oms_session.
Order attributes: ContractNameOrId / SymbolNameOrIsin, Price, Volume, is_deleted, OrderStatus, OrderId, OrderOmsId.
14. Support & Contact
Questions, bug reports, account or access requests? The HedgeTech team is happy to help.
| Channel | Details |
|---|---|
| ✉️ Support e-mail | info@hedgetech.ir |
| 🛒 Store | store.hedgetech.ir |
| linkedin.com/company/hedgetech-ir | |
| 🌐 Platform | core.hedgetech.ir |
When you contact support, please include: your SDK version, Python version, the method you called, the full error message, and the time of the event (including time zone). Never send passwords or tokens.
15. Disclaimer
This SDK provides tools for accessing market data and routing orders. It is not investment advice. Trading — in particular with leverage and derivatives — carries substantial risk of loss. The examples in this document are educational and intentionally simplified; you are solely responsible for testing, risk management, regulatory compliance and any trading decisions made with this software. Market data and order handling depend on exchange, broker (OMS) and network conditions that HedgeTech does not control.
© HedgeTech — All rights reserved. core.hedgetech.ir · info@hedgetech.ir · store.hedgetech.ir · LinkedIn