Skip to content

Market API

Low-level asynchronous market functions. Use them with a shared iranquant.core.client.AsyncHTTPClient, or through iranquant.AsyncIranQuant / the synchronous wrappers.

Symbols

symbol

Symbol search and instrument-code resolution with in-memory caching.

SYMBOL_SEARCH_URL module-attribute

SYMBOL_SEARCH_URL = (
    TSETMC_CDN
    + "/api/Instrument/GetInstrumentSearch/{query}"
)

ACTIVE_FLOWS module-attribute

ACTIVE_FLOWS = frozenset({1, 2, 4})

_search_cache module-attribute

_search_cache: dict[str, list[InstrumentSearchItem]] = {}

_inscode_cache module-attribute

_inscode_cache: dict[str, str] = {}

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()

ParseError

Bases: IranQuantError

Raised when a remote payload cannot be parsed into the expected shape.

Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven or hEven values, and missing var datasource blocks.

SymbolNotFoundError

Bases: IranQuantError

Raised when a symbol cannot be resolved to a TSETMC instrument code.

Examples:

>>> iq.get_inscode("نماد_ناموجود")
Traceback (most recent call last):
...
iranquant.exceptions.SymbolNotFoundError: Symbol not found: 'نماد_ناموجود'

InstrumentSearchItem

Bases: TSETMCBaseModel

InstrumentSearchResponse

Bases: TSETMCBaseModel

int_to_date_optional

int_to_date_optional(d_even: int | None) -> dt.date | None

Convert a TSETMC dEven to a date, returning None for sentinels.

Values such as 0 and 1 are emitted for inactive/expired instruments and placeholder rows. Anything outside [19000101, 21001231] — or not a valid calendar date — yields None instead of raising.

Parameters:

Name Type Description Default
d_even int | None

An eight-digit Gregorian date encoded as an integer, or None.

required

Returns:

Type Description
date | None

The decoded :class:datetime.date, or None for sentinel or invalid

date | None

values.

Examples:

>>> int_to_date_optional(20261028)
datetime.date(2026, 10, 28)
>>> int_to_date_optional(0) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_date_optional(d_even: int | None) -> dt.date | None:
    """Convert a TSETMC ``dEven`` to a date, returning ``None`` for sentinels.

    Values such as ``0`` and ``1`` are emitted for inactive/expired instruments
    and placeholder rows.  Anything outside ``[19000101, 21001231]`` — or not a
    valid calendar date — yields ``None`` instead of raising.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer, or ``None``.

    Returns:
        The decoded :class:`datetime.date`, or ``None`` for sentinel or invalid
        values.

    Examples:
        >>> int_to_date_optional(20261028)
        datetime.date(2026, 10, 28)
        >>> int_to_date_optional(0) is None
        True
    """

    if d_even is None:
        return None
    try:
        value = int(d_even)
    except (TypeError, ValueError):
        return None
    if not MIN_EVEN_DATE <= value <= MAX_EVEN_DATE:
        return None
    try:
        return int_to_date(value)
    except ParseError:
        return None

int_to_jdate_optional

int_to_jdate_optional(d_even: int | None) -> str | None

Jalali counterpart of :func:int_to_date_optional.

Parameters:

Name Type Description Default
d_even int | None

An eight-digit Gregorian date encoded as an integer, or None.

required

Returns:

Type Description
str | None

The Jalali date as "YYYY-MM-DD", or None for sentinel values.

Examples:

>>> int_to_jdate_optional(1) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_jdate_optional(d_even: int | None) -> str | None:
    """Jalali counterpart of :func:`int_to_date_optional`.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer, or ``None``.

    Returns:
        The Jalali date as ``"YYYY-MM-DD"``, or ``None`` for sentinel values.

    Examples:
        >>> int_to_jdate_optional(1) is None
        True
    """

    gregorian = int_to_date_optional(d_even)
    if gregorian is None:
        return None
    jalali = jdatetime.date.fromgregorian(date=gregorian)
    return str(jalali.strftime("%Y-%m-%d"))

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())

instrument_to_dict

instrument_to_dict(
    item: InstrumentSearchItem,
) -> dict[str, Any]

Standardize a search result into a user-facing record.

Parameters:

Name Type Description Default
item InstrumentSearchItem

A raw :class:~iranquant.models.tsetmc.InstrumentSearchItem from the TSETMC search payload.

required

Returns:

Type Description
dict[str, Any]

A dictionary with the following keys:

dict[str, Any]
  • ins_code (str) — TSETMC instrument code.
dict[str, Any]
  • symbol (str) — lVal18AFC ticker, e.g. "فولاد".
dict[str, Any]
  • company_name (str) — full company name.
dict[str, Any]
  • isin (str | None) — international securities code.
dict[str, Any]
  • shares (float) — total listed shares.
dict[str, Any]
  • flow (int) — TSETMC flow id (1, 2 and 4 are tradable).
dict[str, Any]
  • board (str) — market board code (cgrValCot).
dict[str, Any]
  • last_date (datetime.date | None) — last trade date.
dict[str, Any]
  • last_date_jdate (str | None) — Jalali last trade date.

Examples:

>>> record = instrument_to_dict(response.instrumentSearch[0])
>>> record["symbol"]
'فولاد'
Source code in src/iranquant/market/symbol.py
def instrument_to_dict(item: InstrumentSearchItem) -> dict[str, Any]:
    """Standardize a search result into a user-facing record.

    Args:
        item: A raw :class:`~iranquant.models.tsetmc.InstrumentSearchItem` from
            the TSETMC search payload.

    Returns:
        A dictionary with the following keys:

        * ``ins_code`` (``str``) — TSETMC instrument code.
        * ``symbol`` (``str``) — ``lVal18AFC`` ticker, e.g. ``"فولاد"``.
        * ``company_name`` (``str``) — full company name.
        * ``isin`` (``str | None``) — international securities code.
        * ``shares`` (``float``) — total listed shares.
        * ``flow`` (``int``) — TSETMC flow id (1, 2 and 4 are tradable).
        * ``board`` (``str``) — market board code (``cgrValCot``).
        * ``last_date`` (``datetime.date | None``) — last trade date.
        * ``last_date_jdate`` (``str | None``) — Jalali last trade date.

    Examples:
        >>> record = instrument_to_dict(response.instrumentSearch[0])
        >>> record["symbol"]
        'فولاد'
    """

    return {
        "ins_code": item.insCode,
        "symbol": normalize_persian(item.lVal18AFC),
        "company_name": normalize_persian(item.lVal30),
        "isin": item.cIsin,
        "shares": item.zTitad,
        "flow": item.flow,
        "board": item.cgrValCot,
        "last_date": int_to_date_optional(item.lastDate),
        "last_date_jdate": int_to_jdate_optional(item.lastDate),
    }

search_symbol async

search_symbol(
    client: AsyncHTTPClient, query: str
) -> list[InstrumentSearchItem]

Search TSETMC instruments by symbol or company name.

The query is Persian-normalized before it is sent. Results are memoized in-process by normalized query, so repeated searches do not hit the network.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
query str

Symbol or company-name fragment, e.g. "فولاد" or "خودرو".

required

Returns:

Type Description
list[InstrumentSearchItem]

Matching instruments. An empty query returns an empty list without a

list[InstrumentSearchItem]

request.

Raises:

Type Description
NetworkError

If cdn.tsetmc.com cannot be reached.

ParseError

If the response does not match the expected schema.

Examples:

>>> items = await search_symbol(client, "فولاد")
>>> items[0].lVal18AFC
'فولاد'
Source code in src/iranquant/market/symbol.py
async def search_symbol(
    client: AsyncHTTPClient,
    query: str,
) -> list[InstrumentSearchItem]:
    """Search TSETMC instruments by symbol or company name.

    The query is Persian-normalized before it is sent.  Results are memoized
    in-process by normalized query, so repeated searches do not hit the
    network.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        query: Symbol or company-name fragment, e.g. ``"فولاد"`` or ``"خودرو"``.

    Returns:
        Matching instruments.  An empty query returns an empty list without a
        request.

    Raises:
        NetworkError: If ``cdn.tsetmc.com`` cannot be reached.
        ParseError: If the response does not match the expected schema.

    Examples:
        >>> items = await search_symbol(client, "فولاد")
        >>> items[0].lVal18AFC
        'فولاد'
    """

    normalized = normalize_persian(query)
    if not normalized:
        return []
    if normalized in _search_cache:
        return list(_search_cache[normalized])

    url = SYMBOL_SEARCH_URL.format(query=quote(normalized, safe=""))
    payload = await client.get_json(url)
    try:
        response = InstrumentSearchResponse.model_validate(payload)
    except Exception as exc:  # pydantic ValidationError
        raise ParseError(f"Unexpected instrument search payload for {query!r}") from exc

    items = response.instrumentSearch
    _search_cache[normalized] = items
    return list(items)

