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
- 8.1 How streaming works
- 8.2 Message anatomy
- 8.3 Choosing channels (TSE-IFB)
- 8.4 Async stream with a stop switch
- 8.5 TSE-IFB, several channels at once
- 8.6 Sync stream
- 8.7 Behavior you must know
- 8.8 Pattern — keep only the latest state (conflation)
- 8.9 Pattern — producer / consumer with a queue
- 8.10 Pattern — a production-grade reconnecting stream
- 8.11 Pattern — several streams at once
- 8.12 Pattern — route TSE-IFB channels with a dispatch table
- 8.13 Pattern — sync streams in threads
- 8.14 Pattern — WebSocket for reaction, REST for confirmation
- 8.15 Streaming troubleshooting
- EMS Engine — Order Execution
- Algorithmic Trading Tutorial
- The shape of every trading bot
- From Data to Execution — The Decision Pipeline
- Tutorial 1 — Research: moving-average crossover on historical data (TSE-IFB)
- Tutorial 2 — Live monitoring: best bid/ask spread watcher (IME)
- Tutorial 3 — Risk-aware execution: place an order inside the allowed price range (IME)
- Tutorial 4 — Order management loop: chase the market, then cancel
- Tutorial 5 — Strategy sketch: scanning IME options for box-spread edges
- Tutorial 6 — Putting it together: a minimal live bot skeleton
- Production checklist
- 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. - Data → decision → execution. A complete, tested pipeline pattern: stream or request data, let conditions decide, pass a risk guard, execute and follow the order (see §10).
- 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. Each call opens one WebSocket connection, yields every decoded message, and closes the connection when the generator finishes. The WebSocket is the lowest-latency way to receive market data: the server pushes updates to you, instead of you asking for them.
| 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'.
8.1 How streaming works
your code SDK generator core.hedgetech.ir
───────── ───────────── ─────────────────
async for msg in ┌─ connect(wss://…, headers=token) ─► authenticate
ime.websocket_by_name(...) │ subscribe (query string)
▲ │ ┌─ ws.recv() (2 s timeout) ◄────── push update
└── yield decoded JSON ◄┘ └─ loop while event.is_set()
on error / event.clear() → close the connection, generator ends
Key facts:
- One connection, many instruments. Every contract or symbol you pass shares a single connection. Tell messages apart by
message["contractName"](IME) orupdate["symbolName"]+update["channel"](TSE-IFB). - IME messages are full snapshots. Each message carries the complete
BestLimit,Aggregate,AllowedPriceRangeandContractInfoof one contract. You never have to merge partial updates: the newest message is the current state. - TSE-IFB messages are per channel. Each message carries one channel's data for one symbol. If your logic needs several channels at once (for example best-limit and aggregate), keep a small state object per symbol and merge — see 8.12.
- The stream is pulled, not buffered by you. The generator receives the next message only when your loop asks for it. If your loop body is slow, messages queue up in the connection. Keep the loop body fast, or hand work to another task (8.9).
- The same data is available over REST. The
dataof an IME stream message has the same four sections as one entry oflive_overview_by_name. Code written for one source works for the other — see the decision pipeline.
8.2 Message anatomy
IME — one message (illustrative values):
{
"channel": "IME Stream",
"contractName": "KASH05C170",
"timestamp": "2025-01-15T14:30:00.123456",
"data": {
"BestLimit": {
"1": {"buy_quantity": 1500, "buy_price": 35200, "sell_quantity": 800, "sell_price": 35300},
"2": {"buy_quantity": 1200, "buy_price": 35100, "sell_quantity": 600, "sell_price": 35400},
"3": {"buy_quantity": 900, "buy_price": 35000, "sell_quantity": 400, "sell_price": 35500}
},
"Aggregate": {
"date": "2025-01-15", "time": "14:30:00", "trade_count": 1250,
"total_volume": 50000, "total_value": 1765000000,
"closing_price": 35250.0, "last_price": 35250.0,
"low_price": 34900.0, "high_price": 35500.0,
"open_price": 35100.0, "previous_close": 35000.0
},
"AllowedPriceRange": {"minAllowedPrice": 33250.0, "maxAllowedPrice": 36750.0},
"ContractInfo": {"open_interest": 125000, "open_interest_changes": 2500}
}
}
TSE-IFB — two messages (illustrative values):
{"channel": "best-limit", "symbolName": "فملی", "timestamp": "2025-01-15T10:15:02.481203",
"data": {"1": {"buy_order_count": 12, "buy_quantity": 85000, "buy_price": 4210,
"sell_order_count": 7, "sell_quantity": 40000, "sell_price": 4215}}}
{"channel": "aggregate", "symbolName": "فملی", "timestamp": "2025-01-15T10:15:03.002115",
"data": {"last_price": 4212.0, "total_volume": 91000000, "trade_count": 5120}}
Remember: timestamp is an ISO string, and an empty side of the book shows 0 prices and quantities.
8.3 Choosing channels (TSE-IFB)
Subscribe only to what your logic reads — fewer channels means fewer messages to process.
| Channel | data type |
Typical use |
|---|---|---|
best-limit |
BestLimit_WS_* (levels "1"–"6") |
quoting, spread and imbalance conditions, order pricing |
order-book |
OrderBook_WS_* (Buy / Sell lists) |
depth analysis, queue position |
aggregate |
Aggregate_WS_* |
last price, volume, OHLC of the day |
ohlcv-last-1m |
OHLCV_WS_* |
intraday candle logic |
institutional-vs-individual |
institutional_vs_individual_WS_* |
smart-money flow filters |
contract-info |
ContractInfo_WS_* |
open interest and margins of options / futures |
fund-info |
FundInfo_WS_* |
NAV vs. market price (ETF arbitrage) |
8.4 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
8.5 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"])
8.6 Sync stream
The sync twins are blocking generators. Use threading.Event as the stop switch and, ideally, run them in a dedicated thread (see 8.13).
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"])
8.7 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. - Silence is not an error either. If the server simply stops sending (market closed, a half-dead connection), the generator keeps waiting. Detect this yourself with a watchdog (8.10).
- An expired token cannot reconnect. Reconnecting uses the token held by the
Authclient. After the JWT expires you must log in again and rebuild your clients.
8.8 Pattern — keep only the latest state (conflation)
Trading decisions need the current state, not every intermediate tick. Let the stream overwrite a dictionary, and let a separate loop decide at its own pace. A slow decision never delays data intake, and old ticks are discarded automatically.
import asyncio
latest: dict[str, dict] = {} # contractName -> newest message
updated = asyncio.Event() # "something new arrived"
async def collect(ime, names, run: asyncio.Event):
async for message in ime.websocket_by_name(names, event=run):
latest[message["contractName"]] = message
updated.set()
async def decide(run: asyncio.Event):
while run.is_set():
try:
await asyncio.wait_for(updated.wait(), timeout=1.0)
except asyncio.TimeoutError:
continue
updated.clear()
for name, message in list(latest.items()):
level_1 = message["data"]["BestLimit"]["1"]
print(name, level_1["buy_price"], level_1["sell_price"])
async def main(ime):
run = asyncio.Event()
run.set()
await asyncio.gather(collect(ime, ["KASH05C170", "KASH05P170"], run), decide(run))
8.9 Pattern — producer / consumer with a queue
When you must see every message (logging, recording ticks to disk, event-sourced strategies), put a bounded queue between the stream and the consumer. When the queue is full, drop the oldest message so the stream is never blocked.
import asyncio
queue: asyncio.Queue = asyncio.Queue(maxsize=1000)
def push(item):
if queue.full():
queue.get_nowait() # drop the oldest; stale ticks are worth little
queue.put_nowait(item)
async def producer(ime, names, run: asyncio.Event):
try:
async for message in ime.websocket_by_name(names, event=run):
push(message)
finally:
push(None) # sentinel: the stream ended
async def consumer():
while (message := await queue.get()) is not None:
# slow work is fine here (database writes, indicators, ...)
print(message["timestamp"], message["contractName"])
async def main(ime):
run = asyncio.Event()
run.set()
await asyncio.gather(producer(ime, ["KASH05C170"], run), consumer())
8.10 Pattern — a production-grade reconnecting stream
Because streams end silently on errors and stay silent when the feed dies, a robust bot needs three things: a reconnect loop, exponential back-off, and a watchdog that stops a stream that has gone quiet. The watchdog uses the library's own stop switch.
import asyncio
import time
async def stream_forever(open_stream, on_message, shutdown: asyncio.Event,
stale_after: float = 15.0, max_delay: float = 30.0):
"""
open_stream(run_event) -> an async generator, e.g.
lambda run: ime.websocket_by_name(names, event=run)
on_message(message) -> awaitable called for every message
shutdown -> set it to stop everything for good
stale_after -> seconds without messages before we reconnect
"""
delay = 1.0
while not shutdown.is_set():
run = asyncio.Event() # fresh stop switch for every connection
run.set()
last_seen = time.monotonic()
async def watchdog():
while run.is_set():
await asyncio.sleep(1.0)
if shutdown.is_set() or time.monotonic() - last_seen > stale_after:
run.clear() # the generator ends within ~2 seconds
guard = asyncio.create_task(watchdog())
try:
async for message in open_stream(run):
last_seen = time.monotonic()
delay = 1.0 # healthy connection: reset the back-off
await on_message(message)
except Exception as error: # connect-time failures (auth, network)
print("stream error:", repr(error))
finally:
run.clear()
guard.cancel()
if not shutdown.is_set():
print(f"stream ended — reconnecting in {delay:.0f}s")
await asyncio.sleep(delay)
delay = min(delay * 2, max_delay)
Usage:
shutdown = asyncio.Event()
async def on_message(message):
... # keep it fast; see 8.8 / 8.9
await stream_forever(
lambda run: ime.websocket_by_name(["KASH05C170"], event=run),
on_message,
shutdown,
stale_after=20.0,
)
Market hours. Outside trading hours a healthy connection can legitimately be quiet, which would trigger reconnects every
stale_afterseconds. Either pause your bot outside trading hours or use a largestale_after.
8.11 Pattern — several streams at once
Run IME and TSE-IFB streams side by side as independent tasks. Each one can have its own reconnect loop and its own state.
async def main(ime, tse):
shutdown = asyncio.Event()
async def on_ime(message):
...
async def on_tse(update):
...
await asyncio.gather(
stream_forever(
lambda run: ime.websocket_by_name(["KASH05C170", "KASH05P170"], event=run),
on_ime, shutdown,
),
stream_forever(
lambda run: tse.websocket_by_name(
channels=["best-limit", "aggregate"],
symbol_names=["فملی", "خودرو"],
event=run,
),
on_tse, shutdown,
),
)
8.12 Pattern — route TSE-IFB channels with a dispatch table
A single TSE-IFB connection can carry several channels. A dispatch table keeps the code flat and makes adding a channel a one-line change.
async def on_best_limit(update):
level = update["data"]["1"]
print(update["symbolName"], "bid", level["buy_price"], "ask", level["sell_price"])
async def on_aggregate(update):
print(update["symbolName"], "last", update["data"]["last_price"])
HANDLERS = {
"best-limit": on_best_limit,
"aggregate": on_aggregate,
}
async def route(tse, symbols, run):
async for update in tse.websocket_by_name(
channels=list(HANDLERS), # subscribe exactly to the channels you handle
symbol_names=symbols,
event=run,
):
handler = HANDLERS.get(update["channel"])
if handler is not None:
await handler(update)
When your condition needs several channels at once, merge them into one state per symbol (a complete example is in the pipeline section).
8.13 Pattern — sync streams in threads
A sync stream blocks its thread. Read it in a background thread and hand messages to your main thread through a queue.Queue.
import queue
import threading
messages: queue.Queue = queue.Queue(maxsize=1000)
run = threading.Event()
run.set()
def reader():
for message in ime_sync.websocket_by_name(["KASH05C170"], event=run):
try:
messages.put_nowait(message)
except queue.Full:
pass # drop: a newer message will follow
threading.Thread(target=reader, daemon=True).start()
try:
while run.is_set():
try:
message = messages.get(timeout=1.0)
except queue.Empty:
continue
level_1 = message["data"]["BestLimit"]["1"]
print(message["contractName"], level_1["buy_price"], level_1["sell_price"])
except KeyboardInterrupt:
run.clear() # the reader thread ends within ~2 seconds
8.14 Pattern — WebSocket for reaction, REST for confirmation
The stream tells you that the market moved; a REST snapshot confirms the state you are about to act on. A common, safe sequence for a trigger:
- The stream delivers a message and your conditions say "act".
- Just before sending, re-read the book with one REST call (
live_best_limit_by_name) and re-check the condition on this fresh data. - Only then build and send the order.
async def confirmed_trigger(ime, name, condition):
snapshot = (await ime.live_overview_by_name([name]))["Data"][name]
if snapshot is None:
return False
return condition(snapshot["BestLimit"]["1"]) # a plain function of the best level
This costs one extra request per trigger — negligible next to the cost of acting on stale data. The full version is in the decision pipeline.
8.15 Streaming troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
Exception at connect (e.g. InvalidStatus) |
token expired or invalid | log in again, rebuild the clients |
| The loop ends with no error | connection closed / network error / invalid JSON | wrap in a reconnect loop (8.10) |
| The loop never yields | market closed, or the feed is silent | check the market hours; add a watchdog |
Prices are 0 |
empty side of the book | skip such messages in your conditions |
| Loop falls behind real time | handler too slow | conflate (8.8) or queue (8.9) |
| Stopping takes ~2 seconds | by design (receive timeout) | clear the stop event early; it is not a hang |
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 ◄────────────┘
From Data to Execution — The Decision Pipeline
A trading bot is a pipeline in which data flows in, conditions create the decision, and only then is an order executed. Keeping these stages separate is what makes a bot testable, auditable and safe.
┌──────────────┐ ┌────────────┐ ┌──────────────┐ ┌────────────┐ ┌────────────┐ ┌──────────────┐
│ 1. SOURCE │→ │ 2. NORMAL- │→ │ 3. CONDITIONS│→ │ 4. DECISION│→ │ 5. RISK │→ │ 6. EXECUTION │
│ WebSocket or │ │ IZE │ │ (predicates) │ │ side/price/│ │ GUARD │ │ EMS: build, │
│ REST request │ │ → Quote │ │ True / False │ │ volume │ │ allow/deny │ │ send, follow │
└──────────────┘ └────────────┘ └──────────────┘ └────────────┘ └────────────┘ └──────┬───────┘
▲ │
└──────────────────────── Status() / fills feed back into the guard ◄────────────────┘
| Stage | Responsibility | SDK pieces |
|---|---|---|
| 1. Source | Bring data in | websocket_by_name, live_overview_by_name, live_best_limit_by_name, … |
| 2. Normalize | One internal Quote object, whatever the source |
your to_quote() |
| 3. Conditions | Small pure functions: Quote → bool |
your predicates |
| 4. Decision | Combine conditions into what to do (side, price, volume) | your Rule |
| 5. Risk guard | Final veto: price band, size, position limit, cooldown, one order in flight | AllowedPriceRange, static volume limits |
| 6. Execution | Turn an approved decision into an exchange order and follow it | Buy_by_* / Sell_by_*, send, Status, Edit, Delete |
The rest of this section builds a small, reusable kit and then plugs the same kit into two different sources: a WebSocket (Part A) and periodic REST requests (Part B). Only stage 1 changes.
The shared kit (stages 2–6)
# kit.py
import asyncio
import time
from dataclasses import dataclass
from typing import Awaitable, Callable, Literal, Optional
Side = Literal["BUY", "SELL"]
# ── Stage 2: one normalized quote ───────────────────────────────────────────
@dataclass(frozen=True)
class Quote:
name: str
bid: int
bid_qty: int
ask: int
ask_qty: int
last: float
min_price: float
max_price: float
source: str # "ws" | "rest"
received_at: float # time.monotonic() when we received it
open_interest: int = 0
@property
def valid(self) -> bool: # both sides of the book are populated
return self.bid > 0 and self.ask > 0 and self.ask >= self.bid
@property
def spread(self) -> int:
return self.ask - self.bid
@property
def imbalance(self) -> float: # share of buy quantity at level 1; 0.5 = balanced
total = self.bid_qty + self.ask_qty
return self.bid_qty / total if total else 0.5
def to_quote(name: str, blob: dict, source: str) -> Quote:
"""
`blob` is the IME `data` of a WebSocket message OR one entry of
`live_overview_by_name(...)["Data"]` — both have the same four sections.
"""
level = blob["BestLimit"]["1"]
return Quote(
name=name,
bid=int(level["buy_price"]), bid_qty=int(level["buy_quantity"]),
ask=int(level["sell_price"]), ask_qty=int(level["sell_quantity"]),
last=float(blob["Aggregate"]["last_price"]),
min_price=float(blob["AllowedPriceRange"]["minAllowedPrice"]),
max_price=float(blob["AllowedPriceRange"]["maxAllowedPrice"]),
open_interest=int(blob["ContractInfo"]["open_interest"]),
source=source,
received_at=time.monotonic(),
)
# ── Stage 3: conditions are small pure functions Quote -> bool ──────────────
Condition = Callable[[Quote], bool]
def fresh(max_age_s: float) -> Condition:
return lambda q: time.monotonic() - q.received_at <= max_age_s # never act on stale data
def spread_at_most(max_spread: int) -> Condition:
return lambda q: q.valid and q.spread <= max_spread
def bid_at_most(limit: int) -> Condition:
return lambda q: q.valid and q.bid <= limit
def ask_at_least(limit: int) -> Condition:
return lambda q: q.valid and q.ask >= limit
def buy_pressure(min_share: float) -> Condition:
return lambda q: q.valid and q.imbalance >= min_share
def sell_pressure(max_share: float) -> Condition:
return lambda q: q.valid and q.imbalance <= max_share
def inside_price_band(margin: float = 0.0) -> Condition:
# the quote must lie strictly inside today's allowed range, `margin` (fraction) away from the edges
return lambda q: (q.min_price * (1 + margin) <= q.bid) and (q.ask <= q.max_price * (1 - margin))
def all_of(*conditions: Condition) -> Condition:
return lambda q: all(c(q) for c in conditions)
def any_of(*conditions: Condition) -> Condition:
return lambda q: any(c(q) for c in conditions)
# ── Stage 4: a rule turns "conditions hold" into a concrete decision ────────
@dataclass(frozen=True)
class Decision:
side: Side
price: int
volume: int
reason: str
@dataclass(frozen=True)
class Rule:
name: str
when: Condition
side: Side
price_from: Callable[[Quote], int]
volume: int
def evaluate(self, q: Quote) -> Optional[Decision]:
if self.when(q):
return Decision(self.side, int(self.price_from(q)), self.volume, self.name)
return None
# ── Stage 5: the risk guard has the final word ──────────────────────────────
class RiskGuard:
def __init__(self, *, max_volume: int, max_position: int, cooldown_s: float, max_orders: int):
self.max_volume = max_volume
self.max_position = max_position # max |net filled volume| per contract
self.cooldown_s = cooldown_s
self.max_orders = max_orders
self._in_flight: set[str] = set() # one order at a time per contract
self._last_sent: dict[str, float] = {}
self._sent = 0
self._position: dict[str, int] = {} # net filled volume per contract (BUY +, SELL -)
def check(self, q: Quote, d: Decision) -> tuple[bool, str]:
if q.name in self._in_flight:
return False, "an order for this contract is already working"
if time.monotonic() - self._last_sent.get(q.name, -1e9) < self.cooldown_s:
return False, "cooldown"
if self._sent >= self.max_orders:
return False, "daily order cap reached"
if d.volume > self.max_volume:
return False, "volume above the configured maximum"
if not (q.min_price <= d.price <= q.max_price):
return False, "price outside today's allowed range"
signed = d.volume if d.side == "BUY" else -d.volume
if abs(self._position.get(q.name, 0) + signed) > self.max_position:
return False, "position limit"
return True, "ok"
def record_fill(self, name: str, side: Side, volume: int) -> None:
self._position[name] = self._position.get(name, 0) + (volume if side == "BUY" else -volume)
def reserve(self, name: str) -> None:
self._in_flight.add(name)
self._last_sent[name] = time.monotonic()
self._sent += 1
def release(self, name: str) -> None:
self._in_flight.discard(name)
# ── Stage 6: execution = build, send, VERIFY, follow, cancel on timeout ─────
FINAL = ("Cancelled", "Broken", "Settled")
Builder = Callable[[Side, str, int, int], Awaitable["Order | None"]]
class Executor:
def __init__(self, build: Builder, guard: RiskGuard, ttl_s: float = 30.0, log=print):
self.build, self.guard, self.ttl_s, self.log = build, guard, ttl_s, log
async def fire(self, q: Quote, d: Decision) -> None:
try:
order = await self.build(d.side, q.name, d.price, d.volume)
if order is None:
self.log(f"[{q.name}] no OMS session — log in first")
return
await order.send()
if order.OrderId is None: # send() never raises: check the attribute
self.log(f"[{q.name}] order NOT accepted ({d.reason})")
return
self.log(f"[{q.name}] {d.side} {d.volume} @ {d.price} sent, id={order.OrderId} ({d.reason})")
status = await self.supervise(order)
self.log(f"[{q.name}] final: {status}")
executed = status["ExecutedVolume"] if status else d.volume # unknown -> assume the worst
self.guard.record_fill(q.name, d.side, executed)
except Exception as error: # never let a task die silently
self.log(f"[{q.name}] execution error: {error!r}")
finally:
self.guard.release(q.name)
async def supervise(self, order) -> Optional[dict]:
deadline = time.monotonic() + self.ttl_s
while time.monotonic() < deadline:
status = await order.Status()
if status is not None and status["order_status"] in FINAL:
return status
await asyncio.sleep(1.0)
await order.Delete() # time-boxed: do not leave orders behind
return await order.Status()
QUIET_VETOES = ("cooldown", "an order for this contract is already working") # expected on every tick
# ── Glue: evaluate rules, ask the guard, fire without blocking the loop ─────
def handle(q: Quote, rules: list[Rule], guard: RiskGuard, executor: Executor, log=print) -> None:
for rule in rules:
decision = rule.evaluate(q)
if decision is None:
continue
allowed, why = guard.check(q, decision)
if not allowed:
if why not in QUIET_VETOES:
log(f"[{q.name}] rule '{rule.name}' vetoed: {why}")
return
guard.reserve(q.name)
asyncio.create_task(executor.fire(q, decision)) # the loop keeps running meanwhile
return # first matching rule wins
Builders adapt the kit to each market (so the kit itself never changes):
def ime_builder(ems) -> Builder:
async def build(side, name, price, volume):
method = ems.Buy_by_ContractName if side == "BUY" else ems.Sell_by_ContractName
return await method(contractName=name, Price=price, Volume=volume)
return build
def tse_builder(ems) -> Builder:
async def build(side, name, price, volume):
method = ems.Buy_by_Name if side == "BUY" else ems.Sell_by_Name
return await method(symbolName=name, Price=price, Volume=volume)
return build
Writing rules
A rule is conditions + pricing + size. Because conditions are plain functions, rules read like a specification and can be unit-tested without any network:
# rules.py
from kit import *
rules = [
Rule(
name="support-bid",
when=all_of(
fresh(2.0), # data is at most 2 s old
spread_at_most(200), # tight market (price units, IRR)
buy_pressure(0.65), # at least 65 % of level-1 quantity is on the bid
bid_at_most(36_000), # never pay above our limit
inside_price_band(0.01), # stay 1 % away from the daily limits
),
side="BUY",
price_from=lambda q: q.bid, # join the best bid
volume=1,
),
Rule(
name="take-profit-offer",
when=all_of(fresh(2.0), spread_at_most(200), ask_at_least(37_000), sell_pressure(0.35)),
side="SELL",
price_from=lambda q: q.ask, # join the best ask
volume=1,
),
]
Condition cookbook:
| Idea | Condition |
|---|---|
| Price below a level | bid_at_most(limit) |
| Tight market | spread_at_most(n) |
| Order-flow pressure | buy_pressure(0.65) / sell_pressure(0.35) |
| Never trade on stale data | fresh(2.0) |
| Stay away from daily limits | inside_price_band(0.01) |
| Either of two setups | any_of(a, b) |
| Several requirements | all_of(a, b, c) |
Unit tests need no network at all:
import time
from kit import *
from rules import rules
q = Quote(name="T", bid=35_200, bid_qty=1500, ask=35_300, ask_qty=800, last=35_250.0,
min_price=33_250.0, max_price=36_750.0, source="test", received_at=time.monotonic())
assert rules[0].evaluate(q) is not None # all conditions hold -> a BUY decision
assert rules[1].evaluate(q) is None # the sell setup does not hold
Part A — Socket mode: data pushed by the Data Engine
The WebSocket is the source. Every message is normalized into a Quote and stored (latest wins); a separate loop evaluates the rules at a fixed cadence. This is the conflation pattern of 8.8 combined with the reconnecting stream of 8.10 (stream_forever is defined there).
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.IME import DataEngine_Ime_AsyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_AsyncClient
from kit import * # the shared kit above
from rules import rules # the rules above
from streaming import stream_forever # the function from section 8.10
async def run_socket_mode(open_stream, normalize, rules, executor, guard,
shutdown: asyncio.Event, decision_period: float = 0.05):
latest: dict[str, Quote] = {}
async def on_message(message): # stage 1 -> 2
quote = normalize(message)
if quote is not None:
latest[quote.name] = quote
async def decision_loop(): # stages 3 -> 6
while not shutdown.is_set():
await asyncio.sleep(decision_period) # 20 decisions per second at most
for quote in list(latest.values()):
handle(quote, rules, guard, executor)
await asyncio.gather(
stream_forever(open_stream, on_message, shutdown),
decision_loop(),
)
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)
(await ems.Get_Captcha("Sahra | Karamad")).show()
await ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))
guard = RiskGuard(max_volume=5, max_position=10, cooldown_s=10.0, max_orders=50)
executor = Executor(ime_builder(ems), guard, ttl_s=30.0)
names = ["KASH05C170", "KASH05P170"]
shutdown = asyncio.Event()
await run_socket_mode(
open_stream=lambda run: ime.websocket_by_name(names, event=run),
normalize=lambda m: to_quote(m["contractName"], m["data"], "ws"),
rules=rules,
executor=executor,
guard=guard,
shutdown=shutdown,
)
asyncio.run(main())
What happens on every tick, end to end:
- The Data Engine pushes a snapshot →
to_quotenormalizes it →latest[name]is overwritten. - Every 50 ms the decision loop evaluates each rule's conditions on the newest quotes.
- A matching rule produces a decision (side, price, volume).
- The risk guard checks price band, volume, net position limit, cooldown, order cap and "one order in flight".
- The executor builds the order, sends it, verifies
OrderId, follows it withStatus(), cancels it if it is still open afterttl_s, and records the filled volume in the guard (so the position limit works).
If the connection dies, stream_forever reconnects, and fresh(2.0) automatically blocks decisions on data older than 2 seconds in the meantime.
Part B — Request mode: data requested on a schedule
The source is periodic REST requests. Only stage 1 differs: instead of subscribing, you ask. One live_overview_by_name call fetches the state of many contracts, and each entry has the same sections as a stream message, so the same to_quote, rules, guard and executor are reused.
import asyncio
import time
from kit import *
async def run_request_mode(ime, names, rules, executor, guard,
shutdown: asyncio.Event, period: float = 1.0, log=print):
while not shutdown.is_set():
started = time.monotonic()
try:
overview = await ime.live_overview_by_name(names) # stage 1: REST request
except ValueError as error: # API error with the server's message
log("API error:", error)
overview = None
except Exception as error: # timeout / network
log("transport error:", repr(error))
overview = None
if overview is not None:
for name, blob in overview["Data"].items():
if blob is None: # unknown contract
continue
quote = to_quote(name, blob, "rest") # stage 2 (same function)
handle(quote, rules, guard, executor) # stages 3 -> 6 (same code)
await asyncio.sleep(max(0.0, period - (time.monotonic() - started))) # keep a steady cadence
Choosing between the two sources:
| Socket mode | Request mode | |
|---|---|---|
| Latency | lowest — the server pushes | one polling period |
| Load | one connection | one request per period |
| Complexity | reconnects and watchdog needed | trivial loop |
| Failure behaviour | ends silently — must be detected | explicit exception — easy to handle |
| Best for | fast reactions, many instruments, market-making style logic | slow signals, periodic rebalancing, confirmation before acting |
The two combine well: react on the socket, confirm over REST (8.14). For example, wrap the executor so that every decision is re-checked on a fresh REST snapshot just before the order is built:
class ConfirmingExecutor(Executor):
def __init__(self, ime, rules, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ime, self.rules = ime, rules
async def fire(self, q: Quote, d: Decision) -> None:
fresh_quote, decision = None, None
try:
blob = (await self.ime.live_overview_by_name([q.name]))["Data"][q.name]
rule = next((r for r in self.rules if r.name == d.reason), None)
if blob is not None and rule is not None:
fresh_quote = to_quote(q.name, blob, "rest")
decision = rule.evaluate(fresh_quote) # re-check the SAME rule on fresh data
except Exception as error:
self.log(f"[{q.name}] confirmation failed: {error!r}")
if decision is None:
self.log(f"[{q.name}] '{d.reason}' not confirmed on fresh data — skipped")
self.guard.release(q.name)
return
await super().fire(fresh_quote, decision) # releases the guard in its `finally`
Part C — The same pipeline on TSE-IFB: merging channels
TSE-IFB messages carry one channel each, so stage 2 merges the channels into a single Quote. The daily price band comes from static info, fetched once at start-up.
import asyncio
import time
from typing import Optional
from kit import *
from rules import rules # rules whose prices fit these symbols
from streaming import stream_forever
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient
from HedgeTech.EMS.TseIfb import EmsEngine_TseIfb_AsyncClient
class TseBook:
"""Merges 'best-limit' and 'aggregate' messages into one Quote per symbol."""
def __init__(self, bands: dict[str, tuple[float, float]]):
self.bands = bands # symbolName -> (minAllowedPrice, maxAllowedPrice)
self.best: dict[str, dict] = {}
self.last: dict[str, float] = {}
def apply(self, update: dict) -> Optional[Quote]:
name = update["symbolName"]
if update["channel"] == "best-limit":
self.best[name] = update["data"]["1"]
elif update["channel"] == "aggregate":
self.last[name] = float(update["data"]["last_price"])
level = self.best.get(name)
if level is None or name not in self.bands:
return None # not enough information yet
low, high = self.bands[name]
return Quote(
name=name,
bid=int(level["buy_price"]), bid_qty=int(level["buy_quantity"]),
ask=int(level["sell_price"]), ask_qty=int(level["sell_quantity"]),
last=self.last.get(name, 0.0),
min_price=low, max_price=high,
source="ws", received_at=time.monotonic(),
)
async def main():
auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
tse = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)
ems = EmsEngine_TseIfb_AsyncClient(AuthASyncClient=auth)
(await ems.Get_Captcha("Omex | Parsian")).show()
await ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))
symbols = ["فملی", "خودرو"]
# Daily price band from static info (stage 2 needs it for the guard)
info = await tse.instruments_static_info_by_name(symbols)
bands = {i["symbolName"]: (i["minAllowedPrice"], i["maxAllowedPrice"]) for i in info["Data"] if i}
book = TseBook(bands)
guard = RiskGuard(max_volume=1000, max_position=5000, cooldown_s=15.0, max_orders=30)
executor = Executor(tse_builder(ems), guard, ttl_s=45.0)
shutdown = asyncio.Event()
await run_socket_mode(
open_stream=lambda run: tse.websocket_by_name(
channels=["best-limit", "aggregate"], symbol_names=symbols, event=run
),
normalize=book.apply,
rules=rules,
executor=executor,
guard=guard,
shutdown=shutdown,
)
TSE-IFB orders take
Order_ValidityTypeandValidityDate; the builder above uses the default'DAY'. Extendtse_builderif you need GTC/GTD.
Part D — The same flow with the synchronous clients
Sync clients are blocking, so the simplest professional shape is a single loop: request → conditions → execute → follow.
import time
from HedgeTech.Auth import AuthSyncClient
from HedgeTech.Data.IME import DataEngine_Ime_SyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_SyncClient
from kit import to_quote, FINAL
from rules import rules
auth = AuthSyncClient.login(UserName_or_Email="user@example.com", Password="…")
ime = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
ems = EmsEngine_Ime_SyncClient(AuthSyncClient=auth)
ems.Get_Captcha("Sahra | Karamad").show()
ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))
names = ["KASH05C170"]
open_order = None
while True:
started = time.monotonic()
try:
overview = ime.live_overview_by_name(names)
except Exception as error:
print("request failed:", repr(error))
time.sleep(1)
continue
if open_order is not None: # follow the working order first
status = open_order.Status()
if status is not None and status["order_status"] in FINAL:
print("final:", status)
open_order = None
# (add a deadline and open_order.Delete() as in Executor.supervise)
elif overview["Data"][names[0]] is not None:
quote = to_quote(names[0], overview["Data"][names[0]], "rest")
for rule in rules:
decision = rule.evaluate(quote)
if decision is None:
continue
method = ems.Buy_by_ContractName if decision.side == "BUY" else ems.Sell_by_ContractName
order = method(contractName=quote.name, Price=decision.price, Volume=decision.volume)
if order is not None:
order.send()
if order.OrderId is not None: # send() never raises
open_order = order
break
time.sleep(max(0.0, 1.0 - (time.monotonic() - started)))
The sync loop above omits the risk guard to stay short. Add the same checks (price band, cooldown, volume cap) before
method(...)in a real bot.
Part E — Dry run, audit trail and going live
Dry run first. Replace the builder with one that only logs. Every other stage runs unchanged, so you can watch the decisions your conditions would make on live data without touching the exchange:
class _FakeOrder:
OrderId = "dry-run"
OrderStatus = "Settled"
async def send(self): pass
async def Status(self): return {"order_status": "Settled", "ExecutedVolume": 0, "RemainedVolume": 0}
async def Delete(self): pass
def dry_run_builder() -> Builder:
async def build(side, name, price, volume):
print(f"DRY-RUN {side} {volume} {name} @ {price}")
return _FakeOrder()
return build
executor = Executor(dry_run_builder(), guard)
Audit trail. Log one JSON line per decision with the quote, the rule and the guard's verdict. When something unexpected happens, you can replay exactly what the bot saw:
import json, time
def audit(q: Quote, d: Decision, allowed: bool, why: str, path: str = "decisions.jsonl"):
with open(path, "a", encoding="utf-8") as file:
file.write(json.dumps({
"ts": time.time(), "contract": q.name, "rule": d.reason, "side": d.side,
"price": d.price, "volume": d.volume, "allowed": allowed, "why": why,
"bid": q.bid, "ask": q.ask, "bid_qty": q.bid_qty, "ask_qty": q.ask_qty,
"last": q.last, "source": q.source,
}, ensure_ascii=False) + "\n")
Go-live sequence
- Dry run on live data for several sessions; read the audit log.
- Smallest real size (
volume=1), a tightmax_orders, shortttl_s. - Watch the first orders end to end:
OrderId,Status(), fills, cancellations. - Scale up gradually, keeping the guard limits conservative.
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. - Single order in flight per contract and a net position limit (the
RiskGuardin the pipeline). - Dry-run executor first, then audit every decision to a JSON-lines log.
- Stale-data protection (
fresh(...)condition + stream watchdog). - 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