Metadata-Version: 2.4
Name: avantis-trader-sdk
Version: 2.0.0
Summary: Python SDK for Avantis v2 — API-first perpetuals trading on Base
Author: Avantis Labs
License-Expression: MIT
Project-URL: Homepage, https://www.avantisfi.com
Project-URL: Documentation, https://sdk.avantisfi.com
Project-URL: Source, https://github.com/Avantis-Labs/avantis_trader_sdk
Project-URL: Changelog, https://github.com/Avantis-Labs/avantis_trader_sdk/blob/main/CHANGELOG.md
Keywords: avantis,perpetuals,perps,trading,base,defi,derivatives,crypto,web3
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
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: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.8
Requires-Dist: eth-account<0.14,>=0.13.4
Requires-Dist: eth-utils<6,>=4
Requires-Dist: eth-abi<6,>=5
Requires-Dist: websockets<15,>=12
Provides-Extra: kms
Requires-Dist: boto3<2,>=1.35; extra == "kms"
Requires-Dist: pyasn1<1,>=0.6; extra == "kms"
Provides-Extra: streams
Requires-Dist: python-socketio[asyncio_client]<6,>=5.11; extra == "streams"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: respx>=0.21; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: mypy>=1.11; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5; extra == "dev"
Dynamic: license-file

# Avantis Trader SDK v2

Python SDK for [Avantis](https://www.avantisfi.com) v2, leveraged perpetuals
on Base. API-first: no ABIs, no web3, no RPC required. The
SDK signs locally and everything else comes from Avantis services.

```python
import asyncio
from avantis_trader_sdk import AsyncAvantis

async def main():
    async with AsyncAvantis() as client:              # reads AVANTIS_* env vars
        await client.trade.market_open("ETH/USD", "long", collateral=100, leverage=10)
        positions = await client.account.positions()
        print(positions.positions)

asyncio.run(main())
```

## Install

```bash
pip install avantis-trader-sdk            # core
pip install "avantis-trader-sdk[kms]"     # + AWS KMS signing
pip install "avantis-trader-sdk[streams]" # + Socket.IO pair-data stream
```

Python 3.10+.

## Upgrading from v1 (0.8.x)

v2 is a ground-up, **breaking** rewrite for the Avantis v2 protocol (live
August 12, 2026) — the v1 `TraderClient` API is removed. Follow the
[migration guide](https://sdk.avantisfi.com/migration/sdk-migration). Avantis
v1 is superseded on-chain by the upgrade, so staying on the old SDK is only a
stopgap — pin `avantis-trader-sdk<2` if you need time to migrate.

## Setup (default: gasless API key)

1. Create an **API key** with the
   [Avantis API Key Generator](https://delegate.avantisfi.com/).
   One wallet signature registers it
   as a trading delegate for your account (it can trade, but can never move
   funds to itself; payouts always go to your wallet).
2. Approve USDC once (prompted on the UI).
3. Configure:

```bash
export AVANTIS_PRIVATE_KEY=0x...      # the API key
export AVANTIS_TRADER_ADDRESS=0x...   # your wallet
```

(Or copy
[`.env.example`](https://github.com/Avantis-Labs/avantis_trader_sdk/blob/main/.env.example)
to `.env`; it documents every supported variable, including the optional
ones.)

That's it. Every action is now a signed message relayed by Avantis. No gas,
no RPC, no ETH.

## Execution modes

Two independent axes; any combination works:

| | signer = API key (delegate) | signer = trader key |
|---|---|---|
| **relayer** (default, gasless) | sign intents, Avantis submits | same |
| **direct** (own RPC + ETH) | `delegatedAction`-wrapped txs | plain txs |

```bash
export AVANTIS_EXECUTION=direct       # opt into self-broadcasting
export AVANTIS_RPC_URL=https://...    # your Base RPC
```

Market makers can additionally use the **local intent builder**
(`client.local_intents()`) to build and sign orders with zero HTTP
round-trips on the hot path; see `examples/13_mm_fast_path.py`.

## What's covered

- **Trading**: market/limit opens (incl. coin-sized orders and Upside
  markets with automatic PnL-order routing), partial/full closes, margin
  updates, position increases, TP/SL updates, partial TP/SL trigger orders,
  TWAP.
- **Account**: positions with liq price/rollover/funding, limit orders, TWAPs,
  balances, allowances, delegation management, USDC approvals, rebate and
  keeper-reward claims, builder codes.
- **Markets**: full 100+ pair catalog (funding rates, spreads, OI and caps,
  fees, leverage envelopes, market hours), live prices, dynamic spread,
  OHLCV candles.
- **Info**: trade/order history with full fee breakdowns, portfolio analytics
  (PnL, win rate, volume, fees), referral stats, vault APY.
- **Compute** (pure functions, UI parity): net PnL incl. Upside profit-share
  tiers and loss protection, liquidation price, skew-adjusted open fees,
  maker/taker classification, OI headroom, TP/SL bounds, pre-trade validation.
- **Streams**: Lazer SSE + Pyth Hermes prices, pair-data updates, order
  execution events.
- **LP**: vault deposit/withdraw (ERC-4626), previews, utilization, APY.
- **Referral**: codes (incl. gasless registration), tiers, rebates.

## Correctness guarantees

- Every EIP-712 intent is **digest-verified locally** against the API before
  submission, so encoding drift fails loudly instead of reverting on-chain.
- The signing implementation is tested against **golden vectors computed by
  the actual on-chain hashing library** (all 17 intent types).
- The EIP-7702 relayer envelope is byte-for-byte compatible with the Avantis
  web app's implementation.

## Examples

See
[`examples/`](https://github.com/Avantis-Labs/avantis_trader_sdk/tree/main/examples):
one runnable script per flow, from `01_configure_and_meta.py` to
`19_upside_pairs.py`.

## Errors

All failures raise typed exceptions from `avantis_trader_sdk.errors`:
`ValidationError` (pre-trade checks, human-readable), `RelayError`,
`DigestMismatchError`, `DelegationError`, `RateLimitedError`, `RpcError`, etc.

## Security model

The API/delegate key can trade on your account but **cannot** withdraw funds,
approve USDC, or add other delegates. Worst case for a leaked key is
malicious trading until you revoke it (`client.account.revoke_delegate`) or
it expires. Keep expiries short (90 days recommended) and never commit keys.

## Development

```bash
pip install -e ".[dev]"
pytest            # 150+ tests incl. golden vectors and EIP-7702 parity
ruff check .
mypy avantis_trader_sdk
```
