What we're building
Most trading bot tutorials make you wire up your own broker, handle WebSocket reconnects, manage authentication, and figure out order routing before you've written a single strategy line. AgentBroker removes all of that.
In this tutorial we'll write a momentum trading bot that:
- Registers itself on AgentBroker — no credit card, no KYC
- Deposits real USDC to fund the agent
- Streams real-time BTC/USDC prices via WebSocket
- Buys when price is up 1% over the last 5 minutes
- Sells when price drops 1% from entry (stop-loss / exit)
The whole bot fits in about 50 lines of Python. Let's go.
Installation
The AgentBroker Python SDK is on PyPI. Install it with WebSocket support:
bash
pip install "agentbroker[ws]"
The [ws] extra pulls in websocket-client, which you'll need for the streaming price feed.
If you just want the REST API, plain pip install agentbroker is enough.
Register your agent
Every bot on AgentBroker is an agent — a named identity with its own balance, trade history, and strategy settings. You create one with a single call:
python
from agentbroker import AgentBroker
agent = AgentBroker.register(name="my-bot")
print(agent.api_key) # ab_live_sk_xxxxxxxxxxxxxxxxxxxx
print(agent.deposit_address) # send USDC here to fund your agent
Save that API key. On the next run you pass it in directly instead of registering again:
python
import os
from agentbroker import AgentBroker
api_key = os.environ.get("AGENTBROKER_API_KEY", "")
if api_key:
client = AgentBroker(api_key=api_key)
else:
agent = AgentBroker.register(name="my-bot")
print(f"Save your key: export AGENTBROKER_API_KEY={agent.api_key}")
client = AgentBroker(api_key=agent.api_key)
This pattern — check env var first, register if missing — means the bot is fully self-contained. Drop it on any machine and it just works.
Fetch live prices via WebSocket
AgentBroker pushes price ticks to connected agents roughly every 30 seconds. The SDK wraps the WebSocket with a clean event API:
python
ws = client.connect_ws()
@ws.on_connected
def on_connect():
print("✓ Connected — streaming prices")
@ws.on_price
def on_price(tick):
pair = tick.get("pair") # e.g. "BTC-USDC"
price = float(tick.get("price", 0))
print(f"{pair}: ${price:,.2f}")
ws.connect() # non-blocking background thread
ws.connect() starts a background thread. Your main thread keeps running — you just need to keep it alive
(a simple while True: time.sleep(1) at the bottom is enough).
You also get @ws.on_trade and @ws.on_balance for fills and balance updates.
Trading logic
Our strategy is momentum: if price is up 1% over the last 10 ticks (~5 minutes), buy. If price drops 1% from our entry, sell.
We track price history in a deque with a fixed window:
python
from collections import deque
WINDOW = 10 # ~5 min of ticks
BUY_THRESHOLD = 0.01 # +1% → buy signal
SELL_THRESHOLD = 0.01 # -1% from entry → sell signal
prices = deque(maxlen=WINDOW)
position = None # None = flat, dict = in position
def momentum_signal(prices):
if len(prices) < WINDOW:
return "hold"
change = (prices[-1] - prices[0]) / prices[0]
if change >= BUY_THRESHOLD: return "buy"
if change <= -SELL_THRESHOLD: return "sell"
return "hold"
The deque(maxlen=WINDOW) automatically drops old values — no manual sliding window needed.
Clean Python.
Place buy & sell orders
Once we have a signal, placing an order is one line:
python
POSITION_USD = 500 # USDC to deploy per trade
# Buy
qty = round(POSITION_USD / price, 6)
order = client.place_order("BTC-USDC", "buy", "market", quantity=qty)
print(f"Bought {order.filled_quantity} BTC @ ${price:,.2f}")
# Sell
order = client.place_order("BTC-USDC", "sell", "market", quantity=position["qty"])
print(f"Sold — balance now {order.balance_usdc} USDC")
The order object comes back with filled_quantity, status, balance_usdc,
and order_id. Market orders fill based on live Jupiter DEX prices.
POSITION_USD amount per trade.
Real bots should account for slippage, fees, and Kelly criterion. This tutorial keeps it simple.
The full 50-line bot
Here's everything together. Copy it, run it, watch it trade:
python — bot.py
import os, time
from collections import deque
from agentbroker import AgentBroker
# ── Config ────────────────────────────────────────────────────────────────────
PAIR = "BTC-USDC"
BUY_THRESHOLD = 0.01 # buy when price is +1% vs 5-min ago
SELL_THRESHOLD = 0.01 # sell when price is -1% from entry
POSITION_USD = 500 # USDC to deploy per trade
WINDOW = 10 # price ticks to track (~5 min)
# ── Auth: reuse saved key or register fresh agent ─────────────────────────────
api_key = os.environ.get("AGENTBROKER_API_KEY", "")
if api_key:
client = AgentBroker(api_key=api_key)
else:
agent = AgentBroker.register(name="my-bot")
print(f" Save your key: export AGENTBROKER_API_KEY={agent.api_key}")
client = AgentBroker(api_key=agent.api_key)
client.select_strategy("momentum")
profile = client.get_profile()
print(f"Ready balance={profile.balance_usdc} USDC mode={profile.mode}\n")
# ── State ─────────────────────────────────────────────────────────────────────
prices = deque(maxlen=WINDOW)
position = None # None = flat | dict = {entry, qty}
# ── WebSocket price handler ───────────────────────────────────────────────────
ws = client.connect_ws()
@ws.on_price
def on_price(tick):
global position
price = float(tick.get("price", 0))
if tick.get("pair") != PAIR or price <= 0:
return
prices.append(price)
if len(prices) < WINDOW:
print(f" ${price:,.2f} warming up ({len(prices)}/{WINDOW})")
return
change = (price - prices[0]) / prices[0]
status = f"IN @ ${position['entry']:,.2f}" if position else "flat"
print(f" {PAIR}: ${price:,.2f} {change:+.2%} vs 5m [{status}]")
if change >= BUY_THRESHOLD and not position:
qty = round(POSITION_USD / price, 6)
order = client.place_order(PAIR, "buy", "market", quantity=qty)
position = {"entry": price, "qty": float(order.quantity)}
print(f" ✓ BUY {qty} BTC @ ${price:,.2f}")
elif position:
drop = (price - position["entry"]) / position["entry"]
if change <= -SELL_THRESHOLD or drop <= -SELL_THRESHOLD:
client.place_order(PAIR, "sell", "market", quantity=position["qty"])
print(f" ✓ SELL @ ${price:,.2f} pnl={drop:+.2%}")
position = None
ws.connect()
print("Bot running — press Ctrl+C to stop\n")
while True:
time.sleep(1)
That's it. 50 lines including config, auth, state, WebSocket handling, and order placement.
Run it
First run (auto-registers a live agent)
bash
pip install "agentbroker[ws]"
python bot.py
Subsequent runs (reuse saved agent)
bash
export AGENTBROKER_API_KEY=ab_sk_x9vKmQ3...
python bot.py
What's next
This bot is a starting point. Here's where you can take it:
| Enhancement | How |
|---|---|
| Multi-pair | Subscribe to ETH-USDC, SOL-USDC — the same WebSocket delivers all pairs |
| Adjustable thresholds | Tweak BUY_THRESHOLD and SELL_THRESHOLD — lower = more trades, higher = fewer |
| Strategy switching | Try client.select_strategy("mean_reversion") for a different approach |
| Go live | Register with just your name — no mode param needed. Deposit USDC to start trading. |
| AI-driven signals | Feed price history to Claude or GPT and let the model decide buy/sell instead of hardcoded thresholds |
Ready to run your own agent?
Register instantly — no credit card, no KYC. Deposit real USDC to start.
Get your API key →