Skip to content

Stream API

watcher

Async market-wide polling streamer with state-transition events.

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

BUY_QUEUE_LOCKED module-attribute

BUY_QUEUE_LOCKED = 'BUY_QUEUE_LOCKED'

BUY_QUEUE_BROKEN module-attribute

BUY_QUEUE_BROKEN = 'BUY_QUEUE_BROKEN'

SELL_QUEUE_LOCKED module-attribute

SELL_QUEUE_LOCKED = 'SELL_QUEUE_LOCKED'

SELL_QUEUE_BROKEN module-attribute

SELL_QUEUE_BROKEN = 'SELL_QUEUE_BROKEN'

VOLUME_SPIKE module-attribute

VOLUME_SPIKE = 'VOLUME_SPIKE'

EventCallback module-attribute

EventCallback = Callable[
    ["MarketEvent"], Awaitable[None] | None
]

__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:iranquant.config.DEFAULT_TIMEOUT (30 s).

DEFAULT_TIMEOUT
max_concurrency int

Maximum number of simultaneous requests enforced by an internal :class:asyncio.Semaphore. Defaults to :data:iranquant.config.MAX_CONCURRENCY (10).

MAX_CONCURRENCY
max_retries int

Total attempts per request. Defaults to :data:iranquant.config.MAX_RETRIES (3).

MAX_RETRIES
retry_wait float

Base wait used by the exponential retry backoff, in seconds. Defaults to :data:iranquant.config.RETRY_WAIT (0.5).

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. "http://127.0.0.1:9090". When omitted, environment proxy variables are ignored.

None
trust_env bool | None

Whether to honour HTTP_PROXY / HTTPS_PROXY and other environment settings. Defaults to True only when an explicit proxy is supplied, otherwise False.

None
config IranQuantConfig | None

TLS policy. Defaults to :class:IranQuantConfig, which reads IRANQUANT_VERIFY_SSL and IRANQUANT_ALLOW_TLS_FALLBACK.

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
def __init__(
    self,
    *,
    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,
) -> None:
    """Create the pooled HTTP transports.

    Args:
        timeout: Per-request timeout in seconds.  Defaults to
            :data:`iranquant.config.DEFAULT_TIMEOUT` (30 s).
        max_concurrency: Maximum number of simultaneous requests enforced
            by an internal :class:`asyncio.Semaphore`.  Defaults to
            :data:`iranquant.config.MAX_CONCURRENCY` (10).
        max_retries: Total attempts per request.  Defaults to
            :data:`iranquant.config.MAX_RETRIES` (3).
        retry_wait: Base wait used by the exponential retry backoff, in
            seconds.  Defaults to :data:`iranquant.config.RETRY_WAIT` (0.5).
        headers: Extra headers merged over the built-in TSETMC/Codal
            headers.
        proxy: Optional explicit proxy URL, e.g.
            ``"http://127.0.0.1:9090"``.  When omitted, environment proxy
            variables are ignored.
        trust_env: Whether to honour ``HTTP_PROXY`` / ``HTTPS_PROXY`` and
            other environment settings.  Defaults to ``True`` only when an
            explicit ``proxy`` is supplied, otherwise ``False``.
        config: TLS policy. Defaults to :class:`IranQuantConfig`, which
            reads ``IRANQUANT_VERIFY_SSL`` and
            ``IRANQUANT_ALLOW_TLS_FALLBACK``.

    Examples:
        >>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
        >>> client.trust_env
        False
        >>> client = AsyncHTTPClient(
        ...     config=IranQuantConfig(allow_tls_fallback=False)
        ... )
    """
    self._semaphore = asyncio.Semaphore(max_concurrency)
    self._max_retries = max_retries
    self._retry_wait = retry_wait
    self._headers = dict(headers or {})
    self.config = config or IranQuantConfig()
    self.proxy = proxy
    # Explicit proxies imply honouring the environment unless overridden.
    self.trust_env = (proxy is not None) if trust_env is None else trust_env
    self._tls_fallback_warned = False

    common: dict[str, Any] = {
        "timeout": timeout,
        "follow_redirects": True,
        "trust_env": self.trust_env,
        "http2": False,
    }
    if proxy is not None:
        common["proxy"] = proxy

    self._client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=self.config.verify_ssl,
        **common,
    )
    self._fallback_client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=False,
        **common,
    )

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 raw is true.

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 paperTypes[0]=1 brackets must stay literal.

