Agent Bankroll Management: How AI Agents Should Think About Risk
If you give an AI agent a wallet with $100 and access to a casino API, what happens?
Most agents will bet it all in one go. They do not have an intuition for bankroll management — that is a learned behavior that humans develop over years of financial feedback.
This post is about how to write agents that manage risk intelligently. The examples use Purple Flea for the financial APIs, but the principles apply anywhere.
The Kelly Criterion
The most mathematically sound approach to position sizing is the Kelly Criterion:
f* = (bp - q) / b
Where:
-
f*= fraction of bankroll to bet -
b= odds received on the bet (net) -
p= probability of winning -
q= probability of losing (1 - p)
For a coin flip with 0.5% house edge:
- p = 0.495 (you win)
- q = 0.505 (house wins)
- b = 1 (even money)
def kelly_fraction(win_prob, payout_ratio):
"""Calculate Kelly optimal bet fraction."""
q = 1 - win_prob
b = payout_ratio
kelly = (b * win_prob - q) / b
return max(0, kelly) # Never bet negative
# Coin flip, 0.5% house edge
print(kelly_fraction(0.495, 1.0)) # -0.01 — Kelly says don't bet!
The Kelly Criterion tells us something useful: if the house edge is negative for us (as it always is in a casino), the mathematically optimal strategy is to not bet at all.
So why build agents that use a casino?
Because the casino is not the goal — it is the training environment. Agents that learn bankroll management in a casino environment develop financial judgment that applies to every other financial context: trading, escrow, wallets.
A Risk-Aware Agent
Here is an agent that limits its exposure and tracks its bankroll:
import requests
class BankrollAgent:
def __init__(self, api_key, starting_balance):
self.api_key = api_key
self.balance = starting_balance
self.starting_balance = starting_balance
self.max_drawdown = 0.3 # Stop if we lose 30%
self.max_bet_fraction = 0.02 # Never bet more than 2% of bankroll
self.session_log = []
def should_stop(self):
drawdown = (self.starting_balance - self.balance) / self.starting_balance
return drawdown >= self.max_drawdown
def calculate_bet_size(self):
return min(
self.balance * self.max_bet_fraction,
10.0 # Hard cap at $10 regardless of bankroll
)
def place_bet(self, game="coinflip", choice="heads"):
if self.should_stop():
return {"status": "stopped", "reason": "max_drawdown_reached"}
bet_size = self.calculate_bet_size()
response = requests.post(
"https://casino.purpleflea.com/v1/bet",
headers={"Authorization": f"Bearer {self.api_key}"},
json={"game": game, "amount": bet_size, "choice": choice}
).json()
if response["outcome"] == "win":
self.balance += response["payout"] - bet_size
else:
self.balance -= bet_size
self.session_log.append({
"bet": bet_size,
"outcome": response["outcome"],
"balance": self.balance
})
return response
def run_session(self, num_bets=20):
results = []
for _ in range(num_bets):
result = self.place_bet()
results.append(result)
if result.get("status") == "stopped":
break
return {
"bets_placed": len(results),
"final_balance": self.balance,
"return_pct": (self.balance - self.starting_balance) / self.starting_balance * 100,
"log": self.session_log
}
# Example usage
agent = BankrollAgent(api_key="YOUR_API_KEY", starting_balance=100.0)
session = agent.run_session(num_bets=20)
print(f"Session return: {session['return_pct']:.2f}%")
print(f"Final balance: ${session['final_balance']:.2f}")
Stop-Loss and Take-Profit
Trading intuitions apply to casino play too. An agent can implement a session stop-loss (quit if down X%) and a take-profit (quit if up Y%):
def session_limits(balance, starting, stop_loss=0.2, take_profit=0.5):
"""Returns (should_stop, reason)."""
change = (balance - starting) / starting
if change <= -stop_loss:
return True, f"stop_loss triggered at {change:.1%}"
if change >= take_profit:
return True, f"take_profit triggered at {change:.1%}"
return False, None
This is the same logic a disciplined trader uses: define your risk before you enter the position.
The Faucet Strategy: Zero-Risk Learning
The Purple Flea Faucet gives new agents free credits to try the casino. This means you can run your bankroll management code with zero real exposure:
# Register and claim free credits
reg = requests.post(
"https://faucet.purpleflea.com/v1/register",
json={"label": "bankroll-test-agent"}
).json()
claim = requests.post(
"https://faucet.purpleflea.com/v1/claim",
headers={"Authorization": f"Bearer {reg['api_key']}"}
).json()
print(f"Free credits: {claim['amount']}") # Start with free credits
# Run your risk-aware agent on the free credits
agent = BankrollAgent(api_key=reg["api_key"], starting_balance=claim["amount"])
results = agent.run_session()
Connecting to Escrow: Risk in Agent-to-Agent Transactions
Bankroll management is not just for casino play. When an agent uses escrow to pay another agent for a task, the same principles apply:
- Never lock up more than X% of your total balance in a single escrow
- Set an expiry time on escrows so locked funds are not permanently stuck
- Track your outstanding escrow obligations as part of your risk model
def safe_escrow_deposit(api_key, balance, recipient_id, task_value):
max_escrow_pct = 0.25 # Never lock more than 25% of balance in one escrow
max_deposit = balance * max_escrow_pct
deposit_amount = min(task_value, max_deposit)
if deposit_amount < task_value:
print(f"Warning: Capping escrow at {deposit_amount} (requested {task_value})")
return requests.post(
"https://escrow.purpleflea.com/v1/deposit",
headers={"Authorization": f"Bearer {api_key}"},
json={
"amount": deposit_amount,
"recipient_agent_id": recipient_id,
"expiry_hours": 24
}
).json()
Summary: Risk Principles for AI Agents
- Set a max drawdown — stop all financial activity if you lose more than X% of starting balance
- Size positions as a fraction — never bet/lock more than 1-5% of balance on any single action
- Define session limits — stop-loss and take-profit before you start, not in the moment
- Use free credits for testing — the faucet exists so you do not learn these lessons with real funds
- Model escrow as a risk — funds locked in escrow are not available; track them as a liability
The casino is a training environment. The escrow is real. Agents that learn disciplined risk management in one context will apply it to the other.
Try it: faucet.purpleflea.com — free credits to run your own bankroll experiments.
Research on emergent agent economics: doi.org/10.5281/zenodo.18808440
Top comments (0)