_is_active

_is_active(item: InstrumentSearchItem) -> bool
Source code in src/iranquant/market/symbol.py
def _is_active(item: InstrumentSearchItem) -> bool:
    return item.flow in ACTIVE_FLOWS

get_inscode async

get_inscode(client: AsyncHTTPClient, symbol: str) -> str

Resolve a symbol to its TSETMC instrument code (insCode).

Matching is done on normalized lVal18AFC values. Instruments with an active flow (1, 2 or 4) are preferred; ties are broken by the newest lastDate. Results are cached in-process.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
symbol str

Persian ticker, e.g. "فولاد". Arabic yeh/kaf variants and Persian digits are normalized automatically.

required

Returns:

Type Description
str

The numeric insCode as a string, e.g. "46348559193224090".

Raises:

Type Description
SymbolNotFoundError

If the symbol is empty or no exact normalized match exists.

NetworkError

If the search request fails.

ParseError

If the search response is malformed.

Examples:

>>> code = await get_inscode(client, "فولاد")
>>> code.isdigit()
True
Source code in src/iranquant/market/symbol.py
async def get_inscode(client: AsyncHTTPClient, symbol: str) -> str:
    """Resolve a symbol to its TSETMC instrument code (``insCode``).

    Matching is done on normalized ``lVal18AFC`` values.  Instruments with an
    active ``flow`` (1, 2 or 4) are preferred; ties are broken by the newest
    ``lastDate``.  Results are cached in-process.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        symbol: Persian ticker, e.g. ``"فولاد"``.  Arabic yeh/kaf variants and
            Persian digits are normalized automatically.

    Returns:
        The numeric ``insCode`` as a string, e.g. ``"46348559193224090"``.

    Raises:
        SymbolNotFoundError: If the symbol is empty or no exact normalized
            match exists.
        NetworkError: If the search request fails.
        ParseError: If the search response is malformed.

    Examples:
        >>> code = await get_inscode(client, "فولاد")
        >>> code.isdigit()
        True
    """

    normalized = normalize_persian(symbol)
    if not normalized:
        raise SymbolNotFoundError("Empty symbol")

    cached = _inscode_cache.get(normalized)
    if cached is not None:
        return cached

    items = await search_symbol(client, normalized)
    matches = [item for item in items if normalize_persian(item.lVal18AFC) == normalized]
    if not matches:
        raise SymbolNotFoundError(f"Symbol not found: {symbol!r}")

    matches.sort(key=lambda item: (_is_active(item), item.lastDate or 0), reverse=True)
    code = matches[0].insCode
    _inscode_cache[normalized] = code
    return code

clear_cache

clear_cache() -> None

Clear the in-memory symbol caches (mainly useful in tests).

Clears both the search-results cache and the insCode resolution cache for the current process.

Examples:

>>> clear_cache()
Source code in src/iranquant/market/symbol.py
def clear_cache() -> None:
    """Clear the in-memory symbol caches (mainly useful in tests).

    Clears both the search-results cache and the ``insCode`` resolution cache
    for the current process.

    Examples:
        >>> clear_cache()
    """

    _search_cache.clear()
    _inscode_cache.clear()

History and adjustment

history

Daily OHLCV, client-type history and backward price adjustment.

CLIENT_TYPE_HISTORY_URL module-attribute

CLIENT_TYPE_HISTORY_URL = (
    TSETMC_CDN
    + "/api/ClientType/GetClientTypeHistory/{ins_code}"
)

DAILY_HISTORY_URL module-attribute

DAILY_HISTORY_URL = (
    TSETMC_CDN
    + "/api/ClosingPrice/GetClosingPriceDailyList/{ins_code}/0"
)

DPS_URL module-attribute

DPS_URL = (
    TSETMC_CDN
    + "/api/Instrument/GetInstrumentDPS/{ins_code}"
)

SHARE_CHANGE_URL module-attribute

SHARE_CHANGE_URL = (
    TSETMC_CDN
    + "/api/Instrument/GetInstrumentShareChange/{ins_code}"
)

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

Engine module-attribute

Engine = Literal['pandas', 'polars']

MIN_EVEN_DATE module-attribute

MIN_EVEN_DATE = 19000101

AdjustMode module-attribute

AdjustMode = Literal['none', 'all', 'capital_only']

PRICE_COLUMNS module-attribute

PRICE_COLUMNS = (
    "open",
    "high",
    "low",
    "close",
    "final_price",
    "prev_price",
)

HISTORY_COLUMNS module-attribute

HISTORY_COLUMNS = [
    "date",
    "jdate",
    "open",
    "high",
    "low",
    "close",
    "final_price",
    "prev_price",
    "volume",
    "value",
    "trades",
]

CLIENT_TYPE_COLUMNS module-attribute

CLIENT_TYPE_COLUMNS = [
    "date",
    "jdate",
    "buy_I_Volume",
    "buy_N_Volume",
    "buy_I_Value",
    "buy_N_Value",
    "buy_N_Count",
    "buy_I_Count",
    "sell_I_Volume",
    "sell_N_Volume",
    "sell_I_Value",
    "sell_N_Value",
    "sell_N_Count",
    "sell_I_Count",
]

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()

ParseError

Bases: IranQuantError

Raised when a remote payload cannot be parsed into the expected shape.

Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven or hEven values, and missing var datasource blocks.

ClientTypeResponse

Bases: TSETMCBaseModel

ClosingPriceDailyResponse

Bases: TSETMCBaseModel

InstrumentDPS

Bases: TSETMCBaseModel

InstrumentDPSResponse

Bases: TSETMCBaseModel

InstrumentShareChange

Bases: TSETMCBaseModel

InstrumentShareChangeResponse

Bases: TSETMCBaseModel

to_dataframe

to_dataframe(
    records: list[dict[str, Any]], engine: Engine = "pandas"
) -> DataFrame

Convert a list of record dictionaries to a Pandas or Polars DataFrame.

An empty records list still produces a valid (empty) DataFrame for both engines. Column order follows the key insertion order of the first record.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

Row-oriented records, typically produced by the market and Codal modules. Every record should share the same keys.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Name Type Description
A DataFrame

class:pandas.DataFrame or :class:polars.DataFrame matching

DataFrame

engine.

Raises:

Type Description
ValueError

If engine is neither "pandas" nor "polars".

Examples:

>>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
   symbol   close
0   فولاد  4150.0
>>> to_dataframe([], engine="polars").height
0
Source code in src/iranquant/core/dataframe.py
def to_dataframe(records: list[dict[str, Any]], engine: Engine = "pandas") -> DataFrame:
    """Convert a list of record dictionaries to a Pandas or Polars DataFrame.

    An empty ``records`` list still produces a valid (empty) DataFrame for both
    engines.  Column order follows the key insertion order of the first record.

    Args:
        records: Row-oriented records, typically produced by the market and
            Codal modules.  Every record should share the same keys.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A :class:`pandas.DataFrame` or :class:`polars.DataFrame` matching
        ``engine``.

    Raises:
        ValueError: If ``engine`` is neither ``"pandas"`` nor ``"polars"``.

    Examples:
        >>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
           symbol   close
        0   فولاد  4150.0
        >>> to_dataframe([], engine="polars").height
        0
    """

    if engine == "polars":
        return pl.DataFrame(records)
    if engine == "pandas":
        return cast(pd.DataFrame, pd.DataFrame(records))
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

int_to_date

int_to_date(d_even: int) -> dt.date

Convert a TSETMC dEven integer (e.g. 20261028) to a date.

Parameters:

Name Type Description Default
d_even int

An eight-digit Gregorian date encoded as an integer.

required

Returns:

Type Description
date

The corresponding :class:datetime.date.

Raises:

Type Description
ParseError

If the value is longer than eight digits or is not a valid calendar date.

Examples:

>>> int_to_date(20261028)
datetime.date(2026, 10, 28)
Source code in src/iranquant/core/normalizer.py
def int_to_date(d_even: int) -> dt.date:
    """Convert a TSETMC ``dEven`` integer (e.g. ``20261028``) to a date.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer.

    Returns:
        The corresponding :class:`datetime.date`.

    Raises:
        ParseError: If the value is longer than eight digits or is not a valid
            calendar date.

    Examples:
        >>> int_to_date(20261028)
        datetime.date(2026, 10, 28)
    """

    raw = _even_digits(d_even, 8, "dEven")
    year, month, day = int(raw[:4]), int(raw[4:6]), int(raw[6:8])
    try:
        return dt.date(year, month, day)
    except ValueError as exc:
        raise ParseError(f"Invalid TSETMC date: {d_even!r}") from exc

int_to_date_optional

int_to_date_optional(d_even: int | None) -> dt.date | None

Convert a TSETMC dEven to a date, returning None for sentinels.

