Metadata-Version: 2.5
Name: tria-trade
Version: 8.6.6b0
Summary: Tria API-Trading SDK — programmatic access to Decibel + Hyperliquid through Tria with builder-fee attribution.
Project-URL: Documentation, https://pypi.org/project/tria-trade/
Author-email: Tria Futures Squad <futures@tria.so>
License: UNLICENSED
Keywords: decibel,hyperliquid,perpetuals,sdk,trading
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: aptos-sdk>=0.12.2
Requires-Dist: bip-utils>=2.9
Requires-Dist: eth-account>=0.13
Requires-Dist: httpx>=0.27
Requires-Dist: hyperliquid-python-sdk>=0.24
Requires-Dist: msgpack>=1.0
Requires-Dist: websockets>=13
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# `tria-trade` (Python)

Trade **Hyperliquid** and **Decibel** perpetuals from Python, through Tria. One async client for both venues, the same order / fill / position shapes on both, and your Tria fee discounts applied automatically. It mirrors the TypeScript SDK, [`@tria-sdk/api-trading`](https://www.npmjs.com/package/@tria-sdk/api-trading).

## Install

```bash
pip install tria-trade
```

Python 3.11+. No account or token is needed to install.

## 1. Get your keys

In the Tria app: **Settings → API Keys** → choose Hyperliquid and/or Decibel → copy the `.env` block. It is shown once.

```bash
TRIA_TRADE_HL_AGENT_KEY=0x…                  # signs Hyperliquid orders
TRIA_TRADE_HL_ACCOUNT_ADDRESS=0x…            # your Hyperliquid account
TRIA_TRADE_DECIBEL_DELEGATE_KEY=0x…          # signs Decibel orders
TRIA_TRADE_DECIBEL_APTOS_OWNER_ADDRESS=0x…   # your Aptos wallet
TRIA_TRADE_DECIBEL_NODE_API_KEY=…            # Geomi API key, required for Decibel
TRIA_TRADE_DECIBEL_GAS_STATION_KEY=…         # optional, see "Decibel only" below
```

- These keys **can trade but cannot withdraw**. Revoke them any time in the app.
- They expire after 90 days by default (you choose 1–180 days, or none).
- Prefer the terminal? `tria-trade provision` creates the same keys from your own master keys (see [Provisioning CLI](#provisioning-cli)).

### Decibel only: API key, gas and rate limit

1. **API key (required).** Create an account at [geomi.dev](https://geomi.dev) and an API key (service type `Api`) → `TRIA_TRADE_DECIBEL_NODE_API_KEY`. Decibel rejects reads without it.
2. **Gas (pick one).** Every Decibel order is an Aptos transaction that costs a little APT.
   - **Gas station (hands-off):** in Geomi, create a mainnet gas station for module `0x50ead22afd6ffd9769e3b3d6e0e64a2a350d68e8b102c4e72e33d0b8cfdfdb06` with all functions selected, send ~0.5 APT to its fee-payer address, and copy its key → `TRIA_TRADE_DECIBEL_GAS_STATION_KEY`.
   - **Pay your own gas:** keep ~0.05 APT at your **delegate address** (shown as "Delegate Address" when you create the Decibel key in **Settings → API Keys**) and leave the gas-station key unset. Your delegate key signs every Decibel order, so its address pays the gas, not your owner wallet.

   Without either, Decibel orders fail with `INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE`.

3. **Know the rate limit.** Your Geomi organization can make **200 Decibel requests every 30 seconds**, shared by every key, bot and process on it. Over the limit, calls raise `VENUE_RATE_LIMIT` with `retry_after_ms` = 30 s: wait and retry, your account is fine. Busy bots hit this most, so:
   - Use streams (`subscribe_*`) instead of polling `positions` / `open_orders` in a loop.
   - Pass `market` to `cancel_order`: the cancel goes straight to the chain, usually with no lookup.
   - Keep the default `resolve="ack"`; `"confirmed"` adds reads to every order.
   - Leave out `clientOrderId` unless you need it: passing one costs a read per order.
   - Stay up to date: versions before 8.6.1 spend several times more requests per order.
   - Run each bot on its own Geomi organization, or [ask Geomi to raise the limit](https://geomi.dev/docs/admin/billing#system-limits) (adding a payment method does not raise it).

## 2. Place an order

```python
import asyncio
import os

from tria_trade import DecibelConfig, HlConfig, TriaClient, TriaClientConfig


async def main() -> None:
    config = TriaClientConfig(
        hl=HlConfig(
            agent_private_key=os.environ["TRIA_TRADE_HL_AGENT_KEY"],
            account_address=os.environ["TRIA_TRADE_HL_ACCOUNT_ADDRESS"],
        ),
        decibel=DecibelConfig(
            delegate_private_key=os.environ["TRIA_TRADE_DECIBEL_DELEGATE_KEY"],
            aptos_owner_address=os.environ["TRIA_TRADE_DECIBEL_APTOS_OWNER_ADDRESS"],
            node_api_key=os.environ["TRIA_TRADE_DECIBEL_NODE_API_KEY"],
            gas_station=os.environ.get("TRIA_TRADE_DECIBEL_GAS_STATION_KEY"),
        ),
    )
    async with TriaClient(config) as client:
        # Hyperliquid markets: "BTC", "ETH", …
        order = await client.place_order(
            {
                "venue": "hl",
                "market": "BTC",
                "side": "buy",
                "size": "0.001",
                "price": "50000",
                "tif": "gtc",
            }
        )
        await client.cancel_order(venue="hl", order_id=order["orderId"])

        # Decibel markets: "BTC/USD", "ETH/USD", …
        d_order = await client.place_order(
            {
                "venue": "decibel",
                "market": "BTC/USD",
                "side": "buy",
                "size": "0.001",
                "price": "50000",
                "tif": "gtc",
            }
        )
        await client.cancel_order(
            venue="decibel", client_order_id=d_order["clientOrderId"], market="BTC/USD"
        )


asyncio.run(main())
```

- Configure one venue or both; only configured venues work.
- Sizes and prices are **decimal strings** (never floats). Prices are rounded to the market's tick for you.
- `clientOrderId` is optional. Pass your own to make retries safe: a live one can't be reused.
- `async with` closes connections for you; otherwise call `await client.close()`.

## 3. Read and stream

```python
await client.positions(venue="hl")
await client.account(venue="decibel")  # balances, margin, leverage
await client.ticker(venue="hl", market="BTC")

stop = await client.subscribe_fills(venue="hl", callback=lambda fill: print(fill))
stop()
```

## Fund your account

Your trading keys can't move money, and the SDK never asks for a wallet key. It tells you where to send USDC and confirms when it arrives; you send it from your own wallet.

```python
import time

info = client.deposit_info(venue="hl")  # where + how, no network call
since = int(time.time() * 1000)
# … send USDC to info["recipient"] with your own wallet …
arrival = await client.wait_for_deposit(venue="hl", amount="25", since=since)
if arrival["arrived"]:
    print(f"credited {arrival['credited']} USDC")
```

|         | Hyperliquid                                                                                      | Decibel                                                                                                        |
| ------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| Send    | USDC **on Hyperliquid**                                                                          | Native USDC **on Aptos**                                                                                       |
| To      | `info["recipient"]` (your master account)                                                        | `info["recipient"]` (your trading subaccount)                                                                  |
| How     | From your own Hyperliquid account (Portfolio → Send), or bridge to Hyperliquid with that address | Run `info["contractCall"]` from your own Aptos wallet (Aptos CLI or SDK). A plain transfer is **not** credited |
| Minimum | 10 USDC                                                                                          | 10 USDC, plus ~0.0005 APT gas                                                                                  |

`wait_for_deposit` reads only the venue's deposit records, so trading meanwhile is never mistaken for a deposit. It returns `{"arrived": True, "credited", "entries"}`, or `{"arrived": False}` after `timeout_ms` (default 10 minutes).

**If USDC went somewhere else**

| You sent                                                        | What happens                                       | What to do                                    |
| --------------------------------------------------------------- | -------------------------------------------------- | --------------------------------------------- |
| USDC on Arbitrum to Hyperliquid's bridge, from another wallet   | Credited to **that** wallet, not your account      | From that wallet's HL account, send it to you |
| Under 5 USDC to Hyperliquid's bridge                            | Lost (Hyperliquid's rule)                          | Send at least the minimum                     |
| USDC or another token on an EVM chain to your master address    | Lands in your Tria wallet, not the trading balance | Deposit it from the Tria app                  |
| Another token on Hyperliquid (e.g. HYPE) to your master account | Sits in your HL spot balance as that token         | Swap it to USDC on Hyperliquid                |
| A plain USDC transfer to your Aptos owner address               | Lands in your Tria Aptos wallet                    | Deposit it from the Tria app                  |
| A plain transfer to the Decibel subaccount address              | Not credited, may not be recoverable               | Contact support with the transaction hash     |
| USDC on another chain, or another token, to an Aptos address    | Not credited to Decibel                            | Bridge or swap to native Aptos USDC first     |

## Methods

Every method is `async` (except `deposit_info` and `on_connection`) and raises `TriaError`. Every call takes `venue="hl"` or `venue="decibel"`.

| Orders                                                                       |                                                                    |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `place_order(args)`                                                          | One order (`tif`: `"gtc"`, `"ioc"`, `"alo"`)                       |
| `place_batch(venue=, orders=)`                                               | Up to 20 orders; each row returns an order status or a `TriaError` |
| `modify_order(venue=, order_id= \| client_order_id=, new_price=, new_size=)` | Change a resting order. Returns the **new** `orderId`              |
| `cancel_order(venue=, order_id= \| client_order_id=, market=)`               | Cancel one. A second cancel returns `{"status": "not_found"}`      |
| `cancel_all_orders(venue=, market=)`                                         | Cancel all, or all in one market                                   |
| `close_position(venue=, market=, slippage_bps=)`                             | Flatten a position with a reduce-only IOC (default 2% band)        |
| `attach_tp_sl(venue=, market=, take_profit=, stop_loss=)`                    | TP/SL on an open position (Hyperliquid only)                       |
| `scheduled_cancel(venue=, deadline_ms=)`                                     | Dead-man switch (HL only; needs $1M+ lifetime volume)              |

| Account                                                |                                                  |
| ------------------------------------------------------ | ------------------------------------------------ |
| `positions` · `open_orders` · `order_status` · `fills` | Positions, resting orders, one order, past fills |
| `balances` · `margin_state` · `account`                | Balances, margin, or both in one snapshot        |
| `deposit_info` · `wait_for_deposit`                    | Funding, see above                               |

| Market data                                                      |                                               |
| ---------------------------------------------------------------- | --------------------------------------------- |
| `markets` · `ticker` · `orderbook` · `candles` · `recent_trades` | Markets, prices, L2 book, OHLC, latest trades |

| Streams                                                                              |                                          |
| ------------------------------------------------------------------------------------ | ---------------------------------------- |
| `subscribe_fills` · `subscribe_orders` · `subscribe_positions` · `subscribe_account` | `(venue=, callback=)` → returns `stop()` |
| `on_connection(callback)`                                                            | Connection up / down / reconnecting      |
| `close()`                                                                            | Close all connections                    |

Helpers: `generate_client_order_id()`, `round_to_tick_size(price, tick_size)`.

## Errors

```python
from tria_trade import TriaError

try:
    await client.place_order(order)
except TriaError as err:
    print(err.code, err.venue_code, err)
```

| `code`                   | What it means                                                                                                                                                                               | What to do                                                                                                                                                                                                                                                            |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `KEY_EXPIRED_OR_REVOKED` | The trading key can no longer trade on this account: it expired, or it was revoked in the Tria app.                                                                                         | Create a new key in the Tria app (**Settings → API Keys**), put it in your bot's config and restart the bot. Retrying with the same key won't help.                                                                                                                   |
| `MISSING_BUILDER`        | The account hasn't approved Tria's builder fee.                                                                                                                                             | Create a new key for this venue in the Tria app, or re-run provision (see [Moving to the new builder](#moving-to-the-new-builder)). The SDK already falls back to Tria's previous builder when the account approved only that one, so this means it approved neither. |
| `CONFIG`                 | The client is set up wrong (the message names the field), a trading call was made on a read-only Decibel client, or `venue_code` is `SDK_UNSUPPORTED`: this version is no longer supported. | Fix the config the message names. For `SDK_UNSUPPORTED`, upgrade (see [Version checks](#version-checks)); cancels and `close_position` still work meanwhile.                                                                                                          |
| `INVALID_ARGUMENT`       | Bad input, such as an unknown market, a missing price, a venue that isn't configured, or a client order id that is already live. Nothing was sent.                                          | Fix the input. Don't retry it unchanged.                                                                                                                                                                                                                              |
| `VENUE_REJECTED`         | The venue refused the request; `venue_code` has its reason (for example insufficient margin, reduce-only with no position, a size below the minimum, or `INSUFFICIENT_APT`).                | Read `venue_code` and fix the cause; the same request fails the same way. For `INSUFFICIENT_APT`, keep some APT at your delegate address or set `gas_station`.                                                                                                        |
| `VENUE_RATE_LIMIT`       | Too many requests. On Decibel this is your Geomi organization's limit; your account and funds are fine.                                                                                     | Wait `retry_after_ms` (set on Decibel; on Hyperliquid back off a few seconds), then retry, and send fewer requests (see [Decibel only: API key, gas and rate limit](#decibel-only-api-key-gas-and-rate-limit)).                                                       |
| `VENUE_UNREACHABLE`      | A network problem, a venue outage, or no answer in time.                                                                                                                                    | Retry with a backoff. For an order, check `open_orders` / `order_status` first, since it may have gone through, unless the message says nothing was submitted.                                                                                                        |

**Expired or revoked keys.** When the client starts, the SDK checks that its Decibel key is still allowed to trade on the subaccount, and the first order waits for that check (at most 1 second). An expired key is refused before it sends anything; a key that isn't listed, or that expires within a week, gets a warning on the `tria_trade` logger. On either venue, once the venue refuses a key, the SDK stops sending orders with it: each later call fails at once with `KEY_EXPIRED_OR_REVOKED`. On Decibel that saves a transaction certain to fail; on Hyperliquid it saves the request budget the venue gives each IP address, which your other accounts share. The SDK re-checks a stopped key at most once a minute, read-only, and uses it again if it is valid. A Hyperliquid agent without a name can't be re-checked, so restart the bot after re-approving one.

Tria also tells the SDK about its key on the fee lookup it already makes. If Tria reports the key has expired, the SDK stops it on both venues. If the key expires within a week, or Tria can't confirm it for this account, the SDK warns once on the `tria_trade` logger and keeps trading.

**Decibel orders that fail after they're accepted.** By default `place_order` returns as soon as Aptos accepts the transaction, so a failure when it commits isn't raised; the SDK logs a warning instead. Pass `"resolve": "confirmed"` to get that failure from `place_order` itself.

**8.6.5-beta or earlier** has no `KEY_EXPIRED_OR_REVOKED` and never raises `MISSING_BUILDER`, so these cases surface as `VENUE_REJECTED` with the venue's text in `venue_code`:

| Venue's text                                                                                                                                                  | Means                  | Fix                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ----------------------------------- |
| `…ENOT_SUBACCOUNT_OWNER_OR_LACKS_PERP_TRADING_PERMISSIONS…` (Decibel), `User or API Wallet 0x… does not exist.` (Hyperliquid, when the address is your key's) | Key expired or revoked | Create a new key in the Tria app    |
| `Builder fee has not been approved.` (Hyperliquid), `EBUILDER_NOT_REGISTERED` (Decibel)                                                                       | Builder not approved   | Upgrade the SDK (see [Fees](#fees)) |

## Venue notes

**Hyperliquid**

- Minimum order is $10 notional. Prices are rounded to Hyperliquid's rule (5 significant figures) before signing.
- `modify_order` returns a new `orderId`; use that one afterwards.
- Unified accounts (all Tria app accounts) hold spot and perps in one balance; `account()["mode"]` shows which mode you're in.

**Decibel**

- Market names use a slash: `BTC/USD`.
- `place_order` returns `state="submitted"` as soon as Aptos accepts the transaction, with an empty `orderId`; track it by `clientOrderId`. Pass `"resolve": "confirmed"` to wait for the commit and the final state; it can still return `submitted` if Decibel's indexer lags, so check `order_status` rather than placing the order again.
- Take-profit / stop-loss must be set on the entry order (`tpTriggerPrice`, `slTriggerPrice`); `attach_tp_sl` isn't supported.
- `modify_order` returns a new `orderId` and drops the client order id; cancel the modified order by its new `orderId`.
- **Rate limit:** 200 requests per 30 s per Geomi organization; see [Decibel only: API key, gas and rate limit](#decibel-only-api-key-gas-and-rate-limit).

## Provisioning CLI

`tria-trade provision` sets up your accounts from your own master keys: it creates the Hyperliquid agent and Decibel delegate, approves Tria's builder fee, and writes a ready-to-use `.env`. It signs everything locally and never sends your master keys anywhere.

```bash
export HL_MASTER_PRIVATE_KEY=0x…       # or TRIA_MNEMONIC="word1 word2 …"
export APTOS_MASTER_PRIVATE_KEY=0x…    # for Decibel (or derived from TRIA_MNEMONIC)
export DECIBEL_NODE_API_KEY=…

tria-trade provision --dry-run         # show the plan, change nothing
tria-trade provision --output .env
```

Useful flags: `--skip-hl` / `--skip-decibel`, `--gas-station-key`, `--hl-amount` / `--decibel-amount` (move USDC into trading), `--force-new-agent` / `--force-new-decibel-delegate`.

## Fees

Every order carries Tria's builder fee, added by the SDK; it can't be changed or turned off. You can see it on each order (Hyperliquid: the order's builder field; Decibel: `builder_addr` and the builder fee).

The fee is **5 bps**, less the same discounts you get in the Tria app (VIP, staking, fee offers). The SDK looks up your discounts with your trading key; if it can't, the order goes out at the standard fee, never higher. The venue takes the fee from the fill.

**Upgrading from 8.6.5-beta or earlier:** Tria's builder address changed in 8.6.6-beta. 8.6.5-beta and earlier only use the previous builder; 8.6.6-beta and later use the new one, and upgrading keeps working. If your account hasn't approved the new builder yet, orders use the previous one and the SDK logs a one-time warning on the `tria_trade` logger. To switch, create one new key in the Tria app for each venue you trade on (on Decibel, for each subaccount), or re-run provision. Support for the previous builder ends in a future release.

The one case that breaks without upgrading: a brand-new user whose first key is created after the Tria app switches to the new builder. Their account never approved the previous builder, so an older SDK, which has no fallback, gets every order rejected (`VENUE_REJECTED` with "Builder fee has not been approved." on Hyperliquid, or `EBUILDER_NOT_REGISTERED` on Decibel). Upgrading the SDK fixes it.

### Moving to the new builder

The SDK uses the new builder as soon as your account approves it at the standard fee or more. It checks again every 5 minutes, so no restart is needed. Two ways to approve it:

1. **In the Tria app:** create one new key for each venue you trade on (on Decibel, one for each subaccount). Keys created before the Tria app moved to the new builder approved only the previous one; if a new key doesn't switch you, update the app and create the key again.
2. **From the terminal:** run provision. With no amounts it moves no funds; it approves the builder and creates a key only if you don't have one. Check the plan with `--dry-run` first:

   ```bash
   tria-trade provision --dry-run --output builder-approval.env
   ```

   Add `--skip-hl` or `--skip-decibel` to do one venue. On Decibel the approval is an Aptos transaction from your owner wallet: keep a little APT there, or pass `--gas-station-key`. Always pass `--output` with a new file name: the default is `.env`, which provision overwrites, and it has no key in it for a venue that already has one. Keep your existing `.env`. On Decibel, provision approves only your **primary** subaccount; for any other subaccount, create a key for it in the Tria app.

To check, ask the venue what your account has approved for Tria's builder (read-only, no key needed):

```bash
# Hyperliquid: 50 or more means approved. <account> is your Hyperliquid account address.
curl -s https://api.hyperliquid.xyz/info -H 'content-type: application/json' \
  -d '{"type":"maxBuilderFee","user":"<account>","builder":"0x0011765B039FF5e2E6e98329E6422c85AA65e778"}'

# Decibel: [{"vec":["500"]}] or more means approved; [{"vec":[]}] means not approved.
# <subaccount> is the Decibel subaccount you trade on (TRIA_TRADE_DECIBEL_SUBACCOUNT_ADDRESS in your .env).
curl -s https://api.mainnet.aptoslabs.com/v1/view -H 'content-type: application/json' \
  -d '{"function":"0x50ead22afd6ffd9769e3b3d6e0e64a2a350d68e8b102c4e72e33d0b8cfdfdb06::builder_code_registry::get_approved_max_fee","type_arguments":[],"arguments":["<subaccount>","0xb305235a5cbf44a2a9d46b425c5f500eab5a168c1ba718ce1b9a05ffa2e1b9b9"]}'
```

An approval below the standard fee doesn't count: orders stay on the previous builder.

### Using a Tria key without the SDK

If you call Hyperliquid or Decibel directly with a key created in Tria, add Tria's builder to every order. The SDK does this for you.

| Venue       | Builder address                                                      | Order field                 | Standard fee                                                      |
| ----------- | -------------------------------------------------------------------- | --------------------------- | ----------------------------------------------------------------- |
| Hyperliquid | `0x0011765B039FF5e2E6e98329E6422c85AA65e778`                         | `builder: { b, f }`         | `f: 50` (5 bps, in tenths of a basis point)                       |
| Decibel     | `0xb305235a5cbf44a2a9d46b425c5f500eab5a168c1ba718ce1b9a05ffa2e1b9b9` | `builderAddr`, `builderFee` | `5` (bps) in `@decibeltrade/sdk`; `500` in a direct contract call |

Your account must approve this builder first: see [Moving to the new builder](#moving-to-the-new-builder). Until it's approved, orders that carry the builder are rejected.

- Orders with no builder aren't eligible for Tria rewards such as competitions.
- The standard fee keeps an order eligible, but doesn't apply your VIP, staking or fee-offer discounts. Only the SDK applies those automatically.

## Version checks

If your version is out of date, the SDK logs a warning on the `tria_trade` logger (at most every 6 hours) with the upgrade command:

```bash
pip install --upgrade --pre tria-trade
```

If a version is no longer supported, new orders raise `CONFIG` with `venue_code="SDK_UNSUPPORTED"`. Cancels and `close_position` always work, so you can always get flat.

## Telemetry

The SDK sends anonymous usage data (actions, latencies, error types) to Tria. It never includes keys, full addresses or order sizes, and never slows or fails a call. It is always on; `TRIA_TRADE_TELEMETRY_QUIET=1` hides the one-time notice.

## More

- **Examples:** runnable scripts ship in the source distribution under `examples/` (place, cancel, fill stream, both venues).
- **Support:** [support@tria.so](mailto:support@tria.so).
