Skip to main content

Python SDK for AI Agent trading on prediction markets (Polymarket MVP)

Project description

AION SDK (MVP)

Python SDK for AI Agent trading operations on Polymarket and Kalshi prediction markets.

Features

  • 🤖 Agent Management - Register, authenticate, and manage AI agents
  • 📊 Market Operations - Search markets, get prices, access briefings and context
  • 💳 Wallet Management - Register and verify Polymarket CLOB credentials
  • 💹 Trading - Execute trades, manage orders, claim rewards
  • 🌤️ Kalshi BYOW - Quote -> local sign -> submit flow via DFlow
  • 🔐 Type-Safe - Full type hints with Python 3.9+ support
  • 📦 Lightweight - Minimal dependencies (only requests)

Installation

From PyPI (recommended)

pip install aion-sdk

From GitHub (development)

git clone https://github.com/aionmarket/aion-sdk.git
cd aion-sdk
pip install -e .

For Development

pip install -e ".[dev]"

Quick Start

Basic Usage

from aion_sdk import AionMarketClient

# Initialize client
client = AionMarketClient()

# Register a new agent
registration = client.register_agent("my-trading-bot")
print(f"Agent API Key: {registration['apiKeyCode']}")

# Use authenticated client
api_key = registration['apiKeyCode']
client_auth = AionMarketClient(api_key=api_key)

# Get agent info
agent_info = client_auth.get_me()
print(f"Agent: {agent_info}")

Trading Example

from aion_sdk import AionMarketClient

client = AionMarketClient(api_key="your-api-key")

# Search for markets
markets = client.get_markets(q="bitcoin", limit=5)
print(f"Found {len(markets)} markets")

# Get market context before trading
if markets:
    market_id = markets[0]['id']
    context = client.get_market_context(market_id, user="0x...")
    print(f"Market: {context['name']}")
    print(f"Your position: {context['myPosition']}")
    print(f"Suggested risk limit: {context['riskLimit']}")

# Place a trade (Polymarket V2 — pUSD settlement)
# NOTE: V2 settles in pUSD (Polymarket's ERC-20 collateral token).
#       Wallets must hold pUSD before trading. The SDK only supports V2 orders
#       (signatureType=3 + non-zero timestamp).
result = client.trade({
    "venue": "polymarket",
    "isLimitOrder": True,
    "marketConditionId": "0x...",
    "marketQuestion": "Will BTC close above 80k on Friday?",
    "orderSize": 10,
    "price": 0.65,
    "outcome": "YES",
    "reasoning": "Short-term momentum + options skew support YES",
    "source": "sdk:example",
    "skillSlug": "example-skill",
    "order": {
        "maker": "0x...",
        "signer": "0x...",
        "taker": "0x0000000000000000000000000000000000000000",
        "tokenId": "69136365945621600854789649488423522395843457249417452310260493085275775221076",
        "makerAmount": "6500000",
        "takerAmount": "10000000",
        "side": "BUY",
        "expiration": "0",
        # V2 order fields (signatureType=3 with non-zero timestamp)
        "timestamp": "1714400000",        # unix seconds when the order was signed
        "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "builder":  "0x0000000000000000000000000000000000000000000000000000000000000000",
        "signature": "0x...",
        "salt": 599228746038,
        "signatureType": 3,                 # 3 = Deposit wallet (Polymarket V2 / POLY_1271)
    },
})
print(f"Order placed: {result['orderId']}")

# Get open orders
open_orders = client.get_open_orders()
print(f"Open orders: {len(open_orders)}")

# Cancel an order
cancel_result = client.cancel_order(order_id=result.get('orderId', ''))
print(f"Cancelled: {cancel_result['success']}")

Wallet Credentials

from aion_sdk import AionMarketClient

client = AionMarketClient(api_key="your-api-key")

# Check if credentials are registered
wallet = "0x1234..."
check = client.check_wallet_credentials(wallet)
if not check['hasCredentials']:
    # Register credentials
    result = client.register_wallet_credentials(
        wallet_address=wallet,
        api_key="polymarket-api-key",
        api_secret="polymarket-api-secret",
        api_passphrase="polymarket-passphrase",
        # For Polymarket deposit wallets, pass signature_type=3 so the backend
        # stores the credential under the POLY_1271 / V2 path.
        # signature_type=3,
    )
    print(f"Credentials registered: {result['success']}")

Configuration

Base URL

