Stream API¶
watcher
¶
Async market-wide polling streamer with state-transition events.
EventCallback
module-attribute
¶
__all__
module-attribute
¶
__all__ = [
"BUY_QUEUE_BROKEN",
"BUY_QUEUE_LOCKED",
"MarketEvent",
"MarketWatcher",
"SELL_QUEUE_BROKEN",
"SELL_QUEUE_LOCKED",
"VOLUME_SPIKE",
"is_market_open",
]
AsyncHTTPClient
¶
AsyncHTTPClient(
*,
timeout: float = DEFAULT_TIMEOUT,
max_concurrency: int = MAX_CONCURRENCY,
max_retries: int = MAX_RETRIES,
retry_wait: float = RETRY_WAIT,
headers: Mapping[str, str] | None = None,
proxy: str | None = None,
trust_env: bool | None = None,
config: IranQuantConfig | None = None,
)
Small retrying wrapper around :class:httpx.AsyncClient.
Requests use a verified transport when config.verify_ssl is true. A
certificate failure is retried once over an unverified transport only when
config.allow_tls_fallback is true; the first fallback emits a
UserWarning and a log record. With fallback disabled, the failure raises
:class:~iranquant.exceptions.IranQuantConnectionError without retrying.
Environment proxy variables are ignored by default (trust_env=False) to
avoid corporate/VPN HTTP proxies breaking direct connections to domestic
Iranian hosts. Pass proxy=... to opt into an explicit proxy.
Create the pooled HTTP transports.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Per-request timeout in seconds. Defaults to
:data: |
DEFAULT_TIMEOUT
|
max_concurrency
|
int
|
Maximum number of simultaneous requests enforced
by an internal :class: |
MAX_CONCURRENCY
|
max_retries
|
int
|
Total attempts per request. Defaults to
:data: |
MAX_RETRIES
|
retry_wait
|
float
|
Base wait used by the exponential retry backoff, in
seconds. Defaults to :data: |
RETRY_WAIT
|
headers
|
Mapping[str, str] | None
|
Extra headers merged over the built-in TSETMC/Codal headers. |
None
|
proxy
|
str | None
|
Optional explicit proxy URL, e.g.
|
None
|
trust_env
|
bool | None
|
Whether to honour |
None
|
config
|
IranQuantConfig | None
|
TLS policy. Defaults to :class: |
None
|
Examples:
>>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
>>> client.trust_env
False
>>> client = AsyncHTTPClient(
... config=IranQuantConfig(allow_tls_fallback=False)
... )
Source code in src/iranquant/core/client.py
get
async
¶
get(
url: str,
*,
params: Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
raw: bool = False,
) -> httpx.Response
Perform a GET request with retries and TLS fallback.
The request is retried up to max_retries times on network errors,
and responses with status codes >= 500 are treated as retryable.
Certificate failures use the unverified fallback transport once when
allow_tls_fallback is true; the first fallback emits a
UserWarning. With fallback disabled, the request fails immediately
with :class:~iranquant.exceptions.IranQuantConnectionError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute request URL. |
required |
params
|
Mapping[str, Any] | None
|
Optional query parameters. Ignored for URL encoding when
|
None
|
headers
|
Mapping[str, str] | None
|
Optional per-request headers merged over the defaults. |
None
|
raw
|
bool
|
When true the URL string is sent verbatim without
percent-encoding. Required for the MarketWatch endpoint, whose
|
False
|
Returns:
| Type | Description |
|---|---|
Response
|
The successful :class: |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the host is unreachable, a non-2xx status is returned, or all retries are exhausted. |
IranQuantConnectionError
|
If TLS verification fails and
|
Examples:
>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
get_json
async
¶
get_json(
url: str,
*,
params: Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
raw: bool = False,
) -> Any
GET a URL and decode its JSON body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute request URL. |
required |
params
|
Mapping[str, Any] | None
|
Optional query parameters. |
None
|
headers
|
Mapping[str, str] | None
|
Optional per-request headers. |
None
|
raw
|
bool
|
When true, send the URL untouched (see :meth: |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The decoded JSON value (usually a |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the request fails after retries. |
ParseError
|
If the response body is not valid JSON. |
Examples:
>>> payload = await client.get_json(
... "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
... )
>>> "instrumentSearch" in payload
True
Source code in src/iranquant/core/client.py
aclose
async
¶
Close the primary and fallback HTTP transports.
Safe to call more than once. After closing, the instance must not be used again.
Examples:
Source code in src/iranquant/core/client.py
__aenter__
async
¶
__aexit__
async
¶
IranQuantError
¶
Bases: Exception
Base class for every exception raised by iranquant.
Catching this single type covers every library-specific failure while still allowing narrower handlers for specific cases.
Examples:
MarketEvent
dataclass
¶
MarketEvent(
event_type: str,
ins_code: str,
symbol: str,
timestamp: datetime,
data: dict[str, Any] = dict(),
)
A structured market state-change event.
Attributes:
| Name | Type | Description |
|---|---|---|
event_type |
str
|
One of |
ins_code |
str
|
TSETMC instrument code (empty when the snapshot lacks it). |
symbol |
str
|
Persian ticker from MarketWatch. |
timestamp |
datetime
|
When the event was detected (UTC unless supplied). |
data |
dict[str, Any]
|
Event-specific payload. Queue events include |
Examples:
>>> event = MarketEvent(
... event_type=BUY_QUEUE_LOCKED,
... ins_code="46348559193224090",
... symbol="فولاد",
... timestamp=dt.datetime.now(dt.timezone.utc),
... data={"close": 4150.0, "tmax": 4150.0},
... )
>>> event.symbol
'فولاد'
_SymbolState
dataclass
¶
_SymbolState(
buy_locked: bool = False,
sell_locked: bool = False,
last_volume: float | None = None,
avg_delta: float = 0.0,
delta_count: int = 0,
last_close: float = 0.0,
)
MarketWatcher
¶
Poll MarketWatch and emit queue/volume transitions.
process_snapshot is synchronous and stateful so it can also be used in
backtests or tests without any network access. The state machine emits:
BUY_QUEUE_LOCKED/BUY_QUEUE_BROKENwhenclose >= tmaxwith a positive buy queue starts or stops.SELL_QUEUE_LOCKED/SELL_QUEUE_BROKENwhenclose <= tminwith a positive sell queue starts or stops.VOLUME_SPIKEwhen the per-poll volume increase is at least1.8xthe running average increase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Examples:
>>> watcher = MarketWatcher()
>>> @watcher.on_event(BUY_QUEUE_LOCKED)
... def on_lock(event: MarketEvent) -> None:
... print(event.symbol, event.data["buy_queue_volume"])
>>> async for event in watcher.watch(interval=5.0, symbols=["فولاد"]):
... print(event.event_type)
Source code in src/iranquant/stream/watcher.py
on_event
¶
Register a sync or async callback for an event type ("*" = all).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
str
|
A specific event constant or |
required |
Returns:
| Type | Description |
|---|---|
Callable[[EventCallback], EventCallback]
|
A decorator that registers the callback and returns it unchanged, |
Callable[[EventCallback], EventCallback]
|
so the method can be used as |
Examples:
>>> @watcher.on_event("*")
... async def log(event: MarketEvent) -> None:
... print(event.event_type, event.symbol)
Source code in src/iranquant/stream/watcher.py
dispatch
async
¶
Invoke every matching listener for each event.
Sync callbacks are called directly; awaitable results are awaited.
Listeners registered for "*" run after type-specific listeners.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
Iterable[MarketEvent]
|
Events to deliver, typically returned by
:meth: |
required |
Examples:
Source code in src/iranquant/stream/watcher.py
reset
¶
Forget all per-symbol state so the next snapshot starts fresh.
Does not remove registered listeners.
process_snapshot
¶
process_snapshot(
snapshot: DataFrame,
*,
timestamp: datetime | None = None,
symbols: list[str] | None = None,
) -> list[MarketEvent]
Update internal state from a MarketWatch frame and return events.
No I/O is performed; the result is deterministic for a given snapshot sequence, so this is safe to use in backtests and unit tests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshot
|
DataFrame
|
A MarketWatch frame (from
:func: |
required |
timestamp
|
datetime | None
|
Timestamp attached to emitted events. Defaults to the current UTC time. |
None
|
symbols
|
list[str] | None
|
Optional allow-list. Numeric strings are matched against
|
None
|
Returns:
| Type | Description |
|---|---|
list[MarketEvent]
|
The newly triggered events in snapshot order. An empty frame |
list[MarketEvent]
|
returns an empty list without mutating state. |
Examples:
>>> events = watcher.process_snapshot(iq.market_watch())
>>> [event.event_type for event in events]
['BUY_QUEUE_LOCKED']
Source code in src/iranquant/stream/watcher.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
watch
async
¶
watch(
interval: float = 5.0,
symbols: list[str] | None = None,
only_market_hours: bool = False,
) -> AsyncGenerator[MarketEvent, None]
Poll MarketWatch forever, yielding state-change events.
Each iteration fetches a full market snapshot, updates the state machine, dispatches callbacks, yields every new event, then sleeps. IranQuant errors during a poll are swallowed and retried on the next interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Seconds between full MarketWatch polls. Must be positive.
Defaults to |
5.0
|
symbols
|
list[str] | None
|
Optional allow-list passed to :meth: |
None
|
only_market_hours
|
bool
|
When |
False
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[MarketEvent, None]
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> async for event in watcher.watch(interval=3.0, symbols=["فولاد"]):
... print(event.event_type, event.symbol)
Source code in src/iranquant/stream/watcher.py
__aenter__
async
¶
Enter the async context manager, creating a client if needed.
Returns:
| Type | Description |
|---|---|
MarketWatcher
|
|
Source code in src/iranquant/stream/watcher.py
__aexit__
async
¶
Close the owned HTTP client when leaving the context manager.
Source code in src/iranquant/stream/watcher.py
normalize_persian
¶
Normalize Persian/Arabic text for reliable comparison.
Converts Arabic yeh/kaf/teh-marbuta to their Persian equivalents, converts Arabic-Indic and Persian digits to ASCII digits, removes zero-width and directional control characters, and collapses whitespace.
This is what makes "فولاد" written with an Arabic yeh and the same
symbol written with a Persian yeh resolve to the same TSETMC instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Any string, including Persian, Arabic-Indic or mixed text. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The normalized string with single spaces and ASCII digits. |
Examples:
Source code in src/iranquant/core/normalizer.py
get_market_watch
async
¶
Fetch the entire market snapshot in a single request.
The request is sent verbatim (raw=True) so the bracketed
paperTypes[0]=1 query is never percent-encoded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per symbol with the following columns: |
DataFrame
|
================= ========================== ======================= |
DataFrame
|
Column Type Description |
DataFrame
|
================= ========================== ======================= |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
================= ========================== ======================= |
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the MarketWatch endpoint cannot be reached. |
ParseError
|
If the response body is not valid JSON. |
ValidationError
|
If the payload does not match the schema. |
Examples:
>>> market = await get_market_watch(client)
>>> market[["symbol", "close", "tmax"]].head()
>>> book = market.iloc[0]["order_book"]
>>> book[0]["zmd"] # best bid volume
Source code in src/iranquant/market/live.py
to_pandas
¶
Source code in src/iranquant/quant/_utils.py
_to_float
¶
_book_volume
¶
Source code in src/iranquant/stream/watcher.py
_tehran_timezone
¶
is_market_open
¶
Return True during Saturday-Wednesday TSETMC sessions (09:00-12:30 IRST).
Python weekday numbering is Monday=0, so the active days are 5, 6, 0, 1
and 2. The time is interpreted in Asia/Tehran (with a fixed +03:30
fallback when tzdata is unavailable).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
now
|
datetime | None
|
Optional aware or naive datetime. Naive values are assumed to be Tehran local time. Defaults to the current instant. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
local time is between 09:00 and 12:30 inclusive, otherwise |
Examples:
>>> import datetime as dt
>>> is_market_open(dt.datetime(2026, 10, 31, 10, 0)) # Saturday
True
>>> is_market_open(dt.datetime(2026, 10, 30, 13, 0)) # Friday
False