Python SDK for AgentBroker — programmatic crypto trading for autonomous agents
Project description
AgentBroker Python SDK
Official Python SDK for AgentBroker — the non-custodial crypto trading platform built for autonomous agents on Jupiter DEX (Solana).
Features
- Async-first client (
AgentBrokerClient) built onhttpx— runs cleanly underasyncio, FastAPI, Discord bots, etc. - Sync wrapper (
AgentBroker) — backward-compatible with the existing v1.x API. - Non-custodial trading — your wallet signs the Jupiter swap; AgentBroker never holds your private key.
- Typed response models — every API response is parsed into a
dataclassyou can autocomplete against. - Typed exceptions —
AuthenticationError,NotFoundError,RateLimitError,ServerError, etc. — all subclasses ofAgentBrokerError. - WebSocket helpers — decorator-style event handlers with auto-reconnect (optional
agentbroker[ws]extra).
Installation
pip install agentbroker
With WebSocket support:
pip install "agentbroker[ws]"
Quickstart (5 lines)
pip install agentbroker → working trade in 5 lines of Python:
from agentbroker import AgentBrokerClient
import asyncio
client = AgentBrokerClient(api_key="ab_live_...")
async def main():
acct = await client.get_account()
trade = await client.trade("SOL", "USDC", amount_sol=0.1)
asyncio.run(main())
That's it — the asyncio plumbing is already wired up.
Sync wrapper (backward-compatible)
Existing v1.x users keep working unchanged:
from agentbroker import AgentBroker
client = AgentBroker(api_key="ab_live_...")
acct = client.get_account()
order = client.place_order("BTC-USDC", "buy", "market", quantity=0.001)
Both classes ship from agentbroker — pick the one that matches your runtime.
Non-custodial registration (new agents)
import asyncio
from agentbroker import AgentBrokerClient
async def register():
async with AgentBrokerClient() as client:
agent = await client.register(
wallet_address="9B5X5AF5zxkXk7gw7Xj7t3rK4vN2mL1pQ8sR6tU5vW4",
name="my-trading-bot",
email="me@example.com",
)
print(agent.api_key) # ← save this — shown ONCE
asyncio.run(register())
The returned api_key authenticates every subsequent request. The agent's own Solana wallet signs and submits the unsigned trade() output — AgentBroker never touches your private key.
Features in depth
- Full API coverage — registration (legacy + non-custodial), orders, deposits, market data, WebSocket streaming.
- Type hints throughout — autocomplete-friendly with
dataclassresponse models (Agent,Account,DiscoveredToken,TradeResult, ...). - Smart error handling — typed exceptions for auth failures, insufficient balance, not found, rate limit, server errors, etc.
API Reference
AgentBrokerClient(api_key=None, base_url=None, timeout=30.0)
Async client. Use this for all new code.
client = AgentBrokerClient(api_key="ab_live_...", timeout=30.0)
async with client:
...
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key |
str |
None |
API key (required for authenticated endpoints; not needed for register or discover) |
base_url |
str |
https://agentbroker.polsia.app |
API base URL |
timeout |
float |
30.0 |
HTTP request timeout in seconds |
Registration & Account
| Method | Returns | Description |
|---|---|---|
await client.register(wallet_address, name=None, email=None, ...) |
Agent |
Register a non-custodial agent using your own Solana wallet (no API key needed) |
await client.get_account() |
Account |
Balance + totals summary |
await client.get_balance() |
float |
Current USDC balance, as a float |
# Non-custodial register
agent = await client.register(
wallet_address="9B5X5AF5zxkXk7gw7Xj7t3rK4vN2mL1pQ8sR6tU5vW4",
name="my-bot",
email="me@example.com",
)
print(agent.api_key) # save it!
# Account
acct = await client.get_account()
print(acct.balance_usdc)
Discovery
| Method | Returns | Description |
|---|---|---|
await client.discover(limit=20, strategy='trending') |
list[DiscoveredToken] |
Trending tokens + recent launches + recently-active |
tokens = await client.discover(limit=10)
for t in tokens[:5]:
print(f"{t.symbol} ({t.type}) — price: {t.price} — liq: {t.liquidity_usd}")
Trading (non-custodial)
| Method | Returns | Description |
|---|---|---|
await client.trade(token_in, token_out, amount_sol, slippage_bps=50, side=None) |
TradeResult |
Build an unsigned Jupiter swap — your wallet signs + submits |
side is auto-detected from the symbol pair (SOL→USDC = buy, USDC→SOL = sell); pass it explicitly to override. The result contains a base64 unsigned_transaction ready for your wallet to sign, plus the Jupiter quote, expected_output_amount, and the trade_id you'll later confirm via POST /v1/trades/swap-confirm.
trade = await client.trade(
token_in="SOL",
token_out="USDC",
amount_sol=0.1,
slippage_bps=50, # 0.5% default
)
print(f"trade_id {trade.trade_id}: {trade.unsigned_transaction[:40]}…")
print(f"expected out: {trade.expected_output_amount} atomic units")
To execute end-to-end: sign unsigned_transaction in your wallet, broadcast on Solana mainnet, then call swap-confirm with the resulting signature.
Trades (history)
| Method | Returns | Description |
|---|---|---|
await client.get_trades(base_symbol=None, limit=50) |
list[Trade] |
Recent trades for this agent |
WebSocket
ws = await client.connect_ws() # requires agentbroker[ws]
@ws.on_trade
def on_trade(event): ...
ws.run_forever()
Channels: "trades", "balance", "orderbook", "prices".
Exceptions
from agentbroker.exceptions import (
AgentBrokerError, # Base class
AuthenticationError, # 401 — missing/invalid API key
ValidationError, # 400 — bad request params
InsufficientBalanceError,# 400 with code INSUFFICIENT_BALANCE
NotFoundError, # 404 — resource not found
RateLimitError, # 429 — too many requests
ServerError, # 5xx — server-side error
ConnectionError, # Network failure
TimeoutError, # Request timed out
WebSocketError, # WS connection issues
)
try:
trade = await client.trade("SOL", "USDC", amount_sol=10_000)
except InsufficientBalanceError as e:
print(f"Need {e.required} USDC, have {e.available} USDC")
except AuthenticationError:
print("Check your API key")
except AgentBrokerError as e:
print(f"[{e.code}] {e.message}")
Legacy sync API (AgentBroker)
If you're not running under asyncio, the AgentBroker class is a thin synchronous wrapper around AgentBrokerClient (v1.x users keep their existing code).
from agentbroker import AgentBroker
client = AgentBroker(api_key="ab_live_...")
# Same names, same dataclasses — backward-compatible
profile = client.get_profile()
order = client.place_order("BTC-USDC", "buy", "market", quantity=0.001)
The original classmethod registration path is preserved:
agent = AgentBroker.register(
name="quickstart-bot",
email="trader@example.com",
preferred_pairs=["BTC-USDC", "ETH-USDC"],
)
print(agent.api_key)
Examples
| File | Description |
|---|---|
examples/async_basics.py |
Register / account / discover / trade (async) |
examples/basic_trade.py |
Register, deposit, place market + limit orders (sync) |
examples/momentum_bot.py |
Trend-following bot with stop-loss + WebSocket balance updates |
examples/arbitrage_scanner.py |
Scan order books for wide spreads + triangular arb signals |
Run any example:
export AGENTBROKER_API_KEY=ab_live_your_key_here
python examples/async_basics.py
Environment Variables
| Variable | Description |
|---|---|
AGENTBROKER_API_KEY |
Your API key (used by examples) |
AGENTBROKER_BASE_URL |
Override base URL (default: https://agentbroker.polsia.app) |
Development
git clone https://github.com/Polsia-Inc/agentbroker
cd agentbroker/python-sdk
pip install -e ".[dev]"
# Run tests
pytest
# Format
black agentbroker/ examples/
isort agentbroker/ examples/
# Type check
mypy agentbroker/
# Build wheel + sdist
python -m build
License
MIT © AgentBroker
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file agentbroker-1.1.0.tar.gz.
File metadata
- Download URL: agentbroker-1.1.0.tar.gz
- Upload date:
- Size: 19.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cec5def2df960381ad76a9c46a3a681cfdf8fb96f4496438aecdf20b22b22979
|
|
| MD5 |
dd26363c09bb3fc1e06eaa793cc35180
|
|
| BLAKE2b-256 |
b764d12aaeb5127c691be8071f5db8bd6806b212f552e9eb456bc4779191525a
|
Provenance
The following attestation bundles were made for agentbroker-1.1.0.tar.gz:
Publisher:
publish-pypi.yml on Polsia-Inc/agentbroker
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
agentbroker-1.1.0.tar.gz -
Subject digest:
cec5def2df960381ad76a9c46a3a681cfdf8fb96f4496438aecdf20b22b22979 - Sigstore transparency entry: 2166764081
- Sigstore integration time:
-
Permalink:
Polsia-Inc/agentbroker@646d0f155c3f053a9c53cb29a967260638311cba -
Branch / Tag:
refs/heads/main - Owner: https://github.com/Polsia-Inc
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yml@646d0f155c3f053a9c53cb29a967260638311cba -
Trigger Event:
push
-
Statement type:
File details
Details for the file agentbroker-1.1.0-py3-none-any.whl.
File metadata
- Download URL: agentbroker-1.1.0-py3-none-any.whl
- Upload date:
- Size: 17.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
057e2dc3997524c87b553899100e2da0a8e5f546d2b14b2f8b671f79281a0f1f
|
|
| MD5 |
318ff5080d780516a9485bfb48ab2c11
|
|
| BLAKE2b-256 |
ec77e2d7b374efb66c9560cf34d3e9f22528ac35616d9ee55c94207aa31145a7
|
Provenance
The following attestation bundles were made for agentbroker-1.1.0-py3-none-any.whl:
Publisher:
publish-pypi.yml on Polsia-Inc/agentbroker
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
agentbroker-1.1.0-py3-none-any.whl -
Subject digest:
057e2dc3997524c87b553899100e2da0a8e5f546d2b14b2f8b671f79281a0f1f - Sigstore transparency entry: 2166764085
- Sigstore integration time:
-
Permalink:
Polsia-Inc/agentbroker@646d0f155c3f053a9c53cb29a967260638311cba -
Branch / Tag:
refs/heads/main - Owner: https://github.com/Polsia-Inc
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yml@646d0f155c3f053a9c53cb29a967260638311cba -
Trigger Event:
push
-
Statement type: