Most trading bot tutorials require 500+ lines and three npm packages before you even connect to an exchange. This isn't that tutorial.
Here's a fully autonomous trading agent — one that manages its own wallet, executes trades, and handles errors — in under 50 lines of Python using Purple Flea Trading.
#!/usr/bin/env python3
"""
Autonomous trading agent using Purple Flea Trading API.
Registers itself, fetches prices, executes momentum trades.
Full docs: https://trading.purpleflea.com/docs
Get free USDC: https://faucet.purpleflea.com
"""
import requests, time, os
TRADE = "https://trading.purpleflea.com"
WALLET = "https://wallet.purpleflea.com"
FAUCET = "https://faucet.purpleflea.com"
MY_WALLET = os.environ.get("AGENT_WALLET", "0xYourWalletHere")
# 1. Register and get API key
key = requests.post(f"{TRADE}/api/register",
json={"wallet": MY_WALLET, "name": "momentum-bot-v1"}).json()["apiKey"]
H = {"Authorization": f"Bearer {key}"}
def price(sym): return requests.get(f"{TRADE}/api/price/{sym}").json()["price"]
def bal(): return requests.get(f"{WALLET}/api/balance", headers=H).json()["balance"]
def trade(sym, side, usd): return requests.post(f"{TRADE}/api/trade",
json={"symbol": sym, "side": side, "amountUsdc": usd}, headers=H).json()
# 2. Simple momentum strategy
prices = {"BTC": [], "ETH": [], "SOL": []}
while True:
for sym in prices:
p = price(sym)
prices[sym] = (prices[sym] + [p])[-10:] # rolling 10-period window
if len(prices[sym]) < 10: continue
sma = sum(prices[sym]) / 10
balance = bal()
bet = min(balance * 0.05, 50) # risk max 5% or $50
if p > sma * 1.005 and balance > 5: # price >0.5% above SMA: buy
r = trade(sym, "buy", bet)
print(f"BUY {sym} @ {p:.2f} | SMA={sma:.2f} | ${bet:.2f} → {r.get('quantity','?')} {sym}")
elif p < sma * 0.995 and balance < 200: # price <0.5% below SMA: sell
r = trade(sym, "sell", bet)
print(f"SELL {sym} @ {p:.2f} | SMA={sma:.2f} | ${bet:.2f} ← {r.get('quantity','?')} {sym}")
time.sleep(60) # check every minute
That's 47 lines. Let me break down why each piece matters.
key = requests.post(f"{TRADE}/api/register",
json={"wallet": MY_WALLET, "name": "momentum-bot-v1"}).json()["apiKey"]
The agent registers itself on first run and gets an API key. No human auth flow. The wallet address is the agent's identity — it determines where profits land.
Before running: Claim free USDC at faucet.purpleflea.com to bootstrap your wallet.
def price(sym): return requests.get(f"{TRADE}/api/price/{sym}").json()["price"]
def bal(): return requests.get(f"{WALLET}/api/balance", headers=H).json()["balance"]
def trade(sym, side, usd): return requests.post(f"{TRADE}/api/trade", ...)
Three one-liners. Notice how the balance check uses the Wallet API — all Purple Flea services share the same wallet, so trading profits and casino winnings are in the same pot.
sma = sum(prices[sym]) / 10
if p > sma * 1.005: # buy on momentum
if p < sma * 0.995: # sell on mean reversion
Classic 10-period simple moving average. Buys when price is trending above its average, sells when it drops below. Not the fanciest strategy, but it's well-understood and has clear entry/exit signals.
bet = min(balance * 0.05, 50) # risk max 5% or $50
Kelly-inspired position sizing: never risk more than 5% of your balance per trade, hard-capped at $50. This prevents a bad trade from blowing up your account.
Want to graduate from 50 lines to 100? Add these components:
# Track open positions
open_positions = {}
def check_stop_loss():
for sym, entry_price in list(open_positions.items()):
current = price(sym)
if current < entry_price * 0.97: # -3% stop loss
r = trade(sym, "sell", 10)
print(f"STOP LOSS: sold {sym} at {current} (entry: {entry_price})")
del open_positions[sym]
prices_1h = {sym: [] for sym in ["BTC", "ETH", "SOL"]}
prices_15m = {sym: [] for sym in ["BTC", "ETH", "SOL"]}
# Only trade when short and long term agree
def signal(sym):
sma_1h = sum(prices_1h[sym][-20:]) / 20 if len(prices_1h[sym]) >= 20 else None
sma_15m = sum(prices_15m[sym][-10:]) / 10 if len(prices_15m[sym]) >= 10 else None
p = price(sym)
if sma_1h and sma_15m:
bullish_lt = p > sma_1h
bullish_st = p > sma_15m
return "buy" if (bullish_lt and bullish_st) else "sell" if (not bullish_lt and not bullish_st) else "hold"
return "hold"
TARGET_ALLOCATIONS = {"BTC": 0.5, "ETH": 0.3, "SOL": 0.2}
def rebalance():
total = bal()
portfolio = requests.get(f"{TRADE}/api/portfolio", headers=H).json()
for sym, target_pct in TARGET_ALLOCATIONS.items():
current_value = portfolio.get(sym, {}).get("valueUsdc", 0)
target_value = total * target_pct
diff = target_value - current_value
if abs(diff) > 5: # only rebalance if drift > $5
side = "buy" if diff > 0 else "sell"
trade(sym, side, abs(diff))
print(f"Rebalance: {side} {sym} ${abs(diff):.2f}")
# Save your wallet address
export AGENT_WALLET="0xYourWallet"
# Install pm2 if needed
npm install -g pm2
# Run the agent
pm2 start trading_agent.py --interpreter python3 --name "trading-agent"
# Auto-restart on reboot
pm2 startup && pm2 save
# Monitor
pm2 logs trading-agent
Agent registers itself → gets API key
Polls prices every 60 seconds
Calculates 10-period SMA
Buys on upward momentum, sells on downward momentum
All profits go directly to your wallet
All activity is logged with timestamps
Want to watch it trade? Log all trades to a database:
import sqlite3
conn = sqlite3.connect("trades.db")
conn.execute("CREATE TABLE IF NOT EXISTS trades (time, sym, side, price, amount)")
# Add to the trade() function wrapper
conn.execute("INSERT INTO trades VALUES (?,?,?,?,?)",
(time.time(), sym, side, p, bet))
conn.commit()
Get free USDC: faucet.purpleflea.com
Save the 50-line script above as
agent.pyRun:
AGENT_WALLET=0xYourWallet python3 agent.py
The agent handles everything else. Check trading.purpleflea.com and purpleflea.com for full API docs.
