Metadata-Version: 2.4
Name: HedgeTech
Version: 0.4.1
Summary: A unified, high-performance API layer that powers all trading infrastructure across the HedgeTech ecosystem, providing modular, scalable, and real-time interfaces for market data, order management, and execution systems.
Author-email: "hedgetech.ir" <info@hedgetech.ir>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2025 HedgeTech
           Licensed under the Apache License, Version 2.0
Project-URL: Homepage, https://hedgetech.ir/landing/
Project-URL: Documentation, https://gitea.hedgetech.ir/HedgeTech/HedgeTech/src/branch/main/README.md
Project-URL: Repository, https://gitea.hedgetech.ir/HedgeTech/HedgeTech
Project-URL: Store, https://store.hedgetech.ir/
Project-URL: LinkedIn, https://www.linkedin.com/company/hedgetech-ir/
Keywords: hedge,finance,financial-markets,stocks,equities,trading,algo-trading,algorithmic-trading,automated-trading,oms,order-management-system,execution,orderbook,real-time,high-frequency,portfolio-management,risk-management,market-data,exchange-api,sdk,python,async,websocket
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: System :: Networking
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: httpx[http2]<=0.28.1
Requires-Dist: brotli<=1.2.0
Requires-Dist: zstd<=1.5.7.2
Requires-Dist: PyJWT<=2.10.1
Requires-Dist: websockets<=15.0.1
Requires-Dist: pillow<=12.0.0
Dynamic: license-file

<div align="center">

# HedgeTech Python SDK