The client defaults to production (https://api.aionmarket.com/bvapi). For staging, set the base URL:

client = AionMarketClient(
    api_key="your-api-key",
    base_url="https://pm-t1.bxingupdate.com/bvapi"
)

Timeout

Customize request timeout (default 20 seconds):

client = AionMarketClient(api_key="your-api-key", timeout=30)

Supported Endpoints

Agent Management

  • register_agent() - Register new agent
  • get_me() - Get current agent info
  • get_settings() / update_settings() - Risk control settings
  • get_skills() - Available agent skills

Market Data

  • get_markets() - Search markets
  • get_market() - Get market details by ID
  • check_market_exists() - Verify market exists
  • get_prices_history() - Historical price data
  • get_briefing() - Agent briefing with alerts and recommendations
  • get_market_context() - Pre-trade market assessment
  • get_closed_positions() - Closed positions by wallet
  • get_current_positions() - Current positions by wallet (venue=polymarket or kalshi)

Wallet Management

  • check_wallet_credentials() - Verify registered credentials
  • register_wallet_credentials() - Register Polymarket CLOB credentials
  • update_agent_sol_address() - Update agent sol_address for Kalshi flows

Trading Operations

  • trade() - Execute market order
  • get_open_orders() - List pending orders
  • get_order_history() - Order history with filters
  • get_order_detail() - Specific order details
  • cancel_order() - Cancel single order
  • cancel_all_orders() - Cancel all orders
  • redeem() - Claim market settlement rewards
  • kalshi_quote() - Create Kalshi quote (unsigned transaction)
  • kalshi_submit() - Submit signed Kalshi transaction

Error Handling

from aion_sdk import AionMarketClient, ApiError

client = AionMarketClient(api_key="your-api-key")

try:
    result = client.get_me()
except ApiError as e:
    print(f"API Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    print(f"Error Code: {e.code}")
    print(f"Raw Body: {e.response_body}")

Notes:

  • SDK no longer strips response envelopes (success/data). You get the full JSON payload.
  • For non-2xx responses, ApiError.response_body contains raw backend error JSON (for example detail, fix, hint, x402_url).
  • You can call client.request(method, path, params=..., json=...) for passthrough access.

Project Structure

aion-sdk/
├── src/
│   └── aion_sdk/
│       ├── __init__.py        # Package exports
│       └── client.py          # Main API client
├── tests/                     # Test suite
├── pyproject.toml             # Project metadata and dependencies
├── README.md                  # This file
└── LICENSE                    # MIT License

Development

Setup Development Environment

git clone https://github.com/aionmarket/aion-sdk.git
cd aion-sdk
pip install -e ".[dev]"

Run Tests

pytest
pytest --cov              # with coverage

Code Quality

black src/                # format code
isort src/                # sort imports
mypy src/                 # type checking
flake8 src/               # linting

Documentation

For detailed API documentation, visit: https://docs.aionmarket.com

Support

License

MIT License - see LICENSE file for details

Contributing

Contributions are welcome! Please submit issues and pull requests via GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aion_sdk-0.10.7.tar.gz (59.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aion_sdk-0.10.7-py3-none-any.whl (35.5 kB view details)

Uploaded Python 3

File details

Details for the file aion_sdk-0.10.7.tar.gz.

File metadata

  • Download URL: aion_sdk-0.10.7.tar.gz
  • Upload date:
  • Size: 59.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for aion_sdk-0.10.7.tar.gz
Algorithm Hash digest
SHA256 38cc5223aced1138c4c0aaf062dddd0b850be4bf8eb46e3c0dc2f16f295c83f5
MD5 c81fa18fef028a33a9e095512294b6a0
BLAKE2b-256 5b5c2fe09988054572672d09e2b63f87829ed9f99d6f2f2ea08bbc7cfcfd085a

See more details on using hashes here.

File details

Details for the file aion_sdk-0.10.7-py3-none-any.whl.

File metadata

  • Download URL: aion_sdk-0.10.7-py3-none-any.whl
  • Upload date:
  • Size: 35.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for aion_sdk-0.10.7-py3-none-any.whl
Algorithm Hash digest
SHA256 995aca37eb4de00b0d178808388d25132b0fae2725f02b968ae1d3f78910337a
MD5 014bfd1eabd14a641dc66d6261c352d8
BLAKE2b-256 fd2ab051f08a90f41182c382c66828cd05df4c8a8aa4dcbb9bd3a1395add3e24

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page