# Wallex market data

The local marketplace reads the official public API through `/api/markets/wallex`.
No Wallex key is needed or sent for these public data requests. No orders, withdrawals,
account balances or personal Wallex information are requested.

Verified public instruments:

| Instrument | Market | Quote unit |
| --- | --- | --- |
| Tether | USDTTMN | Toman per USDT |
| Tether Gold | XAUTTMN | Toman per XAUT |
| United States Oil Fund (Ondo) | USOONTMN | Toman per USOON token |
| Global X Copper Miners ETF (Ondo) | COPXONTMN | Toman per COPXON token |
| iShares Silver Trust (Ondo) | SLVONTMN | Toman per SLVON token |

Oil/copper/silver fund tokens must not be labelled as physical barrels, kilograms or
ounces. API volume is executed 24-hour volume, not total token supply or available
inventory. Order-book quantities are independently fetched and labelled.

## Admin key field

Open the existing admin app's **اتصال‌ها → اتصال بازار والکس** section. Only an
MFA-authenticated owner can save a key. The form reuses the existing private provider
registry (`wallex_market_data`, scope `other`) and Supabase Vault through the existing
`marketplace_inquiry_settings` / `marketplace_inquiry_configure` RPCs. It does not
need a new migration. Those RPCs and Vault must already be installed as documented
in the identity/inquiry setup. The saved key is optional and is **not used by public
market requests**. The response exposes `hasKey`, version and update time only.
The key is not placed in public site content, browser storage, logs, or a URL.
The provider entry is hidden from the unrelated inquiries UI.

The key is reserved for services that actually require authenticated read access;
this change does not enable private API calls. Do not add trade/withdrawal permissions.

## Data flow and freshness

- Markets: `GET https://api.wallex.ir/hector/web/v1/markets`
- Candles: `GET /v1/udf/history`, hourly closes over 24 hours
- Depth: `GET /v1/depth?symbol=...`, first 5 valid levels per side
- Public requests use a fixed origin and allowlisted symbols, a timeout, and no redirects.
- Price requests coalesce and cache for 20 seconds; visible pages refresh every 30 seconds.
- Detail requests cache/refresh every 60 seconds. Data expires after 90 seconds.
- `receivedAt` is receipt time, not an upstream trade timestamp.
- Failed or malformed responses never fall back to illustrative prices or fabricated charts.
- The smart planner uses actual TMN prices and quantity precision, rounding down.
  Estimated units exclude fees/slippage/liquidity and never execute a trade.
- The five instruments appear in the existing Planck cards, categories, search and
  sorting. Provider attribution is hidden in the public interface; there is no separate Wallex market section.
  Details open from the shared cards or `/market?asset=USDTTMN` (allowlisted symbol).
- The smart planner combines project tokens and market instruments in one selection
  and allocation. One cash reserve and concentration limit apply across the portfolio;
  project capacity/horizon and market quantity precision remain independent constraints.
- Clearly flagged illustrative commodity projects are omitted from the marketplace
  catalog in favour of the real listings; database records are not modified.

## Buy and sell panels

Opening any of the five instruments from the home cards, full market, or smart
portfolio opens the same detail dialog with a buy/sell panel. Like the existing
project trade panel, it provides estimates and a review; execution remains disabled
until a trading service is configured. No order endpoint or ledger mutation is added.

`lib/market-trade.ts` uses exact decimal arithmetic and the selected instrument's
fresh price and quantity precision. Buys round quantity down and cash cost up to a
whole rial; sells round cash proceeds down. The entered budget is never exceeded.
There is no whole-token minimum or invented capacity based on trading volume.

Available balances come only from the signed-in customer's ledger, less locked
amounts. External token holdings require a null project ID and the exact base
symbol. Cash and token valuations are not interchangeable. Percentage controls
remain disabled when balances are unknown or zero; stale quotes disable review.
The final fee and executable price are not represented by the displayed estimate.

Validation: `node --test tests/market-trade.test.mjs tests/trade.test.mjs tests/wallex.test.mjs tests/market-assets.test.mjs`.

## Selectable rial / dollar reference

The admin **اتصال‌ها → نرخ تبدیل ریال و دلار** form sits beside the Wallex API-key
field. It saves a non-secret policy in `site_content.data.exchange_rate`, using the
existing owner session and optimistic `updated_at` checks. No migration is needed.
Other content saves preserve this independently managed setting.

Default: `{ "mode": "single", "sources": ["wallex"] }`. Available references are
Wallex and Nobitex; `average` requires both and uses their equal arithmetic mean.
These are USDT/IRR quotes used as a dollar reference, not a cash USD exchange rate.
The fixed denomination conversion remains 10 IRR = 1 toman.

`GET /api/markets/exchange-rate` reads the saved policy for each request and returns
the configured quote to the smart planner. Wallex TMN is converted to IRR before
averaging; Nobitex `stats["usdt-rls"].latest` is already IRR. Decimal arithmetic is
exact and rounds the final reference to the nearest rial. Selected sources must
all provide a valid fresh quote; failures never silently change the selection or
fall back to an old quote. Receipts expire after 90 seconds, and clients poll every
30 seconds. Provider endpoints are fixed server-side; the setting accepts IDs only.

Adding a provider requires its verified adapter and a matching allowlisted ID in
the admin and marketplace registries. Public APIs use no keys. The stored Wallex
key remains available for future authenticated services without entering public
requests. Existing wallet ledger values are preserved; this setting controls
planning conversions and does not execute orders.

References: https://developers.wallex.ir/docs/basic-services-markets,
https://developers.wallex.ir/docs/basic-services-candles,
https://developers.wallex.ir/docs/basic-services-depth,
https://apidocs.nobitex.ir/market_data/آمار-بازار,
https://t.me/NobitexAPINews/17 (current API origin: https://apiv2.nobitex.ir).
