Metadata-Version: 2.4
Name: megatao-sdk
Version: 0.2.0
Summary: Python SDK for MegaTAO on Bittensor
License: MIT
License-File: LICENSE
Requires-Python: >=3.9
Requires-Dist: httpx>=0.25.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: chain
Requires-Dist: web3>=6.0.0; extra == 'chain'
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: respx>=0.20.0; extra == 'dev'
Description-Content-Type: text/markdown

# MegaTAO Python SDK

Python client for the [MegaTAO](https://megatao.com) perpetual futures API on Bittensor.

## Installation

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

To enable on-chain write operations (deposit, withdraw, open/close positions), install the `chain` extra:

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

---

## Overview

The SDK exposes two sub-clients on the `MegaTAO` object:

| Sub-client | Access | Purpose |
|---|---|---|
| **Info** | `client.info` | Read-only REST API — markets, prices, positions, orders, account data |
| **Chain** | `client.chain` | On-chain writes — deposit, withdraw, open/close positions, place/cancel orders |

`client.chain` is only available when `private_key` and `rpc_url` are provided at construction.

---

## Info Client

Read market data and account state via the REST API. No private key required.

```python
from megatao_sdk import MegaTAO

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

### Methods

| Method | Description |
|---|---|
| `markets()` | List all available markets |
| `market(address)` | Detailed info for a single market |
| `prices()` | Current prices for all markets |
| `orderbook(market, levels=10)` | Order book depth for a market |
| `positions(address)` | Open positions for a trader |
| `orders(address)` | Open limit orders for a trader |
| `margin(address)` | Account summary and margin balances |
| `trades(address)` | Trade history for a trader |
| `vault()` | Vault state (reserves, insurance fund) |
| `funding()` | Current funding rates |
| `platform_stats()` | Aggregate platform statistics |
| `leaderboard(limit=50, sort_by="pnl")` | Trader leaderboard |
| `candles(market, resolution="1h", from_ts=None, to_ts=None)` | OHLCV candle data |

All responses are typed Pydantic models. Numeric values are strings to preserve precision.

```python
market = client.info.markets()[0]
market.symbol       # "BTC-USD"
market.price        # "67000.00"
market.max_leverage # 50
```

### Async

```python
import asyncio
from megatao_sdk import AsyncMegaTAO

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

asyncio.run(main())
```

---

## Chain Client

Submit on-chain transactions. Requires `pip install megatao-sdk[chain]` and a funded wallet.

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

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

# Deposit collateral
tx_hash = client.chain.deposit(1 * TAO)

# Open a 10x long
tx_hash = client.chain.open_market_position(
    market="0xMarketAddress",
    is_long=True,
    margin_wei=1 * TAO,
    leverage_wei=10 * TAO,
    max_slippage_bps=50,
)

# Close a position (size_to_close_wei=0 closes fully)
tx_hash = client.chain.close_position(position_id=b"...", size_to_close_wei=0)

# Withdraw collateral
tx_hash = client.chain.withdraw(1 * TAO)
```

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

Pass `wait_for_receipt=True` to any method to block until mined and return a `TxReceipt` instead of a tx hash.

### Methods

| Method | Description |
|---|---|
| `deposit(amount_wei)` | Deposit TAO as collateral |
| `withdraw(amount_wei)` | Withdraw collateral |
| `open_market_position(market, is_long, margin_wei, leverage_wei, max_slippage_bps)` | Open a market order position |
| `close_position(position_id, size_to_close_wei=0)` | Close a position (0 = full close) |
| `place_limit_order(market, is_buy, margin_wei, leverage_wei, price_wei, reduce_only_type=0)` | Place a limit order |
| `place_take_profit(market, is_buy, margin_wei, leverage_wei, price_wei)` | Place a take-profit order (reduce-only, triggers on favorable price) |
| `place_stop_loss(market, is_buy, margin_wei, leverage_wei, price_wei)` | Place a stop-loss order (reduce-only, triggers on adverse price) |
| `cancel_order(market, order_id)` | Cancel a specific limit order |
| `cancel_all_orders(market)` | Cancel all open orders for a market |

### Async

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

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

tx_hash = await client.chain.deposit(1 * TAO)
```

---

## 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}")
```

---

## License

MIT
