Metadata-Version: 2.5
Name: tria-trade
Version: 8.6.5b0
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`              | Meaning                                                                 |
| ------------------- | ----------------------------------------------------------------------- |
| `INVALID_ARGUMENT`  | Bad input; nothing was sent                                             |
| `VENUE_REJECTED`    | The venue refused it; `venue_code` has the venue's reason               |
| `VENUE_RATE_LIMIT`  | Slow down; `retry_after_ms` says how long                               |
| `VENUE_UNREACHABLE` | Network or venue outage                                                 |
| `CONFIG`            | The client is set up wrong (or this SDK version is no longer supported) |
| `MISSING_BUILDER`   | Tria's builder fee isn't approved on the account                        |

## 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.

## 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).