False

Returns:

Type Description
Response

The successful :class:httpx.Response.

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 allow_tls_fallback is false.

Examples:

>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
async def get(
    self,
    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`.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.  Ignored for URL encoding when
            ``raw`` is true.
        headers: Optional per-request headers merged over the defaults.
        raw: When true the URL string is sent verbatim without
            percent-encoding.  Required for the MarketWatch endpoint, whose
            ``paperTypes[0]=1`` brackets must stay literal.

    Returns:
        The successful :class:`httpx.Response`.

    Raises:
        NetworkError: If the host is unreachable, a non-2xx status is
            returned, or all retries are exhausted.
        IranQuantConnectionError: If TLS verification fails and
            ``allow_tls_fallback`` is false.

    Examples:
        >>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
        >>> response.status_code
        200
    """

    target = self._build_url(url, params, raw=raw)

    try:
        async for attempt in self._retrying():
            with attempt:
                response = await self._send_with_fallback(target, headers)
                if response.status_code >= 500:
                    raise NetworkError(f"Server error {response.status_code} for {target}")
                response.raise_for_status()
                return response
    except httpx.HTTPStatusError as exc:
        raise NetworkError(f"HTTP {exc.response.status_code} for {exc.request.url}") from exc
    except httpx.HTTPError as exc:
        raise NetworkError(f"Request failed for {target}: {exc}") from exc

    raise NetworkError(f"Request failed after retries: {target}")

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:get).

False

Returns:

Type Description
Any

The decoded JSON value (usually a dict or list).

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
async def get_json(
    self,
    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.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.
        headers: Optional per-request headers.
        raw: When true, send the URL untouched (see :meth:`get`).

    Returns:
        The decoded JSON value (usually a ``dict`` or ``list``).

    Raises:
        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
    """

    response = await self.get(url, params=params, headers=headers, raw=raw)
    try:
        return response.json()
    except ValueError as exc:
        raise ParseError(f"Invalid JSON from {response.request.url}") from exc

aclose async

aclose() -> None

Close the primary and fallback HTTP transports.

Safe to call more than once. After closing, the instance must not be used again.

Examples:

>>> client = AsyncHTTPClient()
>>> await client.aclose()
Source code in src/iranquant/core/client.py
async def aclose(self) -> None:
    """Close the primary and fallback HTTP transports.

    Safe to call more than once.  After closing, the instance must not be
    used again.

    Examples:
        >>> client = AsyncHTTPClient()
        >>> await client.aclose()
    """
    await self._client.aclose()
    await self._fallback_client.aclose()

__aenter__ async

__aenter__() -> AsyncHTTPClient

Enter the async context manager and return self.

Source code in src/iranquant/core/client.py
async def __aenter__(self) -> AsyncHTTPClient:
    """Enter the async context manager and return ``self``."""
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close all transports when leaving the async context manager.

Source code in src/iranquant/core/client.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close all transports when leaving the async context manager."""
    await self.aclose()

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:

>>> try:
...     iq.history("نماد_ناموجود")
... except iq.IranQuantError as exc:
...     print(type(exc).__name__)
SymbolNotFoundError

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 BUY_QUEUE_LOCKED, BUY_QUEUE_BROKEN, SELL_QUEUE_LOCKED, SELL_QUEUE_BROKEN or VOLUME_SPIKE.

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 close, tmax, tmin, buy_queue_volume, sell_queue_volume and volume; VOLUME_SPIKE includes volume, delta, avg_delta and close.

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

MarketWatcher(client: AsyncHTTPClient | None = None)

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_BROKEN when close >= tmax with a positive buy queue starts or stops.
  • SELL_QUEUE_LOCKED / SELL_QUEUE_BROKEN when close <= tmin with a positive sell queue starts or stops.
  • VOLUME_SPIKE when the per-poll volume increase is at least 1.8x the running average increase.

Parameters:

Name Type Description Default
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient. When omitted, :meth:watch creates and owns a client itself, or :meth:__aenter__ creates one for the context manager.

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
def __init__(self, client: AsyncHTTPClient | None = None) -> None:
    self._client = client
    self._owns_client = False
    self._states: dict[str, _SymbolState] = {}
    self._listeners: dict[str, list[EventCallback]] = {}

on_event

on_event(
    event_type: str,
) -> Callable[[EventCallback], EventCallback]

Register a sync or async callback for an event type ("*" = all).

Parameters:

Name Type Description Default
event_type str

A specific event constant or "*" to receive every event.

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 @watcher.on_event(...).

Examples:

>>> @watcher.on_event("*")
... async def log(event: MarketEvent) -> None:
...     print(event.event_type, event.symbol)
Source code in src/iranquant/stream/watcher.py
def on_event(
    self,
    event_type: str,
) -> Callable[[EventCallback], EventCallback]:
    """Register a sync or async callback for an event type (``"*"`` = all).

    Args:
        event_type: A specific event constant or ``"*"`` to receive every
            event.

    Returns:
        A decorator that registers the callback and returns it unchanged,
        so the method can be used as ``@watcher.on_event(...)``.

    Examples:
        >>> @watcher.on_event("*")
        ... async def log(event: MarketEvent) -> None:
        ...     print(event.event_type, event.symbol)
    """

    def decorator(callback: EventCallback) -> EventCallback:
        self._listeners.setdefault(event_type, []).append(callback)
        return callback

    return decorator

dispatch async

dispatch(events: Iterable[MarketEvent]) -> None

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:process_snapshot.

required

Examples:

>>> await watcher.dispatch(watcher.process_snapshot(snapshot))
Source code in src/iranquant/stream/watcher.py
async def dispatch(self, events: Iterable[MarketEvent]) -> None:
    """Invoke every matching listener for each event.

    Sync callbacks are called directly; awaitable results are awaited.
    Listeners registered for ``"*"`` run after type-specific listeners.

    Args:
        events: Events to deliver, typically returned by
            :meth:`process_snapshot`.

    Examples:
        >>> await watcher.dispatch(watcher.process_snapshot(snapshot))
    """
    for event in events:
        callbacks = [
            *self._listeners.get(event.event_type, []),
            *self._listeners.get("*", []),
        ]
        for callback in callbacks:
            result = callback(event)
            if inspect.isawaitable(result):
                await cast(Awaitable[Any], result)

reset

reset() -> None

Forget all per-symbol state so the next snapshot starts fresh.

Does not remove registered listeners.

Source code in src/iranquant/stream/watcher.py
def reset(self) -> None:
    """Forget all per-symbol state so the next snapshot starts fresh.

    Does not remove registered listeners.
    """
    self._states.clear()

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:iranquant.market_watch) with at least close, tmax, tmin and volume. ins_code, symbol and order_book are used when present.

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 ins_code; other strings are normalized and matched against symbol.

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
def process_snapshot(
    self,
    snapshot: DataFrame,
    *,
    timestamp: dt.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.

    Args:
        snapshot: A MarketWatch frame (from
            :func:`iranquant.market_watch`) with at least ``close``,
            ``tmax``, ``tmin`` and ``volume``.  ``ins_code``, ``symbol``
            and ``order_book`` are used when present.
        timestamp: Timestamp attached to emitted events.  Defaults to the
            current UTC time.
        symbols: Optional allow-list.  Numeric strings are matched against
            ``ins_code``; other strings are normalized and matched against
            ``symbol``.

    Returns:
        The newly triggered events in snapshot order.  An empty frame
        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']
    """

    frame = to_pandas(snapshot)
    if frame.empty:
        return []

    wanted_codes = {str(symbol) for symbol in symbols or [] if str(symbol).isdigit()}
    wanted_symbols = {
        normalize_persian(symbol) for symbol in symbols or [] if not str(symbol).isdigit()
    }
    moment = timestamp or dt.datetime.now(dt.timezone.utc)

    events: list[MarketEvent] = []
    for _, row in frame.iterrows():
        ins_code = str(row.get("ins_code", "") or "")
        symbol = str(row.get("symbol", "") or "")
        if symbols is not None:
            matches = ins_code in wanted_codes or normalize_persian(symbol) in wanted_symbols
            if not matches:
                continue

        key = ins_code or symbol
        if not key:
            continue

        close = _to_float(row.get("close"))
        tmax = _to_float(row.get("tmax"))
        tmin = _to_float(row.get("tmin"))
        volume = _to_float(row.get("volume"))
        buy_volume = _book_volume(row.get("order_book"), "buy")
        sell_volume = _book_volume(row.get("order_book"), "sell")

        buy_locked = tmax > 0 and close >= tmax and buy_volume > 0
        sell_locked = tmin > 0 and close <= tmin and sell_volume > 0

        state = self._states.get(key)
        is_new = state is None
        if state is None:
            state = _SymbolState()
            self._states[key] = state

        base_data: dict[str, Any] = {
            "close": close,
            "tmax": tmax,
            "tmin": tmin,
            "buy_queue_volume": buy_volume,
            "sell_queue_volume": sell_volume,
            "volume": volume,
        }

        if buy_locked and not state.buy_locked:
            events.append(
                MarketEvent(BUY_QUEUE_LOCKED, ins_code, symbol, moment, dict(base_data))
            )
        elif state.buy_locked and not buy_locked:
            events.append(
                MarketEvent(BUY_QUEUE_BROKEN, ins_code, symbol, moment, dict(base_data))
            )

        if sell_locked and not state.sell_locked:
            events.append(
                MarketEvent(SELL_QUEUE_LOCKED, ins_code, symbol, moment, dict(base_data))
            )
        elif state.sell_locked and not sell_locked:
            events.append(
                MarketEvent(SELL_QUEUE_BROKEN, ins_code, symbol, moment, dict(base_data))
            )

        if not is_new and state.last_volume is not None:
            delta = volume - state.last_volume
            if delta < 0:
                # A new trading day/reset: restart the spike baseline.
                state.avg_delta = 0.0
                state.delta_count = 0
            elif delta > 0:
                previous_average = state.avg_delta
                if state.delta_count > 0 and delta >= 1.8 * previous_average:
                    events.append(
                        MarketEvent(
                            VOLUME_SPIKE,
                            ins_code,
                            symbol,
                            moment,
                            {
                                "volume": volume,
                                "delta": delta,
                                "avg_delta": previous_average,
                                "close": close,
                            },
                        )
                    )
                state.delta_count += 1
                state.avg_delta = (
                    (previous_average * (state.delta_count - 1)) + delta
                ) / state.delta_count

        state.buy_locked = buy_locked
        state.sell_locked = sell_locked
        state.last_volume = volume
        state.last_close = close

    return events

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.

5.0
symbols list[str] | None

Optional allow-list passed to :meth:process_snapshot.

None
only_market_hours bool

When True, skip polling outside Saturday-Wednesday 09:00-12:30 Tehran time. Defaults to False.

False

Yields:

Type Description
AsyncGenerator[MarketEvent, None]

class:MarketEvent objects as state transitions occur.

Raises:

Type Description
ValueError

If interval <= 0.

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
async def watch(
    self,
    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.

    Args:
        interval: Seconds between full MarketWatch polls.  Must be positive.
            Defaults to ``5.0``.
        symbols: Optional allow-list passed to :meth:`process_snapshot`.
        only_market_hours: When ``True``, skip polling outside
            Saturday-Wednesday 09:00-12:30 Tehran time.  Defaults to
            ``False``.

    Yields:
        :class:`MarketEvent` objects as state transitions occur.

    Raises:
        ValueError: If ``interval <= 0``.

    Examples:
        >>> async for event in watcher.watch(interval=3.0, symbols=["فولاد"]):
        ...     print(event.event_type, event.symbol)
    """

    if interval <= 0:
        raise ValueError("interval must be positive")

    owns_client = self._client is None
    if self._client is None:
        self._client = AsyncHTTPClient()
    client = self._client

    try:
        while True:
            if only_market_hours and not is_market_open():
                await asyncio.sleep(interval)
                continue
            try:
                snapshot = await get_market_watch(client)
            except IranQuantError:
                await asyncio.sleep(interval)
                continue

            events = self.process_snapshot(snapshot, symbols=symbols)
            await self.dispatch(events)
            for event in events:
                yield event
            await asyncio.sleep(interval)
    finally:
        if owns_client:
            await client.aclose()
            self._client = None

__aenter__ async

__aenter__() -> MarketWatcher

Enter the async context manager, creating a client if needed.

Returns:

Type Description
MarketWatcher

self so the watcher can be used with async with.

Source code in src/iranquant/stream/watcher.py
async def __aenter__(self) -> MarketWatcher:
    """Enter the async context manager, creating a client if needed.

    Returns:
        ``self`` so the watcher can be used with ``async with``.
    """
    if self._client is None:
        self._client = AsyncHTTPClient()
        self._owns_client = True
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close the owned HTTP client when leaving the context manager.

Source code in src/iranquant/stream/watcher.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close the owned HTTP client when leaving the context manager."""
    if self._owns_client and self._client is not None:
        await self._client.aclose()
        self._client = None
        self._owns_client = False

normalize_persian

normalize_persian(text: str) -> str

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:

>>> normalize_persian("۱۲۳")
'123'
>>> normalize_persian("  علي  ")
'علی'
Source code in src/iranquant/core/normalizer.py
def normalize_persian(text: str) -> str:
    """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.

    Args:
        text: Any string, including Persian, Arabic-Indic or mixed text.

    Returns:
        The normalized string with single spaces and ASCII digits.

    Examples:
        >>> normalize_persian("۱۲۳")
        '123'
        >>> normalize_persian("  علي  ")
        'علی'
    """

    translated = text.translate(_CHAR_MAP).translate(_ZERO_WIDTH)
    return " ".join(translated.split())

get_market_watch async

get_market_watch(
    client: AsyncHTTPClient, *, engine: Engine = "pandas"
) -> DataFrame

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:~iranquant.core.client.AsyncHTTPClient.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per symbol with the following columns:

DataFrame

================= ========================== =======================

DataFrame

Column Type Description

DataFrame

================= ========================== =======================

DataFrame

ins_code str TSETMC instrument code.

DataFrame

symbol str Ticker (lva).

DataFrame

company_name str Company name (lvc).

DataFrame

eps float | None Earnings per share.

DataFrame

pe float | None Price-to-earnings ratio.

DataFrame

open float Opening price (pf).

DataFrame

high float Daily high (pmx).

DataFrame

low float Daily low (pmn).

DataFrame

close float Last trade (pdv).

DataFrame

final_price float Closing price (pcl).

DataFrame

prev_price float Previous close (py).

DataFrame

volume float Volume (qtj/qtt).

DataFrame

value float Value in Rials (qtc).

DataFrame

trades float Trade count (ztt).

DataFrame

tmax float High limit (pMax/ps).

DataFrame

tmin float Low limit (pMin/pi).

DataFrame

total_shares float Listed shares (ztd).

DataFrame

order_book list[dict[str, float]] Best-limit levels.

DataFrame

================= ========================== =======================

DataFrame

order_book dictionaries expose n, qmd, zmd, pmd,

DataFrame

pmo, zmo and qmo for levels 1..5, sorted by n.

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
async def get_market_watch(
    client: AsyncHTTPClient,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """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.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        One row per symbol with the following columns:

        =================  ==========================  =======================
        Column             Type                        Description
        =================  ==========================  =======================
        ``ins_code``       ``str``                     TSETMC instrument code.
        ``symbol``         ``str``                     Ticker (``lva``).
        ``company_name``   ``str``                     Company name (``lvc``).
        ``eps``            ``float | None``            Earnings per share.
        ``pe``             ``float | None``            Price-to-earnings ratio.
        ``open``           ``float``                   Opening price (``pf``).
        ``high``           ``float``                   Daily high (``pmx``).
        ``low``            ``float``                   Daily low (``pmn``).
        ``close``          ``float``                   Last trade (``pdv``).
        ``final_price``    ``float``                   Closing price (``pcl``).
        ``prev_price``     ``float``                   Previous close (``py``).
        ``volume``         ``float``                   Volume (``qtj``/``qtt``).
        ``value``          ``float``                   Value in Rials (``qtc``).
        ``trades``         ``float``                   Trade count (``ztt``).
        ``tmax``           ``float``                   High limit (``pMax``/``ps``).
        ``tmin``           ``float``                   Low limit (``pMin``/``pi``).
        ``total_shares``   ``float``                   Listed shares (``ztd``).
        ``order_book``     ``list[dict[str, float]]``  Best-limit levels.
        =================  ==========================  =======================

        ``order_book`` dictionaries expose ``n``, ``qmd``, ``zmd``, ``pmd``,
        ``pmo``, ``zmo`` and ``qmo`` for levels 1..5, sorted by ``n``.

    Raises:
        NetworkError: If the MarketWatch endpoint cannot be reached.
        ParseError: If the response body is not valid JSON.
        pydantic.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
    """

    payload = await client.get_json(MARKET_WATCH_URL, raw=True)
    response = MarketWatchResponse.model_validate(payload)

    records: list[dict[str, Any]] = []
    for item in response.marketwatch:
        order_book = sorted(item.blDs, key=lambda level: level.n)
        records.append(
            {
                "ins_code": item.insCode,
                "symbol": normalize_persian(item.lva),
                "company_name": normalize_persian(item.lvc),
                "eps": item.eps,
                "pe": item.pe,
                "open": item.pf,
                "high": item.pmx,
                "low": item.pmn,
                "close": item.pdv,
                "final_price": item.pcl,
                "prev_price": item.py,
                # Current servers use qtj/pMax/pMin; fall back to legacy names.
                "volume": _first_value(item.qtj, item.qtt),
                "value": item.qtc,
                "trades": item.ztt,
                "tmax": _first_value(item.pMax, item.ps),
                "tmin": _first_value(item.pMin, item.pi),
                "total_shares": item.ztd,
                "order_book": [level.model_dump() for level in order_book],
            }
        )
    return to_dataframe(records, engine)

to_pandas

to_pandas(frame: DataFrame) -> pd.DataFrame
Source code in src/iranquant/quant/_utils.py
def to_pandas(frame: DataFrame) -> pd.DataFrame:
    if isinstance(frame, pl.DataFrame):
        return cast(pd.DataFrame, frame.to_pandas())
    if isinstance(frame, pd.DataFrame):
        return frame
    raise TypeError(f"Expected a pandas or polars DataFrame, got {type(frame)!r}")

_to_float

_to_float(value: Any) -> float
Source code in src/iranquant/stream/watcher.py
def _to_float(value: Any) -> float:
    try:
        return float(value)
    except (TypeError, ValueError):
        return 0.0

_book_volume

_book_volume(order_book: Any, side: str) -> float
Source code in src/iranquant/stream/watcher.py
def _book_volume(order_book: Any, side: str) -> float:
    if order_book is None or isinstance(order_book, str):
        return 0.0
    levels = [order_book] if isinstance(order_book, dict) else list(order_book)
    key = "zmd" if side == "buy" else "zmo"
    total = 0.0
    for level in levels:
        if isinstance(level, dict):
            total += _to_float(level.get(key, 0.0))
        else:
            total += _to_float(getattr(level, key, 0.0))
    return total

_tehran_timezone

_tehran_timezone() -> dt.tzinfo
Source code in src/iranquant/stream/watcher.py
def _tehran_timezone() -> dt.tzinfo:
    try:
        return ZoneInfo("Asia/Tehran")
    except ZoneInfoNotFoundError:  # pragma: no cover - tzdata normally present
        return dt.timezone(dt.timedelta(hours=3, minutes=30), "IRST")

is_market_open

is_market_open(now: datetime | None = None) -> bool

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

True when the current weekday is Saturday to Wednesday and the

bool

local time is between 09:00 and 12:30 inclusive, otherwise False.

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
Source code in src/iranquant/stream/watcher.py
def is_market_open(now: dt.datetime | None = None) -> bool:
    """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).

    Args:
        now: Optional aware or naive datetime.  Naive values are assumed to be
            Tehran local time.  Defaults to the current instant.

    Returns:
        ``True`` when the current weekday is Saturday to Wednesday and the
        local time is between 09:00 and 12:30 inclusive, otherwise ``False``.

    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
    """

    timezone = _tehran_timezone()
    current = now or dt.datetime.now(timezone)
    if current.tzinfo is None:
        current = current.replace(tzinfo=timezone)
    current = current.astimezone(timezone)
    if current.weekday() not in {5, 6, 0, 1, 2}:
        return False
    current_time = current.time()
    return dt.time(9, 0) <= current_time <= dt.time(12, 30)