# Python SDK

The MegaTAO Python SDK provides a REST-based info client for reading market and account data, and an on-chain write client for executing trades directly from Python.

## Installation

```bash
pip install megatao-sdk
```

For on-chain write operations (deposit, open/close positions, orders):

```bash
pip install "megatao-sdk[chain]"
```

## Quick start

```python
from megatao_sdk import MegaTAO

with MegaTAO() as client:
    markets = client.info.markets()
    for m in markets:
        print(f"{m.symbol}: {m.price}")
```

***

## Info client

`client.info` exposes all REST API endpoints. No private key required.

### Markets

```python
# All markets
markets = client.info.markets()
market.symbol       # "CHUTES"
market.price        # "87707801000000000"
market.funding_rate # "20"
market.long_oi      # "9003500000000000000"

# Single market
info = client.info.market("0x000...0040")

# Current prices (keyed by address)
prices = client.info.prices()
prices["0x000...0040"].price  # "87707850000000000"

# Candle data
candles = client.info.candles("0x000...0040", resolution="1h")

# Order book
ob = client.info.orderbook("0x000...0040", levels=10)
ob.bids[0].price    # best bid
ob.asks[0].price    # best ask

# Funding rates
rates = client.info.funding()
rates[0].rate       # current rate in bps
```

### Account

```python
# Margin balances
margin = client.info.margin("0xYourAddress")
margin.available_margin   # available to trade
margin.account_equity     # deposited + unrealized PnL
margin.unrealized_pnl

# Open positions
positions = client.info.positions("0xYourAddress")
pos.is_long           # True / False
pos.notional_value    # size in wei
pos.entry_price
pos.price_pnl         # unrealized PnL from price movement
pos.liquidation_price

# Open orders
orders = client.info.orders("0xYourAddress")

# Trade history
trades = client.info.trades("0xYourAddress")
```

### Platform

```python
vault = client.info.vault()
vault.total_reserves      # total TAO in vault
vault.available_reserves  # available for fills
vault.insurance_fund
vault.utilization_rate    # in bps (1512 = 15.12%)
```

### Async

Every method has an async equivalent via `AsyncMegaTAO`:

```python
import asyncio
from megatao_sdk import AsyncMegaTAO

async def main():
    async with AsyncMegaTAO() as client:
        markets = await client.info.markets()
        margin = await client.info.margin("0xYourAddress")

asyncio.run(main())
```

***

## Chain client

`client.chain` enables on-chain writes. Requires `pip install "megatao-sdk[chain]"` and a funded wallet with an RPC URL.

```python
from megatao_sdk import MegaTAO
from megatao_sdk.chain import TAO

client = MegaTAO(
    private_key="0xYourPrivateKey",
    rpc_url="https://your-bittensor-rpc-url",
)
```

`TAO = 10**18` — all amounts are in wei (18 decimals).

All methods accept `wait_for_receipt=True` to block until the transaction is mined and return a full `TxReceipt`.

### Collateral

```python
# Deposit 1 TAO
tx = client.chain.deposit(1 * TAO)

# Withdraw 0.5 TAO
tx = client.chain.withdraw(int(0.5 * TAO))
```

### Positions

```python
# Open a 5x long with 1 TAO margin, 0.5% max slippage
tx = client.chain.open_market_position(
    market="0x000...0040",
    is_long=True,
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    max_slippage_bps=50,
)

# Close a position fully (size_to_close_wei=0 means full close)
tx = client.chain.close_position(position_id=bytes.fromhex("..."))
```

### Orders

```python
# Limit order
tx = client.chain.place_limit_order(
    market="0x000...0040",
    is_buy=True,
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    price_wei=int(85e15),
)

# Take-profit (reduce-only, triggers on favorable price)
tx = client.chain.place_take_profit(
    market="0x000...0040",
    is_buy=False,   # close a long
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    price_wei=int(95e15),
)

# Stop-loss (reduce-only, triggers on adverse price)
tx = client.chain.place_stop_loss(
    market="0x000...0040",
    is_buy=False,   # close a long
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    price_wei=int(75e15),
)

# Cancel
tx = client.chain.cancel_order(market="0x...", order_id=b"...")
tx = client.chain.cancel_all_orders(market="0x...")
```

***

## Error handling

```python
from megatao_sdk import MegaTAO, APIError, MegaTAOError

with MegaTAO() as client:
    try:
        info = client.info.market("0xInvalidAddress")
    except APIError as e:
        print(f"HTTP {e.status_code}: {e.message}")
    except MegaTAOError as e:
        print(f"SDK error: {e}")
```