**Market data, live streaming and order execution for the Iranian capital & commodity markets — one SDK for [`core.hedgetech.ir`](https://core.hedgetech.ir).**

[Overview](#1-overview) ·
[Installation](#3-installation) ·
[Quick Start](#4-quick-start) ·
[Data Engine](#6-data-engine--ime-iran-mercantile-exchange) ·
[EMS](#9-ems-engine--order-execution) ·
[Algo-Trading Tutorial](#10-algorithmic-trading-tutorial) ·
[Support](#14-support--contact)

</div>

---

## Table of Contents

1. [Overview](#1-overview)
2. [Architecture & Package Map](#2-architecture--package-map)
3. [Installation](#3-installation)
4. [Quick Start](#4-quick-start)
5. [Authentication (`Auth`)](#5-authentication-auth)
6. [Data Engine — IME (Iran Mercantile Exchange)](#6-data-engine--ime-iran-mercantile-exchange)
7. [Data Engine — TSE-IFB (Tehran Stock Exchange & Iran Fara Bourse)](#7-data-engine--tse-ifb-tehran-stock-exchange--iran-fara-bourse)
8. [Live Streaming with WebSockets](#8-live-streaming-with-websockets)
   - [8.1 How streaming works](#81-how-streaming-works)
   - [8.2 Message anatomy](#82-message-anatomy)
   - [8.3 Choosing channels (TSE-IFB)](#83-choosing-channels-tse-ifb)
   - [8.4 Async stream with a stop switch](#84-async-stream-with-a-stop-switch)
   - [8.5 TSE-IFB, several channels at once](#85-tse-ifb-several-channels-at-once)
   - [8.6 Sync stream](#86-sync-stream)
   - [8.7 Behavior you must know](#87-behavior-you-must-know)
   - [8.8 Pattern — keep only the latest state (conflation)](#88-pattern--keep-only-the-latest-state-conflation)
   - [8.9 Pattern — producer / consumer with a queue](#89-pattern--producer--consumer-with-a-queue)
   - [8.10 Pattern — a production-grade reconnecting stream](#810-pattern--a-production-grade-reconnecting-stream)
   - [8.11 Pattern — several streams at once](#811-pattern--several-streams-at-once)
   - [8.12 Pattern — route TSE-IFB channels with a dispatch table](#812-pattern--route-tse-ifb-channels-with-a-dispatch-table)
   - [8.13 Pattern — sync streams in threads](#813-pattern--sync-streams-in-threads)
   - [8.14 Pattern — WebSocket for reaction, REST for confirmation](#814-pattern--websocket-for-reaction-rest-for-confirmation)
   - [8.15 Streaming troubleshooting](#815-streaming-troubleshooting)
9. [EMS Engine — Order Execution](#9-ems-engine--order-execution)
10. [Algorithmic Trading Tutorial](#10-algorithmic-trading-tutorial)
   - [The shape of every trading bot](#the-shape-of-every-trading-bot)
   - [From Data to Execution — The Decision Pipeline](#from-data-to-execution--the-decision-pipeline)
      - [The shared kit (stages 2–6)](#the-shared-kit-stages-26)
      - [Writing rules](#writing-rules)
      - [Part A — Socket mode: data pushed by the Data Engine](#part-a--socket-mode-data-pushed-by-the-data-engine)
      - [Part B — Request mode: data requested on a schedule](#part-b--request-mode-data-requested-on-a-schedule)
      - [Part C — The same pipeline on TSE-IFB: merging channels](#part-c--the-same-pipeline-on-tse-ifb-merging-channels)
      - [Part D — The same flow with the synchronous clients](#part-d--the-same-flow-with-the-synchronous-clients)
      - [Part E — Dry run, audit trail and going live](#part-e--dry-run-audit-trail-and-going-live)
   - [Tutorial 1 — Research: moving-average crossover on historical data (TSE-IFB)](#tutorial-1--research-moving-average-crossover-on-historical-data-tse-ifb)
   - [Tutorial 2 — Live monitoring: best bid/ask spread watcher (IME)](#tutorial-2--live-monitoring-best-bidask-spread-watcher-ime)
   - [Tutorial 3 — Risk-aware execution: place an order inside the allowed price range (IME)](#tutorial-3--risk-aware-execution-place-an-order-inside-the-allowed-price-range-ime)
   - [Tutorial 4 — Order management loop: chase the market, then cancel](#tutorial-4--order-management-loop-chase-the-market-then-cancel)
   - [Tutorial 5 — Strategy sketch: scanning IME options for box-spread edges](#tutorial-5--strategy-sketch-scanning-ime-options-for-box-spread-edges)
   - [Tutorial 6 — Putting it together: a minimal live bot skeleton](#tutorial-6--putting-it-together-a-minimal-live-bot-skeleton)
   - [Production checklist](#production-checklist)
11. [Data Conventions](#11-data-conventions)
12. [Error Handling & Reliability](#12-error-handling--reliability)
13. [API Reference (Cheat-Sheet)](#13-api-reference-cheat-sheet)
14. [Support & Contact](#14-support--contact)
15. [Disclaimer](#15-disclaimer)

---

## 1. Overview

The HedgeTech SDK is the official Python client for the **HedgeTech Core platform** (`core.hedgetech.ir`). It gives algorithmic-trading developers a single, typed, consistent interface to:

| Capability | What you get |
|---|---|
| **Authentication** | JWT login, authenticated HTTP/2 client with automatic retries |
| **Data Engine (IME)** | Static metadata, live snapshots and live WebSocket streams for **IME futures, options and deposit certificates** |
| **Data Engine (TSE-IFB)** | Static metadata, live snapshots, order book, OHLCV (live & historical), corporate actions and WebSocket streams for **stocks, funds, treasury bonds, stock options and stock futures** |
| **EMS Engine** | Broker (OMS) login with CAPTCHA, then **send / edit / query / cancel orders** on IME and TSE-IFB |

### Highlights

- **Async and sync twins.** Every client exists as an `…AsyncClient` (built on `asyncio`) and a `…SyncClient` (blocking). Endpoints, arguments and return types are identical — only the calling style differs.
- **Fully typed responses.** All responses are `TypedDict`s, so your IDE auto-completes every field.
- **By name or by ID.** Nearly every endpoint has a `*_by_name` variant and a `*_by_id` (IME) / `*_by_isin` (TSE-IFB) variant.
- **Data → decision → execution.** A complete, tested pipeline pattern: stream or request data, let conditions decide, pass a risk guard, execute and follow the order ([see §10](#from-data-to-execution--the-decision-pipeline)).
- **Streaming built in.** WebSocket methods are plain generators (`async for` / `for`) with a built-in stop switch.
- **Production-minded HTTP stack.** HTTP/2, strict TLS verification, short timeouts and up to 10 automatic retries.

> **Who is this for?** Quant developers, trading-bot authors and fintech teams who need low-friction access to Iranian market data and order routing from Python.

---

## 2. Architecture & Package Map

```mermaid
flowchart LR
    A[Your strategy] --> B[AuthAsyncClient / AuthSyncClient]
    B -->|JWT + HTTP/2 client| C[Data Engine IME]
    B --> D[Data Engine TSE-IFB]
    B --> E[EMS Engine IME]
    B --> F[EMS Engine TSE-IFB]
    C & D & E & F --> G[(core.hedgetech.ir)]
```

Everything starts with an authenticated **Auth client**. You create it once and hand it to every other client; they reuse its HTTP session and token.

| Client class | Async | Sync | Purpose |
|---|---|---|---|
| `AuthAsyncClient` / `AuthSyncClient` | ✅ | ✅ | Login, token, authenticated HTTP client |
| `DataEngine_Ime_AsyncClient` / `…_SyncClient` | ✅ | ✅ | IME market data (REST + WebSocket) |
| `DataEngine_TseIfb_AsyncClient` / `…_SyncClient` | ✅ | ✅ | TSE-IFB market data (REST + WebSocket) |
| `EmsEngine_Ime_AsyncClient` / `…_SyncClient` | ✅ | ✅ | IME order execution |
| `EmsEngine_TseIfb_AsyncClient` / `…_SyncClient` | ✅ | ✅ | TSE-IFB order execution |
| `Order` | ✅ | ✅ | A single order: `send`, `Edit`, `Status`, `Delete` |

**Which flavour should I use?**

- Use the **Async** clients for bots that watch many instruments, stream data and place orders concurrently (recommended for trading systems).
- Use the **Sync** clients for scripts, notebooks, research and simple cron-style jobs.

---

## 3. Installation

**Requirements**

- Python **3.10 or newer** (the SDK uses `match` statements and `X | Y` type unions)
- Network access to `core.hedgetech.ir` (HTTPS and WSS)
- A HedgeTech account (see [Support & Contact](#14-support--contact))

**Install**

```bash
pip install hedgetech
```

The SDK depends on `httpx` (with HTTP/2 support), `websockets`, `PyJWT` and `Pillow`. They are installed automatically; to install them by hand:

```bash
pip install "httpx[http2]" websockets PyJWT Pillow
```

**Imports used throughout this guide**

```python
from HedgeTech.Auth import AuthAsyncClient, AuthSyncClient
from HedgeTech.Data.IME import DataEngine_Ime_AsyncClient, DataEngine_Ime_SyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient, DataEngine_TseIfb_SyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_AsyncClient, EmsEngine_Ime_SyncClient
from HedgeTech.EMS.TseIfb import EmsEngine_TseIfb_AsyncClient, EmsEngine_TseIfb_SyncClient
```

---

## 4. Quick Start

### Async

```python
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient


async def main():
    # 1) Log in once.
    auth = await AuthAsyncClient.login(
        UserName_or_Email="user@example.com",
        Password="secure_password",
    )

    # 2) Create the data client.
    data = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)

    # 3) Ask for the best bid/ask of a symbol.
    response = await data.live_best_limit_by_name(["فملی"])
    level_1 = response["Data"]["فملی"]["1"]
    print("bid:", level_1["buy_price"], "ask:", level_1["sell_price"])


asyncio.run(main())
```

### Sync

```python
from HedgeTech.Auth import AuthSyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_SyncClient

auth = AuthSyncClient.login(
    UserName_or_Email="user@example.com",
    Password="secure_password",
)
data = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth)

response = data.live_best_limit_by_name(["فملی"])
level_1 = response["Data"]["فملی"]["1"]
print("bid:", level_1["buy_price"], "ask:", level_1["sell_price"])
```

> **Note.** Keyword arguments are the safest way to call every method: a few sync methods are keyword-only, and the async/sync twins otherwise share the same signatures.

---

## 5. Authentication (`Auth`)

`AuthAsyncClient.login(...)` / `AuthSyncClient.login(...)` sends your credentials to `POST https://core.hedgetech.ir/auth/user/token/issue`. On success (HTTP `201`) the server returns a JWT, and the SDK builds an authenticated client for you.

```python
auth = await AuthAsyncClient.login(
    UserName_or_Email="user@example.com",
    Password="secure_password",
)

auth.token["Authorization"][:10]   # 'eyJ0eXAiOi'
auth.Permissions                   # decoded JWT claims, e.g. {'sub': ..., 'exp': ...}
auth.httpx_Client                  # the authenticated HTTP client (retry-wrapped)
```

### What the login builds for you

| Property | Value |
|---|---|
| HTTP client | `RetriableAsyncClient` / `RetriableSyncClient` — up to **10 retries** |
| Protocol | **HTTP/2 only**, TLS verification enabled |
| Timeouts | connect `0.25 s`, read `1.5 s`, write `1.5 s`, pool `0.25 s` |
| Headers | the token returned by the server + `origin: https://core.hedgetech.ir` |
| Cookies | the cookies set at login are kept |

### Good to know

- **No automatic token refresh.** When the JWT expires, requests start to fail. Call `login(...)` again and recreate your clients with the new auth object.
- **`Permissions` is for display only.** It is decoded **without** verifying the signature or the expiry, so never use it for security decisions.
- **`UpdatePermission` is a property.** Reading `auth.UpdatePermission` (no parentheses) re-decodes `auth.token`.
- **Errors.** A failed login (status other than `201`) raises `ValueError` carrying the server's `detail`. Network failures are raised by `httpx` unchanged.

```python
try:
    auth = await AuthAsyncClient.login(UserName_or_Email="user", Password="wrong")
except ValueError as error:
    print("Login failed:", error)
```

---

## 6. Data Engine — IME (Iran Mercantile Exchange)

`DataEngine_Ime_AsyncClient` / `DataEngine_Ime_SyncClient` wrap `core.hedgetech.ir/data-engine/ime`.

```python
ime = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
```

The endpoints fall into three families:

| Family | Methods | Returns |
|---|---|---|
| **Static data** (rarely changes) | `search_contracts`, `contracts_static_info_by_name`, `contracts_static_info_by_id` | `Contracts` |
| **Live snapshots** (one REST call) | `live_overview_*`, `live_best_limit_*`, `live_aggregate_*`, `live_contract_info_*`, `live_allowed_price_range_*` | `…Response` |
| **Live streams** (WebSocket) | `websocket_by_name`, `websocket_by_id` | generator of messages |

Every REST method except `search_contracts` comes in two flavours: `*_by_name` (`contractName`, e.g. `"KASH05C170"`) and `*_by_id` (`contractId`; `int` values are accepted).

### Step 1 — Find contracts

```python
result = await ime.search_contracts(
    market="IMEOption",          # "IMEOption" | "IMEFutures" | "IMEDepositCertificate"
    Search_char="KASH05C",
)
names = [item["contractName"] for item in result["Data"] if item]
```

### Step 2 — Read static metadata

```python
info = await ime.contracts_static_info_by_name(["KASH05C170"])
contract = info["Data"][0]          # None if the contract was not found
print(contract["strikePrice"], contract["ExpirationDate"], contract["csize"])
print(contract["buyCommission"], contract["sellCommission"])   # fractions: 0.0025 = 0.25 %
```

### Step 3 — Take live snapshots

```python
names = ["KASH05C170", "KASH05P170"]

best      = await ime.live_best_limit_by_name(names)           # 3 depth levels
agg       = await ime.live_aggregate_by_name(names)            # OHLC, volume, last price...
price_rng = await ime.live_allowed_price_range_by_name(names)  # min/max allowed price
oi        = await ime.live_contract_info_by_name(names)        # open interest
everything = await ime.live_overview_by_name(names)            # static + all of the above

best["Data"]["KASH05C170"]["1"]          # {'buy_quantity', 'buy_price', 'sell_quantity', 'sell_price'}
agg["Data"]["KASH05C170"]["last_price"]
price_rng["Data"]["KASH05C170"]          # {'minAllowedPrice', 'maxAllowedPrice'}
oi["Data"]["KASH05C170"]["open_interest"]
```

| Snapshot | Key fields |
|---|---|
| `BestLimit` (levels `"1"`–`"3"`) | `buy_quantity`, `buy_price`, `sell_quantity`, `sell_price` |
| `Aggregate` | `date`, `time`, `trade_count`, `total_volume`, `total_value`, `closing_price`, `last_price`, `low_price`, `high_price`, `open_price`, `previous_close` |
| `AllowedPriceRange` | `minAllowedPrice`, `maxAllowedPrice` |
| `ContractInfo` | `open_interest`, `open_interest_changes` |

### Step 4 — Stream live data

See [Live Streaming with WebSockets](#8-live-streaming-with-websockets).

### Sync usage

```python
ime = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
best = ime.live_best_limit_by_name(["KASH05C170"])
```

---

## 7. Data Engine — TSE-IFB (Tehran Stock Exchange & Iran Fara Bourse)

`DataEngine_TseIfb_AsyncClient` / `DataEngine_TseIfb_SyncClient` wrap `core.hedgetech.ir/data-engine/tse-ifb`.

```python
tse = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)
```

| Family | Methods |
|---|---|
| **Static data** | `search_instruments`, `instruments_static_info_by_name`, `instruments_static_info_by_isin` |
| **Live snapshots** | `live_overview_*`, `live_best_limit_*`, `live_order_book_*`, `live_aggregate_*`, `live_institutional_vs_individual_*`, `live_contract_info_*`, `live_fund_info_*`, `live_ohlcv_last1m_*` |
| **Historical** | `historical_ohlcv_*`, `historical_corporateactions_*` |
| **Live streams** | `websocket_by_name`, `websocket_by_isin` |

Every method above (except `search_instruments`) comes in `*_by_name` and `*_by_isin` flavours.

### Search and static info

```python
found = await tse.search_instruments(
    market="SecuritiesAndFunds",   # | "TreasuryBonds" | "StockOptions" | "StockFutures"
    Search_char="فولاد",
)
print(found["Data"][0]["symbolName"])

info = await tse.instruments_static_info_by_name(["فملی", "خودرو"])
for item in info["Data"]:
    if item:                                  # None when a symbol was not found
        print(item["symbolName"], item["minAllowedPrice"], item["maxAllowedPrice"])
```

### Live snapshots

```python
symbols = ["فملی", "خودرو"]

best  = await tse.live_best_limit_by_name(symbols)              # 6 depth levels
book  = await tse.live_order_book_by_name(symbols)              # full order book
agg   = await tse.live_aggregate_by_name(symbols)
flows = await tse.live_institutional_vs_individual_by_name(symbols)
ohlcv = await tse.live_ohlcv_last1m_by_name(symbols)            # last 1-minute candle
fund  = await tse.live_fund_info_by_name(["اهرم"])               # NAV, units, market cap
deriv = await tse.live_contract_info_by_name(["<option or futures symbol>"])  # open interest, margins

best["Data"]["فملی"]["1"]["buy_price"]
```

| Snapshot | Key fields |
|---|---|
| `BestLimit` (levels `"1"`–`"6"`) | `buy_order_count`, `buy_quantity`, `buy_price`, `sell_order_count`, `sell_quantity`, `sell_price` |
| `OrderBook` | `Buy` and `Sell` lists of `{price, quantity, count}` |
| `Aggregate` | same fields as IME `Aggregate` |
| `institutional_vs_individual` | `buy_count_*`, `buy_volume_*`, `sell_count_*`, `sell_volume_*` for `individual` / `institution` |
| `ContractInfo` | `open_interest`, `initial_margin`, `required_margin` |
| `FundInfo` | `nav`, `units`, `marketCap`, `as_of` |
| `OHLCV_live` | `open`, `high`, `low`, `close`, `volume` |

### Historical data

```python
import time

now = int(time.time())

candles = await tse.historical_ohlcv_by_name(
    symbol_name="فملی",
    start_timestamp=now - 90 * 24 * 3600,    # Unix seconds
    end_timestamp=now,
    AdjustedPrice=True,
    Resolution="D",                           # "1m","5m","15m","30m","1h","D","W","M"
)

data = candles["Data"]            # one object; the lists are index-aligned
for ts, o, h, l, c, v in zip(
    data["Date_timestamp"], data["Open"], data["High"],
    data["Low"], data["Close"], data["Volume"],
):
    print(ts, o, h, l, c, v)

actions = await tse.historical_corporateactions_by_name(
    symbol_name="فملی",
    start_timestamp=now - 5 * 365 * 24 * 3600,
    end_timestamp=now,
)
for action in actions["Data"]:
    print(action["corporateAction"], action["تاریخ"])
```

> Historical methods take **keyword-only** arguments. `Data` is a single object whose lists (`Date_timestamp`, `Open`, `High`, `Low`, `Close`, `Volume`) line up by index.

### Sync usage

```python
tse = DataEngine_TseIfb_SyncClient(AuthSyncClient=auth)
info = tse.instruments_static_info_by_name(["فملی"])
```

---

## 8. Live Streaming with WebSockets

Streaming methods are **generators**. Each call opens one WebSocket connection, yields every decoded message, and closes the connection when the generator finishes. The WebSocket is the lowest-latency way to receive market data: the server **pushes** updates to you, instead of you asking for them.

| Client | Method | Message structure |
|---|---|---|
| IME | `websocket_by_name(contract_names, event=None)` | `{"channel": "IME Stream", "contractName", "timestamp", "data": {BestLimit, Aggregate, AllowedPriceRange, ContractInfo}}` |
| IME | `websocket_by_id(contract_ids, event=None)` | same, keyed by `contractId` |
| TSE-IFB | `websocket_by_name(channels, symbol_names, event=None)` | `{"channel", "symbolName", "timestamp", "data"}` — one channel per message |
| TSE-IFB | `websocket_by_isin(channels, symbol_isins, event=None)` | same, keyed by `symbolIsin` |

TSE-IFB channels: `'best-limit'`, `'order-book'`, `'ohlcv-last-1m'`, `'aggregate'`, `'institutional-vs-individual'`, `'contract-info'`, `'fund-info'`.

### 8.1 How streaming works

```
 your code                       SDK generator                     core.hedgetech.ir
 ─────────                       ─────────────                     ─────────────────
 async for msg in               ┌─ connect(wss://…, headers=token) ─►  authenticate
   ime.websocket_by_name(...)   │                                      subscribe (query string)
        ▲                       │  ┌─ ws.recv() (2 s timeout) ◄──────  push update
        └── yield decoded JSON ◄┘  └─ loop while event.is_set()
                                   on error / event.clear() → close the connection, generator ends
```

Key facts:

- **One connection, many instruments.** Every contract or symbol you pass shares a single connection. Tell messages apart by `message["contractName"]` (IME) or `update["symbolName"]` + `update["channel"]` (TSE-IFB).
- **IME messages are full snapshots.** Each message carries the complete `BestLimit`, `Aggregate`, `AllowedPriceRange` and `ContractInfo` of one contract. You never have to merge partial updates: the newest message *is* the current state.
- **TSE-IFB messages are per channel.** Each message carries one channel's data for one symbol. If your logic needs several channels at once (for example best-limit and aggregate), keep a small state object per symbol and merge — see [8.12](#812-pattern--route-tse-ifb-channels-with-a-dispatch-table).
- **The stream is pulled, not buffered by you.** The generator receives the next message only when your loop asks for it. If your loop body is slow, messages queue up in the connection. Keep the loop body fast, or hand work to another task ([8.9](#89-pattern--producer--consumer-with-a-queue)).
- **The same data is available over REST.** The `data` of an IME stream message has the same four sections as one entry of `live_overview_by_name`. Code written for one source works for the other — see [the decision pipeline](#from-data-to-execution--the-decision-pipeline).

### 8.2 Message anatomy

**IME — one message (illustrative values):**

```json
{
  "channel": "IME Stream",
  "contractName": "KASH05C170",
  "timestamp": "2025-01-15T14:30:00.123456",
  "data": {
    "BestLimit": {
      "1": {"buy_quantity": 1500, "buy_price": 35200, "sell_quantity": 800, "sell_price": 35300},
      "2": {"buy_quantity": 1200, "buy_price": 35100, "sell_quantity": 600, "sell_price": 35400},
      "3": {"buy_quantity":  900, "buy_price": 35000, "sell_quantity": 400, "sell_price": 35500}
    },
    "Aggregate": {
      "date": "2025-01-15", "time": "14:30:00", "trade_count": 1250,
      "total_volume": 50000, "total_value": 1765000000,
      "closing_price": 35250.0, "last_price": 35250.0,
      "low_price": 34900.0, "high_price": 35500.0,
      "open_price": 35100.0, "previous_close": 35000.0
    },
    "AllowedPriceRange": {"minAllowedPrice": 33250.0, "maxAllowedPrice": 36750.0},
    "ContractInfo": {"open_interest": 125000, "open_interest_changes": 2500}
  }
}
```

**TSE-IFB — two messages (illustrative values):**

```json
{"channel": "best-limit", "symbolName": "فملی", "timestamp": "2025-01-15T10:15:02.481203",
 "data": {"1": {"buy_order_count": 12, "buy_quantity": 85000, "buy_price": 4210,
                "sell_order_count": 7, "sell_quantity": 40000, "sell_price": 4215}}}

{"channel": "aggregate", "symbolName": "فملی", "timestamp": "2025-01-15T10:15:03.002115",
 "data": {"last_price": 4212.0, "total_volume": 91000000, "trade_count": 5120}}
```

Remember: `timestamp` is an ISO **string**, and an empty side of the book shows `0` prices and quantities.

### 8.3 Choosing channels (TSE-IFB)

Subscribe only to what your logic reads — fewer channels means fewer messages to process.

| Channel | `data` type | Typical use |
|---|---|---|
| `best-limit` | `BestLimit_WS_*` (levels `"1"`–`"6"`) | quoting, spread and imbalance conditions, order pricing |
| `order-book` | `OrderBook_WS_*` (`Buy` / `Sell` lists) | depth analysis, queue position |
| `aggregate` | `Aggregate_WS_*` | last price, volume, OHLC of the day |
| `ohlcv-last-1m` | `OHLCV_WS_*` | intraday candle logic |
| `institutional-vs-individual` | `institutional_vs_individual_WS_*` | smart-money flow filters |
| `contract-info` | `ContractInfo_WS_*` | open interest and margins of options / futures |
| `fund-info` | `FundInfo_WS_*` | NAV vs. market price (ETF arbitrage) |

### 8.4 Async stream with a stop switch

```python
import asyncio

async def watch(ime):
    stop = asyncio.Event()
    stop.set()                       # the stream runs while the event is set

    async for message in ime.websocket_by_name(["KASH05C170"], event=stop):
        best = message["data"]["BestLimit"]["1"]
        print(message["contractName"], best["buy_price"], best["sell_price"])

        if best["buy_price"] >= 36000:
            stop.clear()             # ends the stream within ~2 seconds
```

### 8.5 TSE-IFB, several channels at once

```python
async for update in tse.websocket_by_name(
    channels=["best-limit", "aggregate"],
    symbol_names=["فملی", "خودرو"],
):
    if update["channel"] == "best-limit":
        print(update["symbolName"], update["data"]["1"]["buy_price"])
    elif update["channel"] == "aggregate":
        print(update["symbolName"], update["data"]["last_price"])
```

### 8.6 Sync stream

The sync twins are blocking generators. Use `threading.Event` as the stop switch and, ideally, run them in a dedicated thread (see [8.13](#813-pattern--sync-streams-in-threads)).

```python
import threading

stop = threading.Event()
stop.set()

for message in ime_sync.websocket_by_name(["KASH05C170"], event=stop):
    print(message["contractName"], message["data"]["Aggregate"]["last_price"])
```

### 8.7 Behavior you must know

1. **Stopping.** The loop runs while `event.is_set()`. Call `event.clear()` to stop; it takes effect within about 2 seconds (the receive timeout).
2. **Silent end after connect.** Once connected, any error (closed connection, invalid JSON, network error) closes the connection and the generator **ends without raising**. A receive timeout is not an error.
3. **Connect errors do raise.** For example, an authentication failure at connect time raises a `websockets` exception.
4. **Silence is not an error either.** If the server simply stops sending (market closed, a half-dead connection), the generator keeps waiting. Detect this yourself with a watchdog ([8.10](#810-pattern--a-production-grade-reconnecting-stream)).
5. **An expired token cannot reconnect.** Reconnecting uses the token held by the `Auth` client. After the JWT expires you must log in again and rebuild your clients.

### 8.8 Pattern — keep only the latest state (conflation)

Trading decisions need the **current** state, not every intermediate tick. Let the stream overwrite a dictionary, and let a separate loop decide at its own pace. A slow decision never delays data intake, and old ticks are discarded automatically.

```python
import asyncio

latest: dict[str, dict] = {}              # contractName -> newest message
updated = asyncio.Event()                 # "something new arrived"


async def collect(ime, names, run: asyncio.Event):
    async for message in ime.websocket_by_name(names, event=run):
        latest[message["contractName"]] = message
        updated.set()


async def decide(run: asyncio.Event):
    while run.is_set():
        try:
            await asyncio.wait_for(updated.wait(), timeout=1.0)
        except asyncio.TimeoutError:
            continue
        updated.clear()

        for name, message in list(latest.items()):
            level_1 = message["data"]["BestLimit"]["1"]
            print(name, level_1["buy_price"], level_1["sell_price"])


async def main(ime):
    run = asyncio.Event()
    run.set()
    await asyncio.gather(collect(ime, ["KASH05C170", "KASH05P170"], run), decide(run))
```

### 8.9 Pattern — producer / consumer with a queue

When you must see **every** message (logging, recording ticks to disk, event-sourced strategies), put a bounded queue between the stream and the consumer. When the queue is full, drop the oldest message so the stream is never blocked.

```python
import asyncio

queue: asyncio.Queue = asyncio.Queue(maxsize=1000)


def push(item):
    if queue.full():
        queue.get_nowait()                # drop the oldest; stale ticks are worth little
    queue.put_nowait(item)


async def producer(ime, names, run: asyncio.Event):
    try:
        async for message in ime.websocket_by_name(names, event=run):
            push(message)
    finally:
        push(None)                        # sentinel: the stream ended


async def consumer():
    while (message := await queue.get()) is not None:
        # slow work is fine here (database writes, indicators, ...)
        print(message["timestamp"], message["contractName"])


async def main(ime):
    run = asyncio.Event()
    run.set()
    await asyncio.gather(producer(ime, ["KASH05C170"], run), consumer())
```

### 8.10 Pattern — a production-grade reconnecting stream

Because streams end silently on errors and stay silent when the feed dies, a robust bot needs three things: a **reconnect loop**, **exponential back-off**, and a **watchdog** that stops a stream that has gone quiet. The watchdog uses the library's own stop switch.

```python
import asyncio
import time


async def stream_forever(open_stream, on_message, shutdown: asyncio.Event,
                         stale_after: float = 15.0, max_delay: float = 30.0):
    """
    open_stream(run_event) -> an async generator, e.g.
        lambda run: ime.websocket_by_name(names, event=run)
    on_message(message)    -> awaitable called for every message
    shutdown               -> set it to stop everything for good
    stale_after            -> seconds without messages before we reconnect
    """
    delay = 1.0

    while not shutdown.is_set():
        run = asyncio.Event()             # fresh stop switch for every connection
        run.set()
        last_seen = time.monotonic()

        async def watchdog():
            while run.is_set():
                await asyncio.sleep(1.0)
                if shutdown.is_set() or time.monotonic() - last_seen > stale_after:
                    run.clear()           # the generator ends within ~2 seconds

        guard = asyncio.create_task(watchdog())
        try:
            async for message in open_stream(run):
                last_seen = time.monotonic()
                delay = 1.0               # healthy connection: reset the back-off
                await on_message(message)
        except Exception as error:        # connect-time failures (auth, network)
            print("stream error:", repr(error))
        finally:
            run.clear()
            guard.cancel()

        if not shutdown.is_set():
            print(f"stream ended — reconnecting in {delay:.0f}s")
            await asyncio.sleep(delay)
            delay = min(delay * 2, max_delay)
```

Usage:

```python
shutdown = asyncio.Event()

async def on_message(message):
    ...                                   # keep it fast; see 8.8 / 8.9

await stream_forever(
    lambda run: ime.websocket_by_name(["KASH05C170"], event=run),
    on_message,
    shutdown,
    stale_after=20.0,
)
```

> **Market hours.** Outside trading hours a healthy connection can legitimately be quiet, which would trigger reconnects every `stale_after` seconds. Either pause your bot outside trading hours or use a large `stale_after`.

### 8.11 Pattern — several streams at once

Run IME and TSE-IFB streams side by side as independent tasks. Each one can have its own reconnect loop and its own state.

```python
async def main(ime, tse):
    shutdown = asyncio.Event()

    async def on_ime(message):
        ...

    async def on_tse(update):
        ...

    await asyncio.gather(
        stream_forever(
            lambda run: ime.websocket_by_name(["KASH05C170", "KASH05P170"], event=run),
            on_ime, shutdown,
        ),
        stream_forever(
            lambda run: tse.websocket_by_name(
                channels=["best-limit", "aggregate"],
                symbol_names=["فملی", "خودرو"],
                event=run,
            ),
            on_tse, shutdown,
        ),
    )
```

### 8.12 Pattern — route TSE-IFB channels with a dispatch table

A single TSE-IFB connection can carry several channels. A dispatch table keeps the code flat and makes adding a channel a one-line change.

```python
async def on_best_limit(update):
    level = update["data"]["1"]
    print(update["symbolName"], "bid", level["buy_price"], "ask", level["sell_price"])


async def on_aggregate(update):
    print(update["symbolName"], "last", update["data"]["last_price"])


HANDLERS = {
    "best-limit": on_best_limit,
    "aggregate": on_aggregate,
}


async def route(tse, symbols, run):
    async for update in tse.websocket_by_name(
        channels=list(HANDLERS),          # subscribe exactly to the channels you handle
        symbol_names=symbols,
        event=run,
    ):
        handler = HANDLERS.get(update["channel"])
        if handler is not None:
            await handler(update)
```

When your condition needs **several channels at once**, merge them into one state per symbol (a complete example is in [the pipeline section](#part-c--the-same-pipeline-on-tse-ifb-merging-channels)).

### 8.13 Pattern — sync streams in threads

A sync stream blocks its thread. Read it in a background thread and hand messages to your main thread through a `queue.Queue`.

```python
import queue
import threading

messages: queue.Queue = queue.Queue(maxsize=1000)
run = threading.Event()
run.set()


def reader():
    for message in ime_sync.websocket_by_name(["KASH05C170"], event=run):
        try:
            messages.put_nowait(message)
        except queue.Full:
            pass                          # drop: a newer message will follow


threading.Thread(target=reader, daemon=True).start()

try:
    while run.is_set():
        try:
            message = messages.get(timeout=1.0)
        except queue.Empty:
            continue
        level_1 = message["data"]["BestLimit"]["1"]
        print(message["contractName"], level_1["buy_price"], level_1["sell_price"])
except KeyboardInterrupt:
    run.clear()                           # the reader thread ends within ~2 seconds
```

### 8.14 Pattern — WebSocket for reaction, REST for confirmation

The stream tells you *that* the market moved; a REST snapshot confirms *the state you are about to act on*. A common, safe sequence for a trigger:

1. The stream delivers a message and your **conditions** say "act".
2. Just before sending, re-read the book with one REST call (`live_best_limit_by_name`) and re-check the condition on this fresh data.
3. Only then build and send the order.

```python
async def confirmed_trigger(ime, name, condition):
    snapshot = (await ime.live_overview_by_name([name]))["Data"][name]
    if snapshot is None:
        return False
    return condition(snapshot["BestLimit"]["1"])        # a plain function of the best level
```

This costs one extra request per trigger — negligible next to the cost of acting on stale data. The full version is in [the decision pipeline](#from-data-to-execution--the-decision-pipeline).

### 8.15 Streaming troubleshooting

| Symptom | Likely cause | What to do |
|---|---|---|
| Exception at connect (e.g. `InvalidStatus`) | token expired or invalid | log in again, rebuild the clients |
| The loop ends with no error | connection closed / network error / invalid JSON | wrap in a reconnect loop ([8.10](#810-pattern--a-production-grade-reconnecting-stream)) |
| The loop never yields | market closed, or the feed is silent | check the market hours; add a watchdog |
| Prices are `0` | empty side of the book | skip such messages in your conditions |
| Loop falls behind real time | handler too slow | conflate ([8.8](#88-pattern--keep-only-the-latest-state-conflation)) or queue ([8.9](#89-pattern--producer--consumer-with-a-queue)) |
| Stopping takes ~2 seconds | by design (receive timeout) | clear the stop event early; it is not a hang |

---

## 9. EMS Engine — Order Execution

The EMS Engine routes orders to your broker's **OMS** (order-management system). The flow is the same for IME and TSE-IFB:

```mermaid
sequenceDiagram
    participant You
    participant EMS as EmsEngine client
    participant Core as core.hedgetech.ir
    You->>EMS: Get_Captcha(OMS)
    EMS->>Core: GET .../oms/login
    Core-->>You: CAPTCHA image
    You->>EMS: oms_login(username, password, captcha_value)
    EMS->>Core: POST .../oms/login
    Core-->>EMS: oms_session
    You->>EMS: Buy_by_...()  (builds an Order, nothing sent)
    You->>EMS: order.send()
    EMS->>Core: POST .../order/new/...
    Core-->>You: OrderId
    You->>EMS: order.Status() / Edit() / Delete()
```

### 9.1 Log in to the OMS

```python
ems = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth)

captcha = await ems.Get_Captcha("Sahra | Karamad")   # PIL image
captcha.show()                                         # or captcha.save("captcha.png")

await ems.oms_login(
    username="user123",
    password="pass123",
    captcha_value=input("CAPTCHA: "),
)

print(ems.Customer_FullName, ems.oms_session)
```

- Call `Get_Captcha` and `oms_login` with the **same client**: the OMS name is not sent again at login; the session created by `Get_Captcha` is used.
- `Get_Captcha` / `oms_login` raise `ValueError` on failure (a wrong CAPTCHA or wrong credentials give HTTP `400` with the server's message).
- IME supports `'Sahra | Karamad'` and `'Sahra | Charisma'`. TSE-IFB supports `'Omex | Parsian'`, `'Omex | Khobregan'`, `'Sahra | Karamad'`, `'Sahra | NIBB'` and `'Sahra | Charisma'`.
- Constructor argument names differ between clients: async EMS clients take `AuthASyncClient=`, sync EMS clients take `AuthSyncClient=`.

### 9.2 Build, send, follow and cancel an order

`Buy_by_*` / `Sell_by_*` **only build** an `Order`. Nothing reaches the exchange until you call `order.send()`.

| Client | Order-building methods |
|---|---|
| IME | `Buy_by_ContractName`, `Sell_by_ContractName`, `Buy_by_ContractId`, `Sell_by_ContractId` |
| TSE-IFB | `Buy_by_Name`, `Sell_by_Name`, `Buy_by_isin`, `Sell_by_isin` (accept `Order_ValidityType` and `ValidityDate`) |

```python
order = await ems.Buy_by_ContractName(contractName="KASH05C170", Price=35_000, Volume=10)

if order is None:
    raise RuntimeError("No OMS session — log in first")

await order.send()                                   # submit
print(order.OrderId, order.OrderOmsId)               # None if the send failed

status = await order.Status()                        # dict, or None on failure
print(status["order_status"], status["ExecutedVolume"], status["RemainedVolume"])

await order.Edit(Price=35_500, Volume=10)            # Volume = new TOTAL volume
await order.Delete()
print(order.is_deleted, order.OrderStatus)
```

### 9.3 Order lifecycle & statuses

| `order_status` | Meaning | State |
|---|---|---|
| `InQueue` | accepted, waiting in the market queue | active |
| `PartiallyFilled` | partly executed | active |
| `Cancelled` | cancelled | final |
| `Broken` | broken / terminated by the system | final |
| `Settled` | fully executed | final |

`order.OrderStatus` starts as `'Unknown'` and is updated by `Status()`, `Delete()` and the reconciliation inside `Edit()` / `Delete()`.

### 9.4 Critical behavior of `Order`

> **`send`, `Edit`, `Status` and `Delete` never raise.** Any error (non-200 response, network failure, unexpected body) is swallowed and the method returns `None`. `send`, `Edit` and `Delete` also return `None` on success — so **always check the outcome on the attributes** (`OrderId`, `is_deleted`, `OrderStatus`, `Price`, `Volume`) or call `Status()`.

- **`send()`** submits only if `OrderId is None`. Only HTTP `200` counts as success. After a failure you can call `send()` again; the same `InitialOrderId` is sent. If a network error happened, the first request may already have reached the exchange — verify before retrying blindly.
- **`Edit()`** sends **all** arguments every time. On TSE-IFB, `Order_ValidityType` defaults to `'DAY'`, so an edit without it turns a GTC/GTD order into a DAY order — pass the current validity to keep it. `Volume` is the new **total** volume (including the executed part).
- **After a non-200 response**, `Edit()` and `Delete()` read the real state with `Status()` and reconcile the attributes, because the order may have changed state (filled, cancelled) in the meantime.
- **`Status()`** also updates `order.OrderStatus`.
- **Orders keep the session they were built with.** If you log in again, rebuild your orders.

### 9.5 TSE-IFB specifics

```python
ems = EmsEngine_TseIfb_AsyncClient(AuthASyncClient=auth)

order = await ems.Buy_by_Name(
    symbolName="اطلس",
    Price=100_000,
    Volume=10,
    Order_ValidityType="GTD",        # 'DAY' (default) | 'GTC' | 'GTD'
    ValidityDate=20271206,           # used for GTD
)
await order.send()
```

Verify the `ValidityDate` format expected by your OMS before going live.

### 9.6 Sync version

```python
ems = EmsEngine_Ime_SyncClient(AuthSyncClient=auth)
captcha = ems.Get_Captcha("Sahra | Karamad")
ems.oms_login(username="user123", password="pass123", captcha_value="abcd")

order = ems.Buy_by_ContractName(contractName="KASH05C170", Price=35_000, Volume=10)
order.send()
```

---

## 10. Algorithmic Trading Tutorial

This section walks from idea to a running bot. The examples are **educational**: they omit margin, taxes, exercise fees and risk limits that a real system must model. See the [Disclaimer](#15-disclaimer).

### The shape of every trading bot

```
 ┌──────────┐   ┌────────────┐   ┌───────────┐   ┌──────────┐   ┌─────────────┐
 │  Login   │ → │ Market data│ → │  Signal   │ → │ Risk     │ → │ Execution   │
 │  (Auth)  │   │ (Data Eng.)│   │  (yours)  │   │ checks   │   │ (EMS Engine)│
 └──────────┘   └────────────┘   └───────────┘   └──────────┘   └─────────────┘
                       ↑                                              │
                       └────────────── Status() feedback ◄────────────┘
```

### From Data to Execution — The Decision Pipeline

A trading bot is a pipeline in which **data flows in, conditions create the decision, and only then is an order executed**. Keeping these stages separate is what makes a bot testable, auditable and safe.

```
 ┌──────────────┐  ┌────────────┐  ┌──────────────┐  ┌────────────┐  ┌────────────┐  ┌──────────────┐
 │ 1. SOURCE    │→ │ 2. NORMAL- │→ │ 3. CONDITIONS│→ │ 4. DECISION│→ │ 5. RISK    │→ │ 6. EXECUTION │
 │ WebSocket or │  │    IZE     │  │ (predicates) │  │ side/price/│  │    GUARD   │  │ EMS: build,  │
 │ REST request │  │ → Quote    │  │ True / False │  │ volume     │  │ allow/deny │  │ send, follow │
 └──────────────┘  └────────────┘  └──────────────┘  └────────────┘  └────────────┘  └──────┬───────┘
        ▲                                                                                    │
        └──────────────────────── Status() / fills feed back into the guard ◄────────────────┘
```

| Stage | Responsibility | SDK pieces |
|---|---|---|
| **1. Source** | Bring data in | `websocket_by_name`, `live_overview_by_name`, `live_best_limit_by_name`, … |
| **2. Normalize** | One internal `Quote` object, whatever the source | your `to_quote()` |
| **3. Conditions** | Small pure functions: `Quote → bool` | your predicates |
| **4. Decision** | Combine conditions into *what to do* (side, price, volume) | your `Rule` |
| **5. Risk guard** | Final veto: price band, size, position limit, cooldown, one order in flight | `AllowedPriceRange`, static volume limits |
| **6. Execution** | Turn an approved decision into an exchange order and follow it | `Buy_by_*` / `Sell_by_*`, `send`, `Status`, `Edit`, `Delete` |

The rest of this section builds a small, reusable kit and then plugs the **same kit** into two different sources: a WebSocket (Part A) and periodic REST requests (Part B). Only stage 1 changes.

#### The shared kit (stages 2–6)

```python
# kit.py
import asyncio
import time
from dataclasses import dataclass
from typing import Awaitable, Callable, Literal, Optional

Side = Literal["BUY", "SELL"]


# ── Stage 2: one normalized quote ───────────────────────────────────────────
@dataclass(frozen=True)
class Quote:
    name: str
    bid: int
    bid_qty: int
    ask: int
    ask_qty: int
    last: float
    min_price: float
    max_price: float
    source: str                      # "ws" | "rest"
    received_at: float               # time.monotonic() when we received it
    open_interest: int = 0

    @property
    def valid(self) -> bool:         # both sides of the book are populated
        return self.bid > 0 and self.ask > 0 and self.ask >= self.bid

    @property
    def spread(self) -> int:
        return self.ask - self.bid

    @property
    def imbalance(self) -> float:    # share of buy quantity at level 1; 0.5 = balanced
        total = self.bid_qty + self.ask_qty
        return self.bid_qty / total if total else 0.5


def to_quote(name: str, blob: dict, source: str) -> Quote:
    """
    `blob` is the IME `data` of a WebSocket message OR one entry of
    `live_overview_by_name(...)["Data"]` — both have the same four sections.
    """
    level = blob["BestLimit"]["1"]
    return Quote(
        name=name,
        bid=int(level["buy_price"]),   bid_qty=int(level["buy_quantity"]),
        ask=int(level["sell_price"]),  ask_qty=int(level["sell_quantity"]),
        last=float(blob["Aggregate"]["last_price"]),
        min_price=float(blob["AllowedPriceRange"]["minAllowedPrice"]),
        max_price=float(blob["AllowedPriceRange"]["maxAllowedPrice"]),
        open_interest=int(blob["ContractInfo"]["open_interest"]),
        source=source,
        received_at=time.monotonic(),
    )


# ── Stage 3: conditions are small pure functions Quote -> bool ──────────────
Condition = Callable[[Quote], bool]


def fresh(max_age_s: float) -> Condition:
    return lambda q: time.monotonic() - q.received_at <= max_age_s      # never act on stale data

def spread_at_most(max_spread: int) -> Condition:
    return lambda q: q.valid and q.spread <= max_spread

def bid_at_most(limit: int) -> Condition:
    return lambda q: q.valid and q.bid <= limit

def ask_at_least(limit: int) -> Condition:
    return lambda q: q.valid and q.ask >= limit

def buy_pressure(min_share: float) -> Condition:
    return lambda q: q.valid and q.imbalance >= min_share

def sell_pressure(max_share: float) -> Condition:
    return lambda q: q.valid and q.imbalance <= max_share

def inside_price_band(margin: float = 0.0) -> Condition:
    # the quote must lie strictly inside today's allowed range, `margin` (fraction) away from the edges
    return lambda q: (q.min_price * (1 + margin) <= q.bid) and (q.ask <= q.max_price * (1 - margin))

def all_of(*conditions: Condition) -> Condition:
    return lambda q: all(c(q) for c in conditions)

def any_of(*conditions: Condition) -> Condition:
    return lambda q: any(c(q) for c in conditions)


# ── Stage 4: a rule turns "conditions hold" into a concrete decision ────────
@dataclass(frozen=True)
class Decision:
    side: Side
    price: int
    volume: int
    reason: str


@dataclass(frozen=True)
class Rule:
    name: str
    when: Condition
    side: Side
    price_from: Callable[[Quote], int]
    volume: int

    def evaluate(self, q: Quote) -> Optional[Decision]:
        if self.when(q):
            return Decision(self.side, int(self.price_from(q)), self.volume, self.name)
        return None


# ── Stage 5: the risk guard has the final word ──────────────────────────────
class RiskGuard:
    def __init__(self, *, max_volume: int, max_position: int, cooldown_s: float, max_orders: int):
        self.max_volume = max_volume
        self.max_position = max_position            # max |net filled volume| per contract
        self.cooldown_s = cooldown_s
        self.max_orders = max_orders
        self._in_flight: set[str] = set()          # one order at a time per contract
        self._last_sent: dict[str, float] = {}
        self._sent = 0
        self._position: dict[str, int] = {}        # net filled volume per contract (BUY +, SELL -)

    def check(self, q: Quote, d: Decision) -> tuple[bool, str]:
        if q.name in self._in_flight:
            return False, "an order for this contract is already working"
        if time.monotonic() - self._last_sent.get(q.name, -1e9) < self.cooldown_s:
            return False, "cooldown"
        if self._sent >= self.max_orders:
            return False, "daily order cap reached"
        if d.volume > self.max_volume:
            return False, "volume above the configured maximum"
        if not (q.min_price <= d.price <= q.max_price):
            return False, "price outside today's allowed range"
        signed = d.volume if d.side == "BUY" else -d.volume
        if abs(self._position.get(q.name, 0) + signed) > self.max_position:
            return False, "position limit"
        return True, "ok"

    def record_fill(self, name: str, side: Side, volume: int) -> None:
        self._position[name] = self._position.get(name, 0) + (volume if side == "BUY" else -volume)

    def reserve(self, name: str) -> None:
        self._in_flight.add(name)
        self._last_sent[name] = time.monotonic()
        self._sent += 1

    def release(self, name: str) -> None:
        self._in_flight.discard(name)


# ── Stage 6: execution = build, send, VERIFY, follow, cancel on timeout ─────
FINAL = ("Cancelled", "Broken", "Settled")
Builder = Callable[[Side, str, int, int], Awaitable["Order | None"]]


class Executor:
    def __init__(self, build: Builder, guard: RiskGuard, ttl_s: float = 30.0, log=print):
        self.build, self.guard, self.ttl_s, self.log = build, guard, ttl_s, log

    async def fire(self, q: Quote, d: Decision) -> None:
        try:
            order = await self.build(d.side, q.name, d.price, d.volume)
            if order is None:
                self.log(f"[{q.name}] no OMS session — log in first")
                return

            await order.send()
            if order.OrderId is None:                     # send() never raises: check the attribute
                self.log(f"[{q.name}] order NOT accepted ({d.reason})")
                return

            self.log(f"[{q.name}] {d.side} {d.volume} @ {d.price} sent, id={order.OrderId} ({d.reason})")
            status = await self.supervise(order)
            self.log(f"[{q.name}] final: {status}")

            executed = status["ExecutedVolume"] if status else d.volume   # unknown -> assume the worst
            self.guard.record_fill(q.name, d.side, executed)
        except Exception as error:                        # never let a task die silently
            self.log(f"[{q.name}] execution error: {error!r}")
        finally:
            self.guard.release(q.name)

    async def supervise(self, order) -> Optional[dict]:
        deadline = time.monotonic() + self.ttl_s
        while time.monotonic() < deadline:
            status = await order.Status()
            if status is not None and status["order_status"] in FINAL:
                return status
            await asyncio.sleep(1.0)
        await order.Delete()                              # time-boxed: do not leave orders behind
        return await order.Status()


QUIET_VETOES = ("cooldown", "an order for this contract is already working")   # expected on every tick


# ── Glue: evaluate rules, ask the guard, fire without blocking the loop ─────
def handle(q: Quote, rules: list[Rule], guard: RiskGuard, executor: Executor, log=print) -> None:
    for rule in rules:
        decision = rule.evaluate(q)
        if decision is None:
            continue
        allowed, why = guard.check(q, decision)
        if not allowed:
            if why not in QUIET_VETOES:
                log(f"[{q.name}] rule '{rule.name}' vetoed: {why}")
            return
        guard.reserve(q.name)
        asyncio.create_task(executor.fire(q, decision))   # the loop keeps running meanwhile
        return                                            # first matching rule wins
```

Builders adapt the kit to each market (so the kit itself never changes):

```python
def ime_builder(ems) -> Builder:
    async def build(side, name, price, volume):
        method = ems.Buy_by_ContractName if side == "BUY" else ems.Sell_by_ContractName
        return await method(contractName=name, Price=price, Volume=volume)
    return build


def tse_builder(ems) -> Builder:
    async def build(side, name, price, volume):
        method = ems.Buy_by_Name if side == "BUY" else ems.Sell_by_Name
        return await method(symbolName=name, Price=price, Volume=volume)
    return build
```

#### Writing rules

A rule is *conditions + pricing + size*. Because conditions are plain functions, rules read like a specification and can be unit-tested without any network:

```python
# rules.py
from kit import *

rules = [
    Rule(
        name="support-bid",
        when=all_of(
            fresh(2.0),                  # data is at most 2 s old
            spread_at_most(200),         # tight market (price units, IRR)
            buy_pressure(0.65),          # at least 65 % of level-1 quantity is on the bid
            bid_at_most(36_000),         # never pay above our limit
            inside_price_band(0.01),     # stay 1 % away from the daily limits
        ),
        side="BUY",
        price_from=lambda q: q.bid,      # join the best bid
        volume=1,
    ),
    Rule(
        name="take-profit-offer",
        when=all_of(fresh(2.0), spread_at_most(200), ask_at_least(37_000), sell_pressure(0.35)),
        side="SELL",
        price_from=lambda q: q.ask,      # join the best ask
        volume=1,
    ),
]
```

Condition cookbook:

| Idea | Condition |
|---|---|
| Price below a level | `bid_at_most(limit)` |
| Tight market | `spread_at_most(n)` |
| Order-flow pressure | `buy_pressure(0.65)` / `sell_pressure(0.35)` |
| Never trade on stale data | `fresh(2.0)` |
| Stay away from daily limits | `inside_price_band(0.01)` |
| Either of two setups | `any_of(a, b)` |
| Several requirements | `all_of(a, b, c)` |

Unit tests need no network at all:

```python
import time
from kit import *
from rules import rules

q = Quote(name="T", bid=35_200, bid_qty=1500, ask=35_300, ask_qty=800, last=35_250.0,
          min_price=33_250.0, max_price=36_750.0, source="test", received_at=time.monotonic())

assert rules[0].evaluate(q) is not None          # all conditions hold -> a BUY decision
assert rules[1].evaluate(q) is None              # the sell setup does not hold
```

#### Part A — Socket mode: data pushed by the Data Engine

The WebSocket is the source. Every message is normalized into a `Quote` and stored (latest wins); a separate loop evaluates the rules at a fixed cadence. This is the conflation pattern of [8.8](#88-pattern--keep-only-the-latest-state-conflation) combined with the reconnecting stream of [8.10](#810-pattern--a-production-grade-reconnecting-stream) (`stream_forever` is defined there).

```python
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.IME import DataEngine_Ime_AsyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_AsyncClient
from kit import *                                   # the shared kit above
from rules import rules                             # the rules above
from streaming import stream_forever                # the function from section 8.10


async def run_socket_mode(open_stream, normalize, rules, executor, guard,
                          shutdown: asyncio.Event, decision_period: float = 0.05):
    latest: dict[str, Quote] = {}

    async def on_message(message):                  # stage 1 -> 2
        quote = normalize(message)
        if quote is not None:
            latest[quote.name] = quote

    async def decision_loop():                      # stages 3 -> 6
        while not shutdown.is_set():
            await asyncio.sleep(decision_period)    # 20 decisions per second at most
            for quote in list(latest.values()):
                handle(quote, rules, guard, executor)

    await asyncio.gather(
        stream_forever(open_stream, on_message, shutdown),
        decision_loop(),
    )


async def main():
    auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
    ime = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
    ems = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth)

    (await ems.Get_Captcha("Sahra | Karamad")).show()
    await ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))

    guard = RiskGuard(max_volume=5, max_position=10, cooldown_s=10.0, max_orders=50)
    executor = Executor(ime_builder(ems), guard, ttl_s=30.0)

    names = ["KASH05C170", "KASH05P170"]
    shutdown = asyncio.Event()

    await run_socket_mode(
        open_stream=lambda run: ime.websocket_by_name(names, event=run),
        normalize=lambda m: to_quote(m["contractName"], m["data"], "ws"),
        rules=rules,
        executor=executor,
        guard=guard,
        shutdown=shutdown,
    )


asyncio.run(main())
```

What happens on every tick, end to end:

1. The Data Engine pushes a snapshot → `to_quote` normalizes it → `latest[name]` is overwritten.
2. Every 50 ms the decision loop evaluates each rule's **conditions** on the newest quotes.
3. A matching rule produces a **decision** (side, price, volume).
4. The **risk guard** checks price band, volume, net position limit, cooldown, order cap and "one order in flight".
5. The **executor** builds the order, sends it, **verifies `OrderId`**, follows it with `Status()`, cancels it if it is still open after `ttl_s`, and records the filled volume in the guard (so the position limit works).

If the connection dies, `stream_forever` reconnects, and `fresh(2.0)` automatically blocks decisions on data older than 2 seconds in the meantime.

#### Part B — Request mode: data requested on a schedule

The source is periodic REST requests. Only stage 1 differs: instead of subscribing, you **ask**. One `live_overview_by_name` call fetches the state of many contracts, and each entry has the same sections as a stream message, so the **same `to_quote`, rules, guard and executor** are reused.

```python
import asyncio
import time
from kit import *


async def run_request_mode(ime, names, rules, executor, guard,
                           shutdown: asyncio.Event, period: float = 1.0, log=print):
    while not shutdown.is_set():
        started = time.monotonic()
        try:
            overview = await ime.live_overview_by_name(names)          # stage 1: REST request
        except ValueError as error:                                    # API error with the server's message
            log("API error:", error)
            overview = None
        except Exception as error:                                     # timeout / network
            log("transport error:", repr(error))
            overview = None

        if overview is not None:
            for name, blob in overview["Data"].items():
                if blob is None:                                       # unknown contract
                    continue
                quote = to_quote(name, blob, "rest")                   # stage 2 (same function)
                handle(quote, rules, guard, executor)                  # stages 3 -> 6 (same code)

        await asyncio.sleep(max(0.0, period - (time.monotonic() - started)))   # keep a steady cadence
```

Choosing between the two sources:

| | **Socket mode** | **Request mode** |
|---|---|---|
| Latency | lowest — the server pushes | one polling period |
| Load | one connection | one request per period |
| Complexity | reconnects and watchdog needed | trivial loop |
| Failure behaviour | ends silently — must be detected | explicit exception — easy to handle |
| Best for | fast reactions, many instruments, market-making style logic | slow signals, periodic rebalancing, confirmation before acting |

The two combine well: **react on the socket, confirm over REST** ([8.14](#814-pattern--websocket-for-reaction-rest-for-confirmation)). For example, wrap the executor so that every decision is re-checked on a fresh REST snapshot just before the order is built:

```python
class ConfirmingExecutor(Executor):
    def __init__(self, ime, rules, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ime, self.rules = ime, rules

    async def fire(self, q: Quote, d: Decision) -> None:
        fresh_quote, decision = None, None
        try:
            blob = (await self.ime.live_overview_by_name([q.name]))["Data"][q.name]
            rule = next((r for r in self.rules if r.name == d.reason), None)
            if blob is not None and rule is not None:
                fresh_quote = to_quote(q.name, blob, "rest")
                decision = rule.evaluate(fresh_quote)         # re-check the SAME rule on fresh data
        except Exception as error:
            self.log(f"[{q.name}] confirmation failed: {error!r}")

        if decision is None:
            self.log(f"[{q.name}] '{d.reason}' not confirmed on fresh data — skipped")
            self.guard.release(q.name)
            return

        await super().fire(fresh_quote, decision)             # releases the guard in its `finally`
```

#### Part C — The same pipeline on TSE-IFB: merging channels

TSE-IFB messages carry one channel each, so stage 2 merges the channels into a single `Quote`. The daily price band comes from static info, fetched once at start-up.

```python
import asyncio
import time
from typing import Optional
from kit import *
from rules import rules                             # rules whose prices fit these symbols
from streaming import stream_forever
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient
from HedgeTech.EMS.TseIfb import EmsEngine_TseIfb_AsyncClient


class TseBook:
    """Merges 'best-limit' and 'aggregate' messages into one Quote per symbol."""

    def __init__(self, bands: dict[str, tuple[float, float]]):
        self.bands = bands                        # symbolName -> (minAllowedPrice, maxAllowedPrice)
        self.best: dict[str, dict] = {}
        self.last: dict[str, float] = {}

    def apply(self, update: dict) -> Optional[Quote]:
        name = update["symbolName"]

        if update["channel"] == "best-limit":
            self.best[name] = update["data"]["1"]
        elif update["channel"] == "aggregate":
            self.last[name] = float(update["data"]["last_price"])

        level = self.best.get(name)
        if level is None or name not in self.bands:
            return None                            # not enough information yet

        low, high = self.bands[name]
        return Quote(
            name=name,
            bid=int(level["buy_price"]),  bid_qty=int(level["buy_quantity"]),
            ask=int(level["sell_price"]), ask_qty=int(level["sell_quantity"]),
            last=self.last.get(name, 0.0),
            min_price=low, max_price=high,
            source="ws", received_at=time.monotonic(),
        )


async def main():
    auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
    tse = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)
    ems = EmsEngine_TseIfb_AsyncClient(AuthASyncClient=auth)

    (await ems.Get_Captcha("Omex | Parsian")).show()
    await ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))

    symbols = ["فملی", "خودرو"]

    # Daily price band from static info (stage 2 needs it for the guard)
    info = await tse.instruments_static_info_by_name(symbols)
    bands = {i["symbolName"]: (i["minAllowedPrice"], i["maxAllowedPrice"]) for i in info["Data"] if i}

    book = TseBook(bands)
    guard = RiskGuard(max_volume=1000, max_position=5000, cooldown_s=15.0, max_orders=30)
    executor = Executor(tse_builder(ems), guard, ttl_s=45.0)
    shutdown = asyncio.Event()

    await run_socket_mode(
        open_stream=lambda run: tse.websocket_by_name(
            channels=["best-limit", "aggregate"], symbol_names=symbols, event=run
        ),
        normalize=book.apply,
        rules=rules,
        executor=executor,
        guard=guard,
        shutdown=shutdown,
    )
```

> TSE-IFB orders take `Order_ValidityType` and `ValidityDate`; the builder above uses the default `'DAY'`. Extend `tse_builder` if you need GTC/GTD.

#### Part D — The same flow with the synchronous clients

Sync clients are blocking, so the simplest professional shape is a single loop: request → conditions → execute → follow.

```python
import time
from HedgeTech.Auth import AuthSyncClient
from HedgeTech.Data.IME import DataEngine_Ime_SyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_SyncClient
from kit import to_quote, FINAL
from rules import rules

auth = AuthSyncClient.login(UserName_or_Email="user@example.com", Password="…")
ime = DataEngine_Ime_SyncClient(AuthSyncClient=auth)
ems = EmsEngine_Ime_SyncClient(AuthSyncClient=auth)

ems.Get_Captcha("Sahra | Karamad").show()
ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))

names = ["KASH05C170"]
open_order = None

while True:
    started = time.monotonic()
    try:
        overview = ime.live_overview_by_name(names)
    except Exception as error:
        print("request failed:", repr(error))
        time.sleep(1)
        continue

    if open_order is not None:                                    # follow the working order first
        status = open_order.Status()
        if status is not None and status["order_status"] in FINAL:
            print("final:", status)
            open_order = None
        # (add a deadline and open_order.Delete() as in Executor.supervise)

    elif overview["Data"][names[0]] is not None:
        quote = to_quote(names[0], overview["Data"][names[0]], "rest")
        for rule in rules:
            decision = rule.evaluate(quote)
            if decision is None:
                continue
            method = ems.Buy_by_ContractName if decision.side == "BUY" else ems.Sell_by_ContractName
            order = method(contractName=quote.name, Price=decision.price, Volume=decision.volume)
            if order is not None:
                order.send()
                if order.OrderId is not None:                     # send() never raises
                    open_order = order
            break

    time.sleep(max(0.0, 1.0 - (time.monotonic() - started)))
```

> The sync loop above omits the risk guard to stay short. Add the same checks (price band, cooldown, volume cap) before `method(...)` in a real bot.

#### Part E — Dry run, audit trail and going live

**Dry run first.** Replace the builder with one that only logs. Every other stage runs unchanged, so you can watch the decisions your conditions would make on **live data** without touching the exchange:

```python
class _FakeOrder:
    OrderId = "dry-run"
    OrderStatus = "Settled"
    async def send(self): pass
    async def Status(self): return {"order_status": "Settled", "ExecutedVolume": 0, "RemainedVolume": 0}
    async def Delete(self): pass


def dry_run_builder() -> Builder:
    async def build(side, name, price, volume):
        print(f"DRY-RUN  {side} {volume} {name} @ {price}")
        return _FakeOrder()
    return build


executor = Executor(dry_run_builder(), guard)
```

**Audit trail.** Log one JSON line per decision with the quote, the rule and the guard's verdict. When something unexpected happens, you can replay exactly what the bot saw:

```python
import json, time

def audit(q: Quote, d: Decision, allowed: bool, why: str, path: str = "decisions.jsonl"):
    with open(path, "a", encoding="utf-8") as file:
        file.write(json.dumps({
            "ts": time.time(), "contract": q.name, "rule": d.reason, "side": d.side,
            "price": d.price, "volume": d.volume, "allowed": allowed, "why": why,
            "bid": q.bid, "ask": q.ask, "bid_qty": q.bid_qty, "ask_qty": q.ask_qty,
            "last": q.last, "source": q.source,
        }, ensure_ascii=False) + "\n")
```

**Go-live sequence**

1. **Dry run** on live data for several sessions; read the audit log.
2. **Smallest real size** (`volume=1`), a tight `max_orders`, short `ttl_s`.
3. **Watch** the first orders end to end: `OrderId`, `Status()`, fills, cancellations.
4. **Scale up gradually**, keeping the guard limits conservative.

---

### Tutorial 1 — Research: moving-average crossover on historical data (TSE-IFB)

Goal: compute a signal offline before risking money.

```python
import time
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.TseIfb import DataEngine_TseIfb_AsyncClient


def sma(values, window):
    return [
        sum(values[i - window + 1 : i + 1]) / window if i >= window - 1 else None
        for i in range(len(values))
    ]


async def main():
    auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
    tse = DataEngine_TseIfb_AsyncClient(AuthAsyncClient=auth)

    now = int(time.time())
    candles = await tse.historical_ohlcv_by_name(
        symbol_name="فملی",
        start_timestamp=now - 365 * 24 * 3600,
        end_timestamp=now,
        AdjustedPrice=True,       # adjusted prices avoid false signals around corporate actions
        Resolution="D",
    )

    closes = candles["Data"]["Close"]
    fast, slow = sma(closes, 10), sma(closes, 30)

    position = 0
    for i in range(1, len(closes)):
        if None in (fast[i], slow[i], fast[i - 1], slow[i - 1]):
            continue
        crossed_up   = fast[i - 1] <= slow[i - 1] and fast[i] > slow[i]
        crossed_down = fast[i - 1] >= slow[i - 1] and fast[i] < slow[i]
        if crossed_up and position == 0:
            position = 1
            print("BUY ", candles["Data"]["Date_timestamp"][i], closes[i])
        elif crossed_down and position == 1:
            position = 0
            print("SELL", candles["Data"]["Date_timestamp"][i], closes[i])


asyncio.run(main())
```

### Tutorial 2 — Live monitoring: best bid/ask spread watcher (IME)

Goal: stream a contract and react when the spread tightens.

```python
import asyncio


async def spread_watcher(ime, contract_name: str, max_spread: int):
    stop = asyncio.Event()
    stop.set()

    async for message in ime.websocket_by_name([contract_name], event=stop):
        level_1 = message["data"]["BestLimit"]["1"]
        bid, ask = level_1["buy_price"], level_1["sell_price"]

        if bid <= 0 or ask <= 0:          # empty side of the book
            continue

        spread = ask - bid
        print(f"{message['timestamp']}  bid={bid} ask={ask} spread={spread}")

        if spread <= max_spread:
            print("Spread is tight — candidate for a limit order.")
            stop.clear()
```

### Tutorial 3 — Risk-aware execution: place an order inside the allowed price range (IME)

Goal: never send a price the exchange will reject.

```python
async def safe_buy(ime, ems, contract_name: str, desired_price: int, volume: int):
    # 1) Static limits for this contract
    static = (await ime.contracts_static_info_by_name([contract_name]))["Data"][0]
    if static is None or not static["canBuy"]:
        return None
    if not (static["minValidBuyVolume"] <= volume <= static["maxValidBuyVolume"]):
        raise ValueError("Volume outside the valid range")

    # 2) Today's allowed price band
    band = (await ime.live_allowed_price_range_by_name([contract_name]))["Data"][contract_name]
    price = max(band["minAllowedPrice"], min(desired_price, band["maxAllowedPrice"]))

    # 3) Build and send
    order = await ems.Buy_by_ContractName(
        contractName=contract_name, Price=int(price), Volume=volume
    )
    if order is None:
        raise RuntimeError("Log in to the OMS first")

    await order.send()
    if order.OrderId is None:                 # send() never raises — check the attribute!
        raise RuntimeError("Order was not accepted")
    return order
```

### Tutorial 4 — Order management loop: chase the market, then cancel

Goal: keep a limit order at the best bid, and give up after a deadline.

```python
import time

ACTIVE = ("InQueue", "PartiallyFilled")


async def chase_bid(ime, ems, contract_name: str, volume: int, give_up_after: float = 60.0):
    started = time.monotonic()

    best = (await ime.live_best_limit_by_name([contract_name]))["Data"][contract_name]["1"]
    order = await ems.Buy_by_ContractName(
        contractName=contract_name, Price=best["buy_price"], Volume=volume
    )
    if order is None:
        return None
    await order.send()
    if order.OrderId is None:
        return order

    while time.monotonic() - started < give_up_after:
        status = await order.Status()
        if status is None or status["order_status"] not in ACTIVE:
            break                                      # filled, cancelled, or unreadable

        best = (await ime.live_best_limit_by_name([contract_name]))["Data"][contract_name]["1"]
        if best["buy_price"] != status["Price"]:
            await order.Edit(Price=best["buy_price"], Volume=status["Volume"])
        await asyncio.sleep(1)

    if order.OrderStatus in ACTIVE or order.OrderStatus == "Unknown":
        await order.Delete()
    return order
```

> Use the range check from Tutorial 3 to choose the first price in real code. Note that `Edit()` only changes an order that was successfully sent and swallows its own errors, so the loop re-reads `Status()` every round.

### Tutorial 5 — Strategy sketch: scanning IME options for box-spread edges

A **long box spread** on strikes `K1 < K2` combines a bull call spread and a bear put spread; at expiry it pays `K2 − K1` per unit regardless of the underlying price (for European-style options). A **short box** is the opposite side. A scanner compares the net premium plus commissions against `K2 − K1`.

```python
from collections import defaultdict


async def scan_long_boxes(ime, search_text: str):
    # 1) Static metadata for the chain
    found = await ime.search_contracts(market="IMEOption", Search_char=search_text)
    options = [o for o in found["Data"] if o]

    # 2) Group calls/puts by (expiry, strike)
    chain = defaultdict(dict)
    for o in options:
        chain[o["ExpirationDate"]][(o["optionType"], o["strikePrice"])] = o

    # 3) Live best bid/ask for every contract in one request
    names = [o["contractName"] for o in options]
    quotes = (await ime.live_best_limit_by_name(names))["Data"]

    def ask(o): return quotes[o["contractName"]]["1"]["sell_price"]
    def bid(o): return quotes[o["contractName"]]["1"]["buy_price"]

    results = []
    for expiry, legs in chain.items():
        strikes = sorted({k for (_, k) in legs})
        for i, k1 in enumerate(strikes):
            for k2 in strikes[i + 1 :]:
                c1, c2 = legs.get(("Call", k1)), legs.get(("Call", k2))
                p1, p2 = legs.get(("Put", k1)), legs.get(("Put", k2))
                if not all((c1, c2, p1, p2)):
                    continue

                # Long box: buy C1, sell C2, sell P1, buy P2 (cross the spread)
                prices = (ask(c1), bid(c2), bid(p1), ask(p2))
                if min(prices) <= 0:                      # an empty side of a book
                    continue

                premium = ask(c1) - bid(c2) - bid(p1) + ask(p2)
                fees = (
                    ask(c1) * c1["buyCommission"] + bid(c2) * c2["sellCommission"]
                    + bid(p1) * p1["sellCommission"] + ask(p2) * p2["buyCommission"]
                )
                edge = (k2 - k1) - premium - fees         # per unit, before margin/tax/time value
                results.append((edge, expiry, k1, k2))

    return sorted(results, reverse=True)
```

Before trading any such signal in production, also model **initial/required margin** (`initialMargin`, `requiredMargin`), exercise fees and taxes (`ExerciseFeePhysical`, `ExerciseFeeCash`, `ExerciseSellTax`), contract size (`csize`), the time value of money until `ExpirationDate`, liquidity at each depth level, and the risk that one leg fills while another does not.

### Tutorial 6 — Putting it together: a minimal live bot skeleton

```python
import asyncio
from HedgeTech.Auth import AuthAsyncClient
from HedgeTech.Data.IME import DataEngine_Ime_AsyncClient
from HedgeTech.EMS.IME import EmsEngine_Ime_AsyncClient

CONTRACT = "KASH05C170"
MAX_SPREAD = 200


async def main():
    auth = await AuthAsyncClient.login(UserName_or_Email="user@example.com", Password="…")
    ime = DataEngine_Ime_AsyncClient(AuthAsyncClient=auth)
    ems = EmsEngine_Ime_AsyncClient(AuthASyncClient=auth)

    # OMS login (needs a human for the CAPTCHA)
    (await ems.Get_Captcha("Sahra | Karamad")).show()
    await ems.oms_login(username="…", password="…", captcha_value=input("CAPTCHA: "))

    stop = asyncio.Event()
    stop.set()
    order = None

    async for message in ime.websocket_by_name([CONTRACT], event=stop):
        level_1 = message["data"]["BestLimit"]["1"]
        bid, ask = level_1["buy_price"], level_1["sell_price"]
        if bid <= 0 or ask <= 0:
            continue

        if order is None and ask - bid <= MAX_SPREAD:
            order = await ems.Buy_by_ContractName(contractName=CONTRACT, Price=bid, Volume=1)
            await order.send()
            if order.OrderId is None:
                order = None                       # not accepted; try again later
            else:
                print("Order sent:", order.OrderId)
                stop.clear()                       # one order, then stop

    if order is not None:
        print(await order.Status())


asyncio.run(main())
```

### Production checklist

- [ ] **Re-login on token expiry.** The SDK does not refresh tokens.
- [ ] **Reconnect loop** around every WebSocket (streams end silently on error).
- [ ] **Verify every order via attributes / `Status()`** — order methods swallow errors.
- [ ] **Idempotency.** After a network error on `send()`, check whether the order exists before resending.
- [ ] **Respect limits.** Use `minAllowedPrice`/`maxAllowedPrice` and `min/maxValid{Buy,Sell}Volume` from static info.
- [ ] **Guard empty books.** A price of `0` usually means an empty side.
- [ ] **Single order in flight per contract** and a **net position limit** (the `RiskGuard` in the pipeline).
- [ ] **Dry-run executor first**, then audit every decision to a JSON-lines log.
- [ ] **Stale-data protection** (`fresh(...)` condition + stream watchdog).
- [ ] **Kill-switch.** Wire an `Event` so you can stop streams and cancel open orders on demand.
- [ ] **Log everything** (`OrderId`, `OrderOmsId`, timestamps, status transitions).
- [ ] **Paper-trade first** with the data clients only, then go live with small volume.

---

## 11. Data Conventions

| Topic | Convention |
|---|---|
| **Prices** | Integers/floats in **IRR (Rial)** |
| **Commissions, margins, taxes** | **Fractions** (`0.0025` = 0.25 %) |
| **`ServerTimeStamp`** (in `Status`) | Unix timestamp as a float |
| **WebSocket `timestamp`** | ISO-formatted string |
| **Historical timestamps** | Unix timestamps in **seconds** |
| **Best-limit depth** | **3** levels on IME, **6** levels on TSE-IFB (keys `"1"`, `"2"`, …) |
| **Missing instruments** | `None` entries inside `Data` lists |
| **Response envelope** | `{"Data": ..., "Status": {...}}` |

The `Status` section of every REST response:

| Field | Meaning |
|---|---|
| `State` | `True` on success |
| `ServerTimeStamp` | Server time (Unix float) |
| `Version`, `Author` | API metadata |
| `Description` | `{"fa": ..., "en": ...}` human-readable message |
| `StatusCode` | Numeric status |

---

## 12. Error Handling & Reliability

| Where | What you get |
|---|---|
| Any REST data method | `ValueError` with the server's `detail` when the HTTP status is not a success |
| `login` | `ValueError` (status ≠ `201`); `httpx` exceptions for network errors |
| `Get_Captcha`, `oms_login` | `ValueError` (message from `detail.Status.Description.en` or raw text) |
| `Order.send / Edit / Status / Delete` | **Never raise** — they return `None`; check attributes |
| WebSocket connect | `websockets` exceptions (e.g. auth failure) |
| WebSocket after connect | Generator **ends silently** |

**Recommended pattern**

```python
async def safe_call(coro):
    try:
        return await coro
    except ValueError as error:           # API-level error with the server's message
        print("API error:", error)
    except Exception as error:            # network / TLS / timeout
        print("Transport error:", error)
```

**Timeouts are short by design** (connect 0.25 s, read 1.5 s) to fit trading latency budgets, and the client retries up to 10 times. If you call large endpoints over slow links, expect occasional timeouts and plan for them.

> The bare `except` blocks inside `Order` also catch cancellation (`asyncio.CancelledError` in async clients, `KeyboardInterrupt` in sync clients). Plan your shutdown logic around the stop-`Event` pattern rather than relying on task cancellation.

---

## 13. API Reference (Cheat-Sheet)

### Auth

| Call | Returns |
|---|---|
| `await AuthAsyncClient.login(UserName_or_Email, Password)` / `AuthSyncClient.login(...)` | authenticated client |
| `auth.token`, `auth.httpx_Client`, `auth.Permissions` | token dict, HTTP client, decoded claims |

### IME Data Engine

| Method | Endpoint family |
|---|---|
| `search_contracts(market, Search_char)` | static |
| `contracts_static_info_by_name(contract_names)` / `…_by_id(contract_ids)` | static |
| `live_overview_by_name / _by_id` | live |
| `live_best_limit_by_name / _by_id` | live |
| `live_aggregate_by_name / _by_id` | live |
| `live_contract_info_by_name / _by_id` | live |
| `live_allowed_price_range_by_name / _by_id` | live |
| `websocket_by_name(contract_names, event)` / `websocket_by_id(contract_ids, event)` | stream |

### TSE-IFB Data Engine

| Method | Endpoint family |
|---|---|
| `search_instruments(market, Search_char)` | static |
| `instruments_static_info_by_name(symbol_names)` / `…_by_isin(symbol_isins)` | static |
| `live_overview_*`, `live_best_limit_*`, `live_order_book_*`, `live_aggregate_*` | live |
| `live_institutional_vs_individual_*`, `live_contract_info_*`, `live_fund_info_*`, `live_ohlcv_last1m_*` | live |
| `historical_ohlcv_by_name / _by_isin` | historical |
| `historical_corporateactions_by_name / _by_isin` | historical |
| `websocket_by_name(channels, symbol_names, event)` / `websocket_by_isin(channels, symbol_isins, event)` | stream |

### EMS Engine

| Client | Methods |
|---|---|
| Both | `Get_Captcha(OMS)`, `oms_login(username, password, captcha_value)` |
| IME | `Buy_by_ContractName`, `Sell_by_ContractName`, `Buy_by_ContractId`, `Sell_by_ContractId` |
| TSE-IFB | `Buy_by_Name`, `Sell_by_Name`, `Buy_by_isin`, `Sell_by_isin` |
| `Order` | `send()`, `Edit(Price, Volume[, Order_ValidityType, ValidityDate])`, `Status()`, `Delete()` |

Client attributes after OMS login: `Customer_FullName`, `Customer_IMEBourseCode` (IME) or `Customer_TSEBourseCode` (TSE-IFB), `oms_session`.

Order attributes: `ContractNameOrId` / `SymbolNameOrIsin`, `Price`, `Volume`, `is_deleted`, `OrderStatus`, `OrderId`, `OrderOmsId`.

---

## 14. Support & Contact

Questions, bug reports, account or access requests? The HedgeTech team is happy to help.

| Channel | Details |
|---|---|
| ✉️ **Support e-mail** | [info@hedgetech.ir](mailto:info@hedgetech.ir) |
| 🛒 **Store** | [store.hedgetech.ir](https://store.hedgetech.ir) |
| 💼 **LinkedIn** | [linkedin.com/company/hedgetech-ir](https://www.linkedin.com/company/hedgetech-ir) |
| 🌐 **Platform** | [core.hedgetech.ir](https://core.hedgetech.ir) |

**When you contact support, please include:** your SDK version, Python version, the method you called, the full error message, and the time of the event (including time zone). Never send passwords or tokens.

---

## 15. Disclaimer

This SDK provides tools for accessing market data and routing orders. It is **not investment advice**. Trading — in particular with leverage and derivatives — carries substantial risk of loss. The examples in this document are educational and intentionally simplified; you are solely responsible for testing, risk management, regulatory compliance and any trading decisions made with this software. Market data and order handling depend on exchange, broker (OMS) and network conditions that HedgeTech does not control.

---

<div align="center">

**© HedgeTech — All rights reserved.**
[core.hedgetech.ir](https://core.hedgetech.ir) · [info@hedgetech.ir](mailto:info@hedgetech.ir) · [store.hedgetech.ir](https://store.hedgetech.ir) · [LinkedIn](https://www.linkedin.com/company/hedgetech-ir)

</div>
