Metadata-Version: 2.4
Name: pax-api
Version: 3.0.0
Summary: Official Python SDK for the PredictAsiaX Trader Track API — Web3-native prediction markets
Author-email: PredictAsiaX <support@predictasiax.com>
License: MIT
Project-URL: Homepage, https://predictasiax.com/developer
Project-URL: Documentation, https://docs.predictasiax.com
Project-URL: Repository, https://github.com/predictasiax/pax-python-sdk
Project-URL: Issues, https://github.com/predictasiax/pax-python-sdk/issues
Project-URL: Changelog, https://docs.predictasiax.com/changelog
Keywords: predictasiax,pax,prediction-market,trading-api,web3,hmac
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28
Requires-Dist: websocket-client>=1.5
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-cov>=4; extra == "dev"
Requires-Dist: responses>=0.23; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: mypy>=1; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: twine>=4; extra == "dev"
Dynamic: license-file

# pax-api — Official Python SDK for PredictAsiaX

REST + WebSocket client for the PredictAsiaX API gateway (`https://api.predictasiax.com`).

**Version 3.0.0** · MIT license · Python 3.8+ · [Changelog](CHANGELOG.md)

- **Docs**: https://docs.predictasiax.com
- **Verify**: https://docs.predictasiax.com/verify — public audit-log verifier
- **Sandbox key (anonymous)**: `POST /v1/sandbox-keys`
- **Support**: support@predictasiax.com

## Install

```bash
pip install --upgrade pax-api
```

## Quickstart

```python
from pax_api import PaxClient

# Public endpoints need no key
pax = PaxClient()
print(pax.audit_status()["data"]["events"]["total"])
print(pax.get_orderbook("hadjar-f1-2026"))

# Mint a sandbox key (the api_key is shown once — store it)
key = pax.mint_sandbox_key(org_name="my-app")["data"]["api_key"]

pax = PaxClient(api_key=key)          # sent as Authorization: Bearer sk_live_...
print(pax.get_balance())
print(pax.get_positions())
```

## Credentials

| Mode | Constructor | Sent on the wire |
|------|-------------|------------------|
| API key | `PaxClient(api_key="sk_live_...")` | `Authorization: Bearer sk_live_...` |
| HMAC signing | `PaxClient(api_key="sk_live_...", key_id="api_...")` | `PAX-ADDRESS`, `PAX-TIMESTAMP`, `PAX-NONCE`, `PAX-SIGNATURE` (no key) |
| Session / OAuth | `PaxClient(bearer_token="...")` | `Authorization: Bearer ...` |

HMAC signature (what the gateway verifies):

```text
canonical = timestamp + "\n" + nonce + "\n" + METHOD + "\n" + path_with_query + "\n" + body
signature = base64(HMAC-SHA256(key = the full sk_live_ key, msg = canonical))
```

`timestamp` is Unix seconds (accepted window ±300 s), `nonce` is single-use, `path_with_query` includes `/v1` and the query string. The SDK signs every attempt afresh, retries included. `pax_api.auth.sign_request` is exported if you need the headers yourself.

## Trading

```python
pax = PaxClient(api_key="sk_live_...", key_id="api_...")

order = pax.place_order(market_id="hadjar-f1-2026", side="yes", price="0.05", size="10")
pax.get_orders(status="open")
pax.cancel_order(order_id)
pax.cancel_all_orders(market_id="hadjar-f1-2026")

pax.place_orders_batch([
    {"market_id": "hadjar-f1-2026", "side": "yes", "price": "0.04", "size": "5"},
    {"market_id": "hadjar-f1-2026", "side": "no",  "price": "0.90", "size": "5"},
])
```

`place_order` is a limit BUY of the chosen outcome (`side="yes"` or `"no"`), price 0.01–0.99.

## Fee estimate

```python
pax.estimate_fees(size="10", price="0.55", market_id="hadjar-f1-2026", side="yes")
```

## Audit log verification

Every platform event is hash-chained and batched into SHA-256 Merkle trees. The SDK checks everything locally:

```python
from pax_api import PaxClient, verify_event, verify_merkle_proof, expected_proof_length

pax = PaxClient()
result = pax.verify_audit_event(1866215)
print(result["ok"], result["checks"])
# checks: event_hash (sha256(prev_event_hash + canonical)), same_event,
#         seq_in_batch, server_length_agrees, merkle (incl. proof length)

# Low level
proof = pax.audit_proof(1866215)["data"]
n = proof["batch"]["last_seq"] - proof["batch"]["first_seq"] + 1
verify_merkle_proof(proof["event_hash"], proof["batch"]["merkle_root"],
                    proof["merkle_proof"], expected_proof_length(n))
```

`verify_merkle_proof` requires `expected_length`: a proof with any other number of siblings is rejected, so an interior node cannot pass as a leaf. A root read from the same API proves internal consistency; for an independent check pass the anchored root (`pax.audit_anchor(batch_num)`) as `root=`.

## WebSocket streams

See `examples/03_websocket.py` and `PaxWSClient`.

## Error handling

Every response error becomes a typed exception:

```python
from pax_api import (
    PaxClient,
    PaxRateLimitError,
    PaxReadOnlyModeError,
    PaxValidationError,
    PaxWrongEnvKeyError,
    PaxError,           # base class — catch-all
)

try:
    pax.place_order(...)
except PaxRateLimitError as e:
    time.sleep(e.retry_after or 5)
except PaxValidationError as e:
    print(f"Bad request: {e.details}")
except PaxReadOnlyModeError:
    print("Trading paused by ops")
except PaxWrongEnvKeyError:
    print("Wrong environment key")
except PaxError as e:
    print(f"[{e.code}] {e.message} (request_id={e.request_id})")
```

## Automatic retry

Built-in exponential backoff on `429`, `500`, `502`, `504`. `Retry-After` header respected on rate limits. Each mutating call gets one `Idempotency-Key`, reused by every retry of that call; `place_order` also fixes its `client_order_id` before the first attempt, so a retry can never place a second order.

```python
pax = PaxClient(api_key=key, max_retries=5)
# max_retries=1 disables retries
```

## Base URL

The gateway is `https://api.predictasiax.com`; methods add the `/v1/...` path themselves. A `base_url` ending in `/v1` is accepted and normalised. Sandbox and production share the host: sandbox is a tier on the key (`tier=self_serve`), with per-order and per-day caps.

## Applications (progressive trust)

Move from sandbox → trade-capped → trade-full by submitting an application:

```python
res = pax.apply(track="self_serve", org="my-org", email="team@my-org.io")
print(res["data"]["application_code"])   # save this

status = pax.get_application(res["data"]["application_code"])
print(status["data"]["status"])           # submitted → in_review → approved / declined
```

## Development

```bash
git clone https://github.com/predictasiax/pax-python-sdk
cd pax-python-sdk
pip install -e ".[dev]"
pytest                 # run all tests
ruff check src tests   # lint
mypy src               # type-check
```

## Links

- [OpenAPI spec](https://docs.predictasiax.com/openapi)
- [AsyncAPI (WebSocket) spec](https://docs.predictasiax.com/asyncapi)
- [Auth guide](https://docs.predictasiax.com/auth)
- [Verify (public Merkle verifier)](https://docs.predictasiax.com/verify)
- [Error codes](https://docs.predictasiax.com/errors)
- [Rate limits](https://docs.predictasiax.com/rate-limits)
- [FAQ](https://docs.predictasiax.com/faq)
- [Changelog](https://docs.predictasiax.com/changelog)
- [API Terms](https://docs.predictasiax.com/api-terms)

## License

MIT — see [LICENSE](LICENSE).