Values such as 0 and 1 are emitted for inactive/expired instruments and placeholder rows. Anything outside [19000101, 21001231] — or not a valid calendar date — yields None instead of raising.

Parameters:

Name Type Description Default
d_even int | None

An eight-digit Gregorian date encoded as an integer, or None.

required

Returns:

Type Description
date | None

The decoded :class:datetime.date, or None for sentinel or invalid

date | None

values.

Examples:

>>> int_to_date_optional(20261028)
datetime.date(2026, 10, 28)
>>> int_to_date_optional(0) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_date_optional(d_even: int | None) -> dt.date | None:
    """Convert a TSETMC ``dEven`` to a date, returning ``None`` for sentinels.

    Values such as ``0`` and ``1`` are emitted for inactive/expired instruments
    and placeholder rows.  Anything outside ``[19000101, 21001231]`` — or not a
    valid calendar date — yields ``None`` instead of raising.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer, or ``None``.

    Returns:
        The decoded :class:`datetime.date`, or ``None`` for sentinel or invalid
        values.

    Examples:
        >>> int_to_date_optional(20261028)
        datetime.date(2026, 10, 28)
        >>> int_to_date_optional(0) is None
        True
    """

    if d_even is None:
        return None
    try:
        value = int(d_even)
    except (TypeError, ValueError):
        return None
    if not MIN_EVEN_DATE <= value <= MAX_EVEN_DATE:
        return None
    try:
        return int_to_date(value)
    except ParseError:
        return None

int_to_jdate

int_to_jdate(d_even: int) -> str

Convert a TSETMC dEven integer to a Jalali YYYY-MM-DD string.

Parameters:

Name Type Description Default
d_even int

An eight-digit Gregorian date encoded as an integer.

required

Returns:

Type Description
str

The Jalali (Solar Hijri) date as a zero-padded "YYYY-MM-DD" string.

Raises:

Type Description
ParseError

If d_even is not a valid Gregorian date.

Examples:

>>> int_to_jdate(20261028)
'1405-08-06'
Source code in src/iranquant/core/normalizer.py
def int_to_jdate(d_even: int) -> str:
    """Convert a TSETMC ``dEven`` integer to a Jalali ``YYYY-MM-DD`` string.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer.

    Returns:
        The Jalali (Solar Hijri) date as a zero-padded ``"YYYY-MM-DD"`` string.

    Raises:
        ParseError: If ``d_even`` is not a valid Gregorian date.

    Examples:
        >>> int_to_jdate(20261028)
        '1405-08-06'
    """

    gregorian = int_to_date(d_even)
    jalali = jdatetime.date.fromgregorian(date=gregorian)
    return str(jalali.strftime("%Y-%m-%d"))

_validate

_validate(
    model: type[Any], payload: Any, label: str
) -> Any
Source code in src/iranquant/market/history.py
def _validate(model: type[Any], payload: Any, label: str) -> Any:
    try:
        return model.model_validate(payload)
    except Exception as exc:  # pydantic.ValidationError
        raise ParseError(f"Unexpected {label} payload") from exc

apply_gap_adjustment

apply_gap_adjustment(
    records: list[dict[str, Any]],
) -> list[dict[str, Any]]

Backward-adjust prices using the priceYesterday gap ratio.

priceYesterday on day t already reflects any dividend or capital increase applied between t-1 and t, while final_price on day t-1 is unadjusted. The cumulative factor is therefore computed backwards from the newest day (factor 1.0) and applied to all price columns.

For i = n-2 ... 0 the per-day ratio is r[i] = prev_price[i+1] / final_price[i] and the cumulative factor is F[i] = F[i+1] * r[i]. Every column in PRICE_COLUMNS (open, high, low, close, final_price, prev_price) is multiplied by F[i]. The input list is never mutated.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

Chronologically ascending daily records produced by :func:_daily_records. Each record must contain the keys in PRICE_COLUMNS.

required

Returns:

Type Description
list[dict[str, Any]]

A new list of copied records with adjusted float prices. Records with

list[dict[str, Any]]

fewer than two rows are returned as shallow copies.

Examples:

>>> rows = [
...     {"final_price": 100.0, "prev_price": 100.0, "open": 100.0,
...      "high": 100.0, "low": 100.0, "close": 100.0},
...     {"final_price": 100.0, "prev_price": 90.0, "open": 100.0,
...      "high": 100.0, "low": 100.0, "close": 100.0},
... ]
>>> apply_gap_adjustment(rows)[0]["final_price"]
90.0
Source code in src/iranquant/market/history.py
def apply_gap_adjustment(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Backward-adjust prices using the ``priceYesterday`` gap ratio.

    ``priceYesterday`` on day *t* already reflects any dividend or capital
    increase applied between *t-1* and *t*, while ``final_price`` on day *t-1*
    is unadjusted.  The cumulative factor is therefore computed backwards from
    the newest day (factor 1.0) and applied to all price columns.

    For ``i = n-2 ... 0`` the per-day ratio is
    ``r[i] = prev_price[i+1] / final_price[i]`` and the cumulative factor is
    ``F[i] = F[i+1] * r[i]``.  Every column in ``PRICE_COLUMNS``
    (``open``, ``high``, ``low``, ``close``, ``final_price``, ``prev_price``)
    is multiplied by ``F[i]``.  The input list is never mutated.

    Args:
        records: Chronologically ascending daily records produced by
            :func:`_daily_records`.  Each record must contain the keys in
            ``PRICE_COLUMNS``.

    Returns:
        A new list of copied records with adjusted float prices.  Records with
        fewer than two rows are returned as shallow copies.

    Examples:
        >>> rows = [
        ...     {"final_price": 100.0, "prev_price": 100.0, "open": 100.0,
        ...      "high": 100.0, "low": 100.0, "close": 100.0},
        ...     {"final_price": 100.0, "prev_price": 90.0, "open": 100.0,
        ...      "high": 100.0, "low": 100.0, "close": 100.0},
        ... ]
        >>> apply_gap_adjustment(rows)[0]["final_price"]
        90.0
    """

    if len(records) < 2:
        return [dict(record) for record in records]

    factors = [1.0] * len(records)
    for index in range(len(records) - 2, -1, -1):
        previous_final = float(records[index]["final_price"])
        current_prev = float(records[index + 1]["prev_price"])
        ratio = current_prev / previous_final if previous_final > 0 and current_prev > 0 else 1.0
        factors[index] = factors[index + 1] * ratio

    adjusted: list[dict[str, Any]] = []
    for factor, record in zip(factors, records, strict=True):
        row = dict(record)
        for column in PRICE_COLUMNS:
            row[column] = float(record[column]) * factor
        adjusted.append(row)
    return adjusted

apply_capital_adjustment

apply_capital_adjustment(
    records: list[dict[str, Any]],
    share_changes: list[InstrumentShareChange],
) -> list[dict[str, Any]]

Adjust prices backwards for capital increases only.

For an increase from numberOfShareOld to numberOfShareNew the historical prices preceding the event are multiplied by old / new (the theoretical ex-rights ratio).

Events with non-positive share counts or an invalid dEven are ignored. A record exactly on the event date is not adjusted; only strictly earlier records are. The input list is never mutated.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

Chronologically ascending daily records with a datetime.date under the "date" key.

required
share_changes list[InstrumentShareChange]

Corporate-action events from :func:get_share_changes.

required

Returns:

Type Description
list[dict[str, Any]]

A new list of copied records whose PRICE_COLUMNS are scaled by the

list[dict[str, Any]]

cumulative old / new factors of all later events.

Examples:

>>> event = InstrumentShareChange(
...     dEven=20261028, numberOfShareOld=100.0, numberOfShareNew=200.0
... )
>>> apply_capital_adjustment(records, [event])[0]["open"]
50.0
Source code in src/iranquant/market/history.py
def apply_capital_adjustment(
    records: list[dict[str, Any]],
    share_changes: list[InstrumentShareChange],
) -> list[dict[str, Any]]:
    """Adjust prices backwards for capital increases only.

    For an increase from ``numberOfShareOld`` to ``numberOfShareNew`` the
    historical prices preceding the event are multiplied by
    ``old / new`` (the theoretical ex-rights ratio).

    Events with non-positive share counts or an invalid ``dEven`` are ignored.
    A record exactly on the event date is *not* adjusted; only strictly earlier
    records are.  The input list is never mutated.

    Args:
        records: Chronologically ascending daily records with a
            ``datetime.date`` under the ``"date"`` key.
        share_changes: Corporate-action events from
            :func:`get_share_changes`.

    Returns:
        A new list of copied records whose ``PRICE_COLUMNS`` are scaled by the
        cumulative ``old / new`` factors of all later events.

    Examples:
        >>> event = InstrumentShareChange(
        ...     dEven=20261028, numberOfShareOld=100.0, numberOfShareNew=200.0
        ... )
        >>> apply_capital_adjustment(records, [event])[0]["open"]
        50.0
    """

    events: list[tuple[dt.date, InstrumentShareChange]] = []
    for event in share_changes:
        if event.numberOfShareOld <= 0 or event.numberOfShareNew <= 0:
            continue
        event_date = int_to_date_optional(event.dEven)
        if event_date is None:
            continue
        events.append((event_date, event))
    events.sort(key=lambda pair: pair[0])

    adjusted: list[dict[str, Any]] = []
    for record in records:
        row_date = cast(dt.date, record["date"])
        factor = 1.0
        for event_date, event in events:
            if row_date < event_date:
                factor *= event.numberOfShareOld / event.numberOfShareNew
        row = dict(record)
        for column in PRICE_COLUMNS:
            row[column] = float(record[column]) * factor
        adjusted.append(row)
    return adjusted

get_share_changes async

get_share_changes(
    client: AsyncHTTPClient, ins_code: str
) -> list[InstrumentShareChange]

Fetch the capital-increase history of an instrument.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required

Returns:

Type Description
list[InstrumentShareChange]

Share-change events, each exposing dEven, numberOfShareOld and

list[InstrumentShareChange]

numberOfShareNew.

Raises:

Type Description
NetworkError

If the endpoint cannot be reached.

ParseError

If the payload does not match the expected schema.

Examples:

>>> events = await get_share_changes(client, "46348559193224090")
>>> events[0].numberOfShareNew
2000000000000.0
Source code in src/iranquant/market/history.py
async def get_share_changes(
    client: AsyncHTTPClient,
    ins_code: str,
) -> list[InstrumentShareChange]:
    """Fetch the capital-increase history of an instrument.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        ins_code: TSETMC instrument code.

    Returns:
        Share-change events, each exposing ``dEven``, ``numberOfShareOld`` and
        ``numberOfShareNew``.

    Raises:
        NetworkError: If the endpoint cannot be reached.
        ParseError: If the payload does not match the expected schema.

    Examples:
        >>> events = await get_share_changes(client, "46348559193224090")
        >>> events[0].numberOfShareNew
        2000000000000.0
    """
    payload = await client.get_json(SHARE_CHANGE_URL.format(ins_code=ins_code))
    response = cast(
        InstrumentShareChangeResponse,
        _validate(InstrumentShareChangeResponse, payload, "share change"),
    )
    return response.instrumentShareChange

get_dps async

get_dps(
    client: AsyncHTTPClient, ins_code: str
) -> list[InstrumentDPS]

Fetch dividend-per-share (DPS) events for an instrument.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required

Returns:

Type Description
list[InstrumentDPS]

DPS events with dEven and priceAfterTax fields.

Raises:

Type Description
NetworkError

If the endpoint cannot be reached.

ParseError

If the payload does not match the expected schema.

Examples:

>>> events = await get_dps(client, "46348559193224090")
>>> events[0].priceAfterTax
350.0
Source code in src/iranquant/market/history.py
async def get_dps(
    client: AsyncHTTPClient,
    ins_code: str,
) -> list[InstrumentDPS]:
    """Fetch dividend-per-share (DPS) events for an instrument.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        ins_code: TSETMC instrument code.

    Returns:
        DPS events with ``dEven`` and ``priceAfterTax`` fields.

    Raises:
        NetworkError: If the endpoint cannot be reached.
        ParseError: If the payload does not match the expected schema.

    Examples:
        >>> events = await get_dps(client, "46348559193224090")
        >>> events[0].priceAfterTax
        350.0
    """
    payload = await client.get_json(DPS_URL.format(ins_code=ins_code))
    response = cast(InstrumentDPSResponse, _validate(InstrumentDPSResponse, payload, "DPS"))
    return response.instrumentDPS

_daily_records async

_daily_records(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    adjust: AdjustMode,
) -> list[dict[str, Any]]
Source code in src/iranquant/market/history.py
async def _daily_records(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    adjust: AdjustMode,
) -> list[dict[str, Any]]:
    if adjust not in ("none", "all", "capital_only"):
        raise ValueError(f"Unsupported adjust mode: {adjust!r}")

    payload = await client.get_json(DAILY_HISTORY_URL.format(ins_code=ins_code))
    response = cast(
        ClosingPriceDailyResponse,
        _validate(ClosingPriceDailyResponse, payload, "daily history"),
    )

    records: list[dict[str, Any]] = []
    for item in response.closingPriceDaily:
        # Drop sentinel dates emitted for expired/placeholder instruments.
        if item.dEven < MIN_EVEN_DATE:
            continue
        # Drop non-trading placeholder rows.
        if item.qTotTran5J == 0 and item.zTotTran == 0:
            continue
        records.append(
            {
                "date": int_to_date(item.dEven),
                "jdate": int_to_jdate(item.dEven),
                "open": item.priceFirst,
                "high": item.priceMax,
                "low": item.priceMin,
                "close": item.pDrCotVal,
                "final_price": item.pClosing,
                "prev_price": item.priceYesterday,
                "volume": item.qTotTran5J,
                "value": item.qTotCap,
                "trades": item.zTotTran,
            }
        )

    records.sort(key=lambda row: cast(dt.date, row["date"]))

    if adjust == "all":
        return apply_gap_adjustment(records)
    if adjust == "capital_only":
        changes = await get_share_changes(client, ins_code)
        return apply_capital_adjustment(records, changes)
    return records

_empty_frame

_empty_frame(
    columns: list[str], engine: Engine
) -> DataFrame
Source code in src/iranquant/market/history.py
def _empty_frame(columns: list[str], engine: Engine) -> DataFrame:
    if engine == "polars":
        return pl.DataFrame({column: [] for column in columns})
    if engine == "pandas":
        return pd.DataFrame(columns=columns)
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

_client_type_records

_client_type_records(
    response: ClientTypeResponse,
) -> list[dict[str, Any]]
Source code in src/iranquant/market/history.py
def _client_type_records(
    response: ClientTypeResponse,
) -> list[dict[str, Any]]:
    records: list[dict[str, Any]] = []
    for item in response.clientType:
        if item.recDate < MIN_EVEN_DATE:
            continue
        records.append(
            {
                "date": int_to_date(item.recDate),
                "jdate": int_to_jdate(item.recDate),
                "buy_I_Volume": item.buy_I_Volume,
                "buy_N_Volume": item.buy_N_Volume,
                "buy_I_Value": item.buy_I_Value,
                "buy_N_Value": item.buy_N_Value,
                "buy_N_Count": item.buy_N_Count,
                "buy_I_Count": item.buy_I_Count,
                "sell_I_Volume": item.sell_I_Volume,
                "sell_N_Volume": item.sell_N_Volume,
                "sell_I_Value": item.sell_I_Value,
                "sell_N_Value": item.sell_N_Value,
                "sell_N_Count": item.sell_N_Count,
                "sell_I_Count": item.sell_I_Count,
            }
        )
    records.sort(key=lambda row: cast(dt.date, row["date"]))
    return records

get_daily_history async

get_daily_history(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch standardized daily OHLCV history for an instrument.

Sentinel dates (dEven below 19000101) and placeholder rows with no volume and no trades are dropped, then rows are sorted by date.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required
adjust AdjustMode

Price adjustment mode.

  • "none" — raw prices exactly as TSETMC reports them.
  • "all" (default) — backward-adjusted for dividends and capital increases using :func:apply_gap_adjustment.
  • "capital_only" — backward-adjusted for capital increases only using :func:apply_capital_adjustment and the instrument's share changes.
'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

A frame with one row per trading day and the following columns:

DataFrame

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

DataFrame

Column Type Description

DataFrame

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

DataFrame

date datetime.date Gregorian trading date.

DataFrame

jdate str Jalali date, YYYY-MM-DD.

DataFrame

open float First traded price (priceFirst).

DataFrame

high float Daily maximum (priceMax).

DataFrame

low float Daily minimum (priceMin).

DataFrame

close float Last traded price (pDrCotVal).

DataFrame

final_price float Closing price (pClosing).

DataFrame

prev_price float Previous-day close (priceYesterday).

DataFrame

volume float Traded shares (qTotTran5J).

DataFrame

value float Traded value in Rials (qTotCap).

DataFrame

trades float Number of trades (zTotTran).

DataFrame

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

DataFrame

An empty frame with the same columns is returned when no valid rows

DataFrame

remain.

Raises:

Type Description
ValueError

If adjust is not one of the three supported modes or engine is unsupported.

NetworkError

If TSETMC cannot be reached.

ParseError

If the payload does not match the expected schema.

Examples:

>>> frame = await get_daily_history(client, "46348559193224090")
>>> frame.columns.tolist()[:5]
['date', 'jdate', 'open', 'high', 'low']
>>> frame = await get_daily_history(
...     client, "46348559193224090", adjust="none", engine="polars"
... )
Source code in src/iranquant/market/history.py
async def get_daily_history(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch standardized daily OHLCV history for an instrument.

    Sentinel dates (``dEven`` below ``19000101``) and placeholder rows with no
    volume and no trades are dropped, then rows are sorted by ``date``.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        ins_code: TSETMC instrument code.
        adjust: Price adjustment mode.

            * ``"none"`` — raw prices exactly as TSETMC reports them.
            * ``"all"`` (default) — backward-adjusted for dividends and capital
              increases using :func:`apply_gap_adjustment`.
            * ``"capital_only"`` — backward-adjusted for capital increases only
              using :func:`apply_capital_adjustment` and the instrument's share
              changes.

        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A frame with one row per trading day and the following columns:

        ==============  =================  =====================================
        Column          Type               Description
        ==============  =================  =====================================
        ``date``        ``datetime.date``  Gregorian trading date.
        ``jdate``       ``str``            Jalali date, ``YYYY-MM-DD``.
        ``open``        ``float``          First traded price (``priceFirst``).
        ``high``        ``float``          Daily maximum (``priceMax``).
        ``low``         ``float``          Daily minimum (``priceMin``).
        ``close``       ``float``          Last traded price (``pDrCotVal``).
        ``final_price`` ``float``          Closing price (``pClosing``).
        ``prev_price``  ``float``          Previous-day close (``priceYesterday``).
        ``volume``      ``float``          Traded shares (``qTotTran5J``).
        ``value``       ``float``          Traded value in Rials (``qTotCap``).
        ``trades``      ``float``          Number of trades (``zTotTran``).
        ==============  =================  =====================================

        An empty frame with the same columns is returned when no valid rows
        remain.

    Raises:
        ValueError: If ``adjust`` is not one of the three supported modes or
            ``engine`` is unsupported.
        NetworkError: If TSETMC cannot be reached.
        ParseError: If the payload does not match the expected schema.

    Examples:
        >>> frame = await get_daily_history(client, "46348559193224090")
        >>> frame.columns.tolist()[:5]
        ['date', 'jdate', 'open', 'high', 'low']
        >>> frame = await get_daily_history(
        ...     client, "46348559193224090", adjust="none", engine="polars"
        ... )
    """

    records = await _daily_records(client, ins_code, adjust=adjust)
    if not records:
        return _empty_frame(HISTORY_COLUMNS, engine)
    return to_dataframe(records, engine)

get_client_type_history async

get_client_type_history(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch retail/institutional (حقیقی/حقوقی) client-type history.

I columns describe individual/retail (حقیقی) activity and N columns describe institutional/legal (حقوقی) activity.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

A frame sorted by date with the following columns:

DataFrame

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

DataFrame

Column Type Description

DataFrame

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

DataFrame

date datetime.date Trading date.

DataFrame

jdate str Jalali date, YYYY-MM-DD.

DataFrame

buy_I_Volume float Retail buy volume.

DataFrame

buy_N_Volume float Institutional buy volume.

DataFrame

buy_I_Value float Retail buy value (Rials).

DataFrame

buy_N_Value float Institutional buy value (Rials).

DataFrame

buy_N_Count int Institutional buy order count.

DataFrame

buy_I_Count int Retail buy order count.

DataFrame

sell_I_Volume float Retail sell volume.

DataFrame

sell_N_Volume float Institutional sell volume.

DataFrame

sell_I_Value float Retail sell value (Rials).

DataFrame

sell_N_Value float Institutional sell value (Rials).

DataFrame

sell_N_Count int Institutional sell order count.

DataFrame

sell_I_Count int Retail sell order count.

DataFrame

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

Raises:

Type Description
NetworkError

If TSETMC cannot be reached.

ParseError

If the payload does not match the expected schema.

ValueError

If engine is unsupported.

Examples:

>>> frame = await get_client_type_history(client, "46348559193224090")
>>> frame[["date", "buy_I_Volume", "sell_N_Count"]].tail(1)
Source code in src/iranquant/market/history.py
async def get_client_type_history(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch retail/institutional (حقیقی/حقوقی) client-type history.

    ``I`` columns describe individual/retail (حقیقی) activity and ``N`` columns
    describe institutional/legal (حقوقی) activity.

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

    Returns:
        A frame sorted by ``date`` with the following columns:

        =================  =================  ==================================
        Column             Type               Description
        =================  =================  ==================================
        ``date``           ``datetime.date``  Trading date.
        ``jdate``          ``str``            Jalali date, ``YYYY-MM-DD``.
        ``buy_I_Volume``   ``float``          Retail buy volume.
        ``buy_N_Volume``   ``float``          Institutional buy volume.
        ``buy_I_Value``    ``float``          Retail buy value (Rials).
        ``buy_N_Value``    ``float``          Institutional buy value (Rials).
        ``buy_N_Count``    ``int``            Institutional buy order count.
        ``buy_I_Count``    ``int``            Retail buy order count.
        ``sell_I_Volume``  ``float``          Retail sell volume.
        ``sell_N_Volume``  ``float``          Institutional sell volume.
        ``sell_I_Value``   ``float``          Retail sell value (Rials).
        ``sell_N_Value``   ``float``          Institutional sell value (Rials).
        ``sell_N_Count``   ``int``            Institutional sell order count.
        ``sell_I_Count``   ``int``            Retail sell order count.
        =================  =================  ==================================

    Raises:
        NetworkError: If TSETMC cannot be reached.
        ParseError: If the payload does not match the expected schema.
        ValueError: If ``engine`` is unsupported.

    Examples:
        >>> frame = await get_client_type_history(client, "46348559193224090")
        >>> frame[["date", "buy_I_Volume", "sell_N_Count"]].tail(1)
    """

    payload = await client.get_json(CLIENT_TYPE_HISTORY_URL.format(ins_code=ins_code))
    response = cast(
        ClientTypeResponse,
        _validate(ClientTypeResponse, payload, "client type history"),
    )
    records = _client_type_records(response)
    if not records:
        return _empty_frame(CLIENT_TYPE_COLUMNS, engine)
    return to_dataframe(records, engine)

get_full_history async

get_full_history(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Merge daily OHLCV with client-type history on the trading date.

The two requests are performed sequentially and merged with an outer join on date (so dates missing from either source are retained), then sorted ascending. The client-type jdate column is dropped, leaving a single jdate from the OHLCV frame.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required
adjust AdjustMode

Price adjustment mode, identical to :func:get_daily_history ("none", "all" or "capital_only").

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

A frame with the eleven :func:get_daily_history columns followed by

DataFrame

the twelve client-type columns below (date is shared):

DataFrame
  • buy_I_Volume, buy_N_Volume (float)
DataFrame
  • buy_I_Value, buy_N_Value (float)
DataFrame
  • buy_N_Count, buy_I_Count (int)
DataFrame
  • sell_I_Volume, sell_N_Volume (float)
DataFrame
  • sell_I_Value, sell_N_Value (float)
DataFrame
  • sell_N_Count, sell_I_Count (int)
DataFrame

When both sources are empty an empty frame is returned.

Raises:

Type Description
ValueError

If adjust or engine is unsupported.

NetworkError

If either request fails.

ParseError

If either payload is malformed.

Examples:

>>> frame = await get_full_history(client, "46348559193224090")
>>> {"open", "final_price", "buy_I_Volume"} <= set(frame.columns)
True
Source code in src/iranquant/market/history.py
async def get_full_history(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Merge daily OHLCV with client-type history on the trading date.

    The two requests are performed sequentially and merged with an outer join
    on ``date`` (so dates missing from either source are retained), then sorted
    ascending.  The client-type ``jdate`` column is dropped, leaving a single
    ``jdate`` from the OHLCV frame.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        ins_code: TSETMC instrument code.
        adjust: Price adjustment mode, identical to
            :func:`get_daily_history` (``"none"``, ``"all"`` or
            ``"capital_only"``).
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A frame with the eleven :func:`get_daily_history` columns followed by
        the twelve client-type columns below (``date`` is shared):

        * ``buy_I_Volume``, ``buy_N_Volume`` (``float``)
        * ``buy_I_Value``, ``buy_N_Value`` (``float``)
        * ``buy_N_Count``, ``buy_I_Count`` (``int``)
        * ``sell_I_Volume``, ``sell_N_Volume`` (``float``)
        * ``sell_I_Value``, ``sell_N_Value`` (``float``)
        * ``sell_N_Count``, ``sell_I_Count`` (``int``)

        When both sources are empty an empty frame is returned.

    Raises:
        ValueError: If ``adjust`` or ``engine`` is unsupported.
        NetworkError: If either request fails.
        ParseError: If either payload is malformed.

    Examples:
        >>> frame = await get_full_history(client, "46348559193224090")
        >>> {"open", "final_price", "buy_I_Volume"} <= set(frame.columns)
        True
    """

    daily = await _daily_records(client, ins_code, adjust=adjust)
    payload = await client.get_json(CLIENT_TYPE_HISTORY_URL.format(ins_code=ins_code))
    response = cast(
        ClientTypeResponse,
        _validate(ClientTypeResponse, payload, "client type history"),
    )
    clients = _client_type_records(response)

    daily_frame = pd.DataFrame(daily) if daily else pd.DataFrame(columns=HISTORY_COLUMNS)
    client_frame = pd.DataFrame(clients)
    if daily_frame.empty or client_frame.empty:
        merged = daily_frame
    else:
        client_frame = client_frame.drop(columns=["jdate"], errors="ignore")
        merged = daily_frame.merge(client_frame, on="date", how="outer")

    merged = merged.sort_values("date").reset_index(drop=True)

    if engine == "polars":
        return pl.from_pandas(merged)
    if engine == "pandas":
        return merged
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

Live data

live

Live market data: MarketWatch, order book and intraday trades.

BEST_LIMITS_URL module-attribute

BEST_LIMITS_URL = TSETMC_CDN + '/api/BestLimits/{ins_code}'

MARKET_WATCH_URL module-attribute

MARKET_WATCH_URL = (
    TSETMC_CDN
    + "/api/ClosingPrice/GetMarketWatch"
    + "?market=0&industrialGroup="
    + "&paperTypes[0]=1&paperTypes[1]=2&paperTypes[2]=8"
    + "&showTraded=false&withBestLimits=true"
)

TRADE_INTRADAY_URL module-attribute

TRADE_INTRADAY_URL = (
    TSETMC_CDN + "/api/Trade/GetTradeIntraDay/{ins_code}"
)

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

Engine module-attribute

Engine = Literal['pandas', 'polars']

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()

BestLimitResponse

Bases: TSETMCBaseModel

MarketWatchResponse

Bases: TSETMCBaseModel

TradeIntraDayResponse

Bases: TSETMCBaseModel

to_dataframe

to_dataframe(
    records: list[dict[str, Any]], engine: Engine = "pandas"
) -> DataFrame

Convert a list of record dictionaries to a Pandas or Polars DataFrame.

An empty records list still produces a valid (empty) DataFrame for both engines. Column order follows the key insertion order of the first record.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

Row-oriented records, typically produced by the market and Codal modules. Every record should share the same keys.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Name Type Description
A DataFrame

class:pandas.DataFrame or :class:polars.DataFrame matching

DataFrame

engine.

Raises:

Type Description
ValueError

If engine is neither "pandas" nor "polars".

Examples:

>>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
   symbol   close
0   فولاد  4150.0
>>> to_dataframe([], engine="polars").height
0
Source code in src/iranquant/core/dataframe.py
def to_dataframe(records: list[dict[str, Any]], engine: Engine = "pandas") -> DataFrame:
    """Convert a list of record dictionaries to a Pandas or Polars DataFrame.

    An empty ``records`` list still produces a valid (empty) DataFrame for both
    engines.  Column order follows the key insertion order of the first record.

    Args:
        records: Row-oriented records, typically produced by the market and
            Codal modules.  Every record should share the same keys.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A :class:`pandas.DataFrame` or :class:`polars.DataFrame` matching
        ``engine``.

    Raises:
        ValueError: If ``engine`` is neither ``"pandas"`` nor ``"polars"``.

    Examples:
        >>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
           symbol   close
        0   فولاد  4150.0
        >>> to_dataframe([], engine="polars").height
        0
    """

    if engine == "polars":
        return pl.DataFrame(records)
    if engine == "pandas":
        return cast(pd.DataFrame, pd.DataFrame(records))
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

int_to_time_optional

int_to_time_optional(h_even: int | None) -> dt.time | None

Convert a TSETMC hEven to a time, returning None when invalid.

Parameters:

Name Type Description Default
h_even int | None

A HHMMSS time encoded as an integer, or None.

required

Returns:

Type Description
time | None

The decoded :class:datetime.time, or None when the value is not a

time | None

valid time between 00:00:00 and 23:59:59.

Examples:

>>> int_to_time_optional(91500)
datetime.time(9, 15)
>>> int_to_time_optional(999999) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_time_optional(h_even: int | None) -> dt.time | None:
    """Convert a TSETMC ``hEven`` to a time, returning ``None`` when invalid.

    Args:
        h_even: A ``HHMMSS`` time encoded as an integer, or ``None``.

    Returns:
        The decoded :class:`datetime.time`, or ``None`` when the value is not a
        valid time between ``00:00:00`` and ``23:59:59``.

    Examples:
        >>> int_to_time_optional(91500)
        datetime.time(9, 15)
        >>> int_to_time_optional(999999) is None
        True
    """

    if h_even is None:
        return None
    try:
        value = int(h_even)
    except (TypeError, ValueError):
        return None
    if not 0 <= value <= 235959:
        return None
    try:
        return int_to_time(value)
    except ParseError:
        return None

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())

_first_value

_first_value(*values: float | None) -> float

Return the first value that is not None (older/newer field names).

Source code in src/iranquant/market/live.py
def _first_value(*values: float | None) -> float:
    """Return the first value that is not ``None`` (older/newer field names)."""

    for value in values:
        if value is not None:
            return value
    return 0.0

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)

get_order_book async

get_order_book(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch the best-limit order book (levels 1..5) for an instrument.

Rows are sorted by level number. The d/o suffixes mean demand (buy) and offer (sell) respectively.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

A frame with one row per visible level and these columns:

DataFrame
  • n (int) — level number (1 is the best level).
DataFrame
  • qmd (float) — bid order count.
DataFrame
  • zmd (float) — bid volume.
DataFrame
  • pmd (float) — bid price.
DataFrame
  • pmo (float) — ask price.
DataFrame
  • zmo (float) — ask volume.
DataFrame
  • qmo (float) — ask order count.

Raises:

Type Description
NetworkError

If the endpoint cannot be reached.

ParseError

If the response body is not valid JSON.

ValidationError

If the payload does not match the schema.

Examples:

>>> book = await get_order_book(client, "46348559193224090")
>>> book.iloc[0][["pmd", "zmd", "pmo", "zmo"]]
Source code in src/iranquant/market/live.py
async def get_order_book(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch the best-limit order book (levels 1..5) for an instrument.

    Rows are sorted by level number.  The ``d``/``o`` suffixes mean *demand*
    (buy) and *offer* (sell) respectively.

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

    Returns:
        A frame with one row per visible level and these columns:

        * ``n`` (``int``) — level number (1 is the best level).
        * ``qmd`` (``float``) — bid order count.
        * ``zmd`` (``float``) — bid volume.
        * ``pmd`` (``float``) — bid price.
        * ``pmo`` (``float``) — ask price.
        * ``zmo`` (``float``) — ask volume.
        * ``qmo`` (``float``) — ask order count.

    Raises:
        NetworkError: If the endpoint cannot be reached.
        ParseError: If the response body is not valid JSON.
        pydantic.ValidationError: If the payload does not match the schema.

    Examples:
        >>> book = await get_order_book(client, "46348559193224090")
        >>> book.iloc[0][["pmd", "zmd", "pmo", "zmo"]]
    """

    payload = await client.get_json(BEST_LIMITS_URL.format(ins_code=ins_code))
    response = BestLimitResponse.model_validate(payload)

    records = [
        {
            "n": level.number,
            "qmd": level.qTitMeDem,
            "zmd": level.zOrdMeDem,
            "pmd": level.pMeDem,
            "pmo": level.pMeOf,
            "zmo": level.zOrdMeOf,
            "qmo": level.qTitMeOf,
        }
        for level in sorted(response.bestLimits, key=lambda level: level.number)
    ]
    return to_dataframe(records, engine)

get_intraday_trades async

get_intraday_trades(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch intraday OHLCV bars for the current/last trading session.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
ins_code str

TSETMC instrument code.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per intraday bar, in server order, with these columns:

DataFrame
  • time (datetime.time | None) — bar time from hEven.
DataFrame
  • open (float) — first price in the bar.
DataFrame
  • high (float) — highest price in the bar.
DataFrame
  • low (float) — lowest price in the bar.
DataFrame
  • close (float) — last price in the bar.
DataFrame
  • volume (float) — traded volume in the bar.

Raises:

Type Description
NetworkError

If the endpoint cannot be reached.

ParseError

If the response body is not valid JSON.

ValidationError

If the payload does not match the schema.

Examples:

>>> bars = await get_intraday_trades(client, "46348559193224090")
>>> bars[["time", "close", "volume"]].tail()
Source code in src/iranquant/market/live.py
async def get_intraday_trades(
    client: AsyncHTTPClient,
    ins_code: str,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch intraday OHLCV bars for the current/last trading session.

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

    Returns:
        One row per intraday bar, in server order, with these columns:

        * ``time`` (``datetime.time | None``) — bar time from ``hEven``.
        * ``open`` (``float``) — first price in the bar.
        * ``high`` (``float``) — highest price in the bar.
        * ``low`` (``float``) — lowest price in the bar.
        * ``close`` (``float``) — last price in the bar.
        * ``volume`` (``float``) — traded volume in the bar.

    Raises:
        NetworkError: If the endpoint cannot be reached.
        ParseError: If the response body is not valid JSON.
        pydantic.ValidationError: If the payload does not match the schema.

    Examples:
        >>> bars = await get_intraday_trades(client, "46348559193224090")
        >>> bars[["time", "close", "volume"]].tail()
    """

    payload = await client.get_json(TRADE_INTRADAY_URL.format(ins_code=ins_code))
    response = TradeIntraDayResponse.model_validate(payload)

    records = [
        {
            "time": int_to_time_optional(bar.hEven),
            "open": bar.openPrice,
            "high": bar.maxPrice,
            "low": bar.minPrice,
            "close": bar.closePrice,
            "volume": bar.volume,
        }
        for bar in response.tradeIntraDay
    ]
    return to_dataframe(records, engine)

Indices

index

Live and historical index data (overall, equal-weight and sector indices).

EQUAL_WEIGHT_INDEX_CODE module-attribute

EQUAL_WEIGHT_INDEX_CODE = '43685683301327984'

INDEX_B1_HISTORY_URL module-attribute

INDEX_B1_HISTORY_URL = (
    TSETMC_CDN + "/api/Index/GetIndexB1History/{index_code}"
)

INDEX_B2_HISTORY_URL module-attribute

INDEX_B2_HISTORY_URL = (
    TSETMC_CDN + "/api/Index/GetIndexB2History/{index_code}"
)

INDEX_SECTORS_LIVE_URL module-attribute

INDEX_SECTORS_LIVE_URL = (
    TSETMC_CDN + "/api/Index/GetIndexB1LastAll/0/1"
)

MARKET_OVERVIEW_URL module-attribute

MARKET_OVERVIEW_URL = (
    TSETMC_CDN + "/api/MarketData/GetMarketOverview/{flow}"
)

OVERALL_INDEX_CODE module-attribute

OVERALL_INDEX_CODE = '32097828799138957'

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

Engine module-attribute

Engine = Literal['pandas', 'polars']

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()

NetworkError

Bases: IranQuantError

Raised when a remote endpoint cannot be reached or returns an error.

Wraps connection failures, timeouts, HTTP error statuses and exhausted retries from TSETMC or Codal.

to_dataframe

to_dataframe(
    records: list[dict[str, Any]], engine: Engine = "pandas"
) -> DataFrame

Convert a list of record dictionaries to a Pandas or Polars DataFrame.

An empty records list still produces a valid (empty) DataFrame for both engines. Column order follows the key insertion order of the first record.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

Row-oriented records, typically produced by the market and Codal modules. Every record should share the same keys.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Name Type Description
A DataFrame

class:pandas.DataFrame or :class:polars.DataFrame matching

DataFrame

engine.

Raises:

Type Description
ValueError

If engine is neither "pandas" nor "polars".

Examples:

>>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
   symbol   close
0   فولاد  4150.0
>>> to_dataframe([], engine="polars").height
0
Source code in src/iranquant/core/dataframe.py
def to_dataframe(records: list[dict[str, Any]], engine: Engine = "pandas") -> DataFrame:
    """Convert a list of record dictionaries to a Pandas or Polars DataFrame.

    An empty ``records`` list still produces a valid (empty) DataFrame for both
    engines.  Column order follows the key insertion order of the first record.

    Args:
        records: Row-oriented records, typically produced by the market and
            Codal modules.  Every record should share the same keys.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A :class:`pandas.DataFrame` or :class:`polars.DataFrame` matching
        ``engine``.

    Raises:
        ValueError: If ``engine`` is neither ``"pandas"`` nor ``"polars"``.

    Examples:
        >>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
           symbol   close
        0   فولاد  4150.0
        >>> to_dataframe([], engine="polars").height
        0
    """

    if engine == "polars":
        return pl.DataFrame(records)
    if engine == "pandas":
        return cast(pd.DataFrame, pd.DataFrame(records))
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

int_to_date_optional

int_to_date_optional(d_even: int | None) -> dt.date | None

Convert a TSETMC dEven to a date, returning None for sentinels.

Values such as 0 and 1 are emitted for inactive/expired instruments and placeholder rows. Anything outside [19000101, 21001231] — or not a valid calendar date — yields None instead of raising.

Parameters:

Name Type Description Default
d_even int | None

An eight-digit Gregorian date encoded as an integer, or None.

required

Returns:

Type Description
date | None

The decoded :class:datetime.date, or None for sentinel or invalid

date | None

values.

Examples:

>>> int_to_date_optional(20261028)
datetime.date(2026, 10, 28)
>>> int_to_date_optional(0) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_date_optional(d_even: int | None) -> dt.date | None:
    """Convert a TSETMC ``dEven`` to a date, returning ``None`` for sentinels.

    Values such as ``0`` and ``1`` are emitted for inactive/expired instruments
    and placeholder rows.  Anything outside ``[19000101, 21001231]`` — or not a
    valid calendar date — yields ``None`` instead of raising.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer, or ``None``.

    Returns:
        The decoded :class:`datetime.date`, or ``None`` for sentinel or invalid
        values.

    Examples:
        >>> int_to_date_optional(20261028)
        datetime.date(2026, 10, 28)
        >>> int_to_date_optional(0) is None
        True
    """

    if d_even is None:
        return None
    try:
        value = int(d_even)
    except (TypeError, ValueError):
        return None
    if not MIN_EVEN_DATE <= value <= MAX_EVEN_DATE:
        return None
    try:
        return int_to_date(value)
    except ParseError:
        return None

int_to_jdate_optional

int_to_jdate_optional(d_even: int | None) -> str | None

Jalali counterpart of :func:int_to_date_optional.

Parameters:

Name Type Description Default
d_even int | None

An eight-digit Gregorian date encoded as an integer, or None.

required

Returns:

Type Description
str | None

The Jalali date as "YYYY-MM-DD", or None for sentinel values.

Examples:

>>> int_to_jdate_optional(1) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_jdate_optional(d_even: int | None) -> str | None:
    """Jalali counterpart of :func:`int_to_date_optional`.

    Args:
        d_even: An eight-digit Gregorian date encoded as an integer, or ``None``.

    Returns:
        The Jalali date as ``"YYYY-MM-DD"``, or ``None`` for sentinel values.

    Examples:
        >>> int_to_jdate_optional(1) is None
        True
    """

    gregorian = int_to_date_optional(d_even)
    if gregorian is None:
        return None
    jalali = jdatetime.date.fromgregorian(date=gregorian)
    return str(jalali.strftime("%Y-%m-%d"))

int_to_time_optional

int_to_time_optional(h_even: int | None) -> dt.time | None

Convert a TSETMC hEven to a time, returning None when invalid.

Parameters:

Name Type Description Default
h_even int | None

A HHMMSS time encoded as an integer, or None.

required

Returns:

Type Description
time | None

The decoded :class:datetime.time, or None when the value is not a

time | None

valid time between 00:00:00 and 23:59:59.

Examples:

>>> int_to_time_optional(91500)
datetime.time(9, 15)
>>> int_to_time_optional(999999) is None
True
Source code in src/iranquant/core/normalizer.py
def int_to_time_optional(h_even: int | None) -> dt.time | None:
    """Convert a TSETMC ``hEven`` to a time, returning ``None`` when invalid.

    Args:
        h_even: A ``HHMMSS`` time encoded as an integer, or ``None``.

    Returns:
        The decoded :class:`datetime.time`, or ``None`` when the value is not a
        valid time between ``00:00:00`` and ``23:59:59``.

    Examples:
        >>> int_to_time_optional(91500)
        datetime.time(9, 15)
        >>> int_to_time_optional(999999) is None
        True
    """

    if h_even is None:
        return None
    try:
        value = int(h_even)
    except (TypeError, ValueError):
        return None
    if not 0 <= value <= 235959:
        return None
    try:
        return int_to_time(value)
    except ParseError:
        return None

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())

_to_float

_to_float(value: Any) -> float | None
Source code in src/iranquant/market/index.py
def _to_float(value: Any) -> float | None:
    if value is None:
        return None
    try:
        return float(value)
    except (TypeError, ValueError):
        return None

_extract_items

_extract_items(
    payload: Any, preferred_keys: tuple[str, ...]
) -> list[dict[str, Any]]
Source code in src/iranquant/market/index.py
def _extract_items(payload: Any, preferred_keys: tuple[str, ...]) -> list[dict[str, Any]]:
    if isinstance(payload, list):
        return [item for item in payload if isinstance(item, dict)]
    if isinstance(payload, dict):
        for key in preferred_keys:
            value = payload.get(key)
            if isinstance(value, list):
                return [item for item in value if isinstance(item, dict)]
        for value in payload.values():
            if isinstance(value, list) and value and isinstance(value[0], dict):
                return [item for item in value if isinstance(item, dict)]
    return []

_normalize_index

_normalize_index(item: dict[str, Any]) -> dict[str, Any]

Standardize an index row from either the live or history endpoints.

Source code in src/iranquant/market/index.py
def _normalize_index(item: dict[str, Any]) -> dict[str, Any]:
    """Standardize an index row from either the live or history endpoints."""

    record = dict(item)
    even_date = record.get("dEven")
    parsed_date = int_to_date_optional(even_date) if isinstance(even_date, int) else None
    record["index_code"] = str(record.get("insCode") or "")
    record["name"] = normalize_persian(str(record.get("lVal30") or ""))
    record["index_value"] = _to_float(record.get("xDrNivJIdx004"))
    if record["index_value"] is None:
        record["index_value"] = _to_float(record.get("xNivInuClMresIbs"))
    record["change"] = _to_float(record.get("indexChange"))
    record["change_pct"] = _to_float(record.get("xVarIdxJRfV"))
    record["date"] = parsed_date
    record["jdate"] = int_to_jdate_optional(even_date) if parsed_date else None
    record["time"] = int_to_time_optional(record.get("hEven"))
    return record

get_indices_live async

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

Fetch live overall, equal-weight and sector index snapshots.

Uses MarketData/GetMarketOverview/1 for the overall and equal-weight indices and Index/GetIndexB1LastAll/0/1 for sector indices. The two requests run concurrently; if one fails but the other returns data, the partial result is returned.

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

A frame with at least the following standardized columns:

DataFrame
  • index_code (str) — TSETMC index code.
DataFrame
  • name (str) — index name (Persian).
DataFrame
  • index_value (float | None) — current index value.
DataFrame
  • change (float | None) — absolute change.
DataFrame
  • change_pct (float | None) — percentage change.
DataFrame
  • date (datetime.date | None) — date, when reported.
DataFrame
  • jdate (str | None) — Jalali date, when reported.
DataFrame
  • time (datetime.time | None) — last update time.
DataFrame

Rows for the overall (OVERALL_INDEX_CODE) and equal-weight

DataFrame

(EQUAL_WEIGHT_INDEX_CODE) indices additionally contain

DataFrame

market_state and market_state_title. Sector rows keep every

DataFrame

extra raw TSETMC field alongside the standardized columns.

Raises:

Type Description
NetworkError

If both requests fail and no rows can be produced.

Examples:

>>> indices = await get_indices_live(client)
>>> indices[["index_code", "name", "index_value"]].head()
Source code in src/iranquant/market/index.py
async def get_indices_live(
    client: AsyncHTTPClient,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch live overall, equal-weight and sector index snapshots.

    Uses ``MarketData/GetMarketOverview/1`` for the overall and equal-weight
    indices and ``Index/GetIndexB1LastAll/0/1`` for sector indices.  The two
    requests run concurrently; if one fails but the other returns data, the
    partial result is returned.

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

    Returns:
        A frame with at least the following standardized columns:

        * ``index_code`` (``str``) — TSETMC index code.
        * ``name`` (``str``) — index name (Persian).
        * ``index_value`` (``float | None``) — current index value.
        * ``change`` (``float | None``) — absolute change.
        * ``change_pct`` (``float | None``) — percentage change.
        * ``date`` (``datetime.date | None``) — date, when reported.
        * ``jdate`` (``str | None``) — Jalali date, when reported.
        * ``time`` (``datetime.time | None``) — last update time.

        Rows for the overall (``OVERALL_INDEX_CODE``) and equal-weight
        (``EQUAL_WEIGHT_INDEX_CODE``) indices additionally contain
        ``market_state`` and ``market_state_title``.  Sector rows keep every
        extra raw TSETMC field alongside the standardized columns.

    Raises:
        NetworkError: If both requests fail and no rows can be produced.

    Examples:
        >>> indices = await get_indices_live(client)
        >>> indices[["index_code", "name", "index_value"]].head()
    """

    results = await asyncio.gather(
        client.get_json(MARKET_OVERVIEW_URL.format(flow=1)),
        client.get_json(INDEX_SECTORS_LIVE_URL),
        return_exceptions=True,
    )
    overview_result: Any = results[0]
    sectors_result: Any = results[1]

    records: list[dict[str, Any]] = []
    errors: list[BaseException] = []

    if isinstance(overview_result, BaseException):
        errors.append(overview_result)
    else:
        overview = overview_result.get("marketOverview")
        if isinstance(overview, dict):
            overview_rows = (
                (
                    OVERALL_INDEX_CODE,
                    "شاخص کل",
                    "indexLastValue",
                    "indexChange",
                ),
                (
                    EQUAL_WEIGHT_INDEX_CODE,
                    "شاخص هم‌وزن",
                    "indexEqualWeightedLastValue",
                    "indexEqualWeightedChange",
                ),
            )
            for code, name, value_key, change_key in overview_rows:
                value = _to_float(overview.get(value_key))
                if value is None:
                    continue
                records.append(
                    {
                        "index_code": code,
                        "name": name,
                        "index_value": value,
                        "change": _to_float(overview.get(change_key)) or 0.0,
                        "change_pct": None,
                        "date": None,
                        "jdate": None,
                        "time": None,
                        "market_state": overview.get("marketState"),
                        "market_state_title": normalize_persian(
                            str(overview.get("marketStateTitle") or "")
                        ),
                    }
                )

    if isinstance(sectors_result, BaseException):
        errors.append(sectors_result)
    else:
        records.extend(
            _normalize_index(item) for item in _extract_items(sectors_result, ("indexB1",))
        )

    if not records and errors:
        raise NetworkError("Unable to fetch any live index data") from errors[0]

    return to_dataframe(records, engine)

get_index_history async

get_index_history(
    client: AsyncHTTPClient,
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch historical daily values for an index code.

Falls back to the B1 endpoint when the B2 endpoint is unavailable. Rows are sorted ascending by date; rows without a parseable date sort first.

Parameters:

Name Type Description Default
client AsyncHTTPClient

An open :class:~iranquant.core.client.AsyncHTTPClient.

required
index_code str

TSETMC index code. Defaults to :data:iranquant.config.OVERALL_INDEX_CODE (شاخص کل).

OVERALL_INDEX_CODE
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

A frame with the same standardized columns as

DataFrame

func:get_indices_live (index_code, name, index_value,

DataFrame

change, change_pct, date, jdate, time) plus the raw

DataFrame

upstream fields (for example xNivInuClMresIbs and hEven).

Raises:

Type Description
NetworkError

If both the B2 and B1 endpoints fail.

ParseError

If a returned body is not valid JSON.

ValueError

If engine is unsupported.

Examples:

>>> overall = await get_index_history(client)
>>> overall[["date", "index_value"]].tail()
>>> equal = await get_index_history(
...     client, EQUAL_WEIGHT_INDEX_CODE, engine="polars"
... )
Source code in src/iranquant/market/index.py
async def get_index_history(
    client: AsyncHTTPClient,
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch historical daily values for an index code.

    Falls back to the B1 endpoint when the B2 endpoint is unavailable.  Rows
    are sorted ascending by ``date``; rows without a parseable date sort first.

    Args:
        client: An open :class:`~iranquant.core.client.AsyncHTTPClient`.
        index_code: TSETMC index code.  Defaults to
            :data:`iranquant.config.OVERALL_INDEX_CODE` (شاخص کل).
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A frame with the same standardized columns as
        :func:`get_indices_live` (``index_code``, ``name``, ``index_value``,
        ``change``, ``change_pct``, ``date``, ``jdate``, ``time``) plus the raw
        upstream fields (for example ``xNivInuClMresIbs`` and ``hEven``).

    Raises:
        NetworkError: If both the B2 and B1 endpoints fail.
        ParseError: If a returned body is not valid JSON.
        ValueError: If ``engine`` is unsupported.

    Examples:
        >>> overall = await get_index_history(client)
        >>> overall[["date", "index_value"]].tail()
        >>> equal = await get_index_history(
        ...     client, EQUAL_WEIGHT_INDEX_CODE, engine="polars"
        ... )
    """

    b2_url = INDEX_B2_HISTORY_URL.format(index_code=index_code)
    try:
        payload = await client.get_json(b2_url)
    except NetworkError:
        payload = await client.get_json(INDEX_B1_HISTORY_URL.format(index_code=index_code))

    items = _extract_items(payload, ("indexB2", "indexB1"))
    records = [_normalize_index(item) for item in items]
    records.sort(key=lambda row: row["date"] or dt.date.min)

    if engine == "polars":
        return pl.DataFrame(records)
    if engine == "pandas":
        return to_dataframe(records, "pandas")
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")