Optimal Gambling Algorithms

AI Agent Casino
Strategy Guide

Autonomous gambling agents don't run on hunches — they run on math. This guide covers the quantitative foundations every AI agent needs before placing a single bet: house edge reality, Kelly Criterion, martingale failure modes, crash game optimisation, and responsible bankroll management.


Algorithms, not intuition

When a human gambles, they bring cognitive biases, emotional reactions, and gut feelings to the table. When an AI agent gambles, it has only one advantage: it can be perfectly rational. But rational play in a negative-EV environment still loses money — just more slowly and predictably. This guide is not about winning; it is about understanding exactly what your agent is doing and why, so it can make informed, auditable decisions at every step.

The Purple Flea Casino API exposes four provably fair games — coin flip, dice, roulette, and crash — each with configurable parameters and a cryptographic fairness proof on every outcome. Your agent can verify every result independently. That transparency is the foundation of sound algorithmic play.

Every section below pairs the mathematical theory with Python code your agent can use directly. The code assumes you have already installed the purpleflea SDK and configured your API key. If you haven't, start with the LangChain integration guide or the Python SDK docs.


What every game
actually costs

Before writing a single line of betting logic, your agent must internalise one fact: every casino game has a negative expected value for the player. Here is the precise edge for each Purple Flea game.

Game Parameters Win Probability Payout Multiplier House Edge Verdict
Coin Flip Standard 49% 1.96x -2.0% Do not bet
Dice Roll under 50 49% 1.98x -1.0% Do not bet
Roulette European (single zero) 48.6% 1.94x -2.7% Do not bet
Crash Auto-cashout 2x 49% 2.0x -2.0% Strategy-dependent

The house edge is the percentage of every bet the casino expects to keep over infinite trials. On a coin flip with a 49% win rate and 1.96x payout, your expected return per $1 wagered is: 0.49 * 1.96 + 0.51 * 0 - 1 = -0.02. You lose two cents on average for every dollar bet. This is not a flaw or a trick — it is the mathematical definition of how casinos operate sustainably.

The only paths to long-term profit are: earning volume rebates from the platform, collecting referral commissions (Purple Flea pays 10% on all activity from referred agents), exploiting genuine informational edges if they exist, or receiving promotional bonuses whose expected value exceeds the house edge. For most agents, most of the time, the correct bet size according to optimal theory is zero.


The mathematically
optimal bet size

The Kelly Criterion tells you exactly what fraction of your bankroll to bet in order to maximise long-run geometric growth. For negative-EV games, its answer is unambiguous.

Kelly Formula

f* = (p * b - q) / b

where: p = win probability, q = loss probability (1 - p), b = net odds (payout - 1)

Coin flip: f* = (0.49 * 0.96 - 0.51) / 0.96 = -0.0208
Negative Kelly = bet zero, or take the other side
kelly.py
def kelly_fraction(win_prob: float, payout_multiplier: float) -> float: """ Returns the Kelly-optimal fraction of bankroll to bet. A negative result means: don't bet (or bet on the other side). payout_multiplier is the gross payout (e.g., 1.96 for a coin flip that returns $1.96 per $1 wagered on a win). """ p = win_prob q = 1 - p b = payout_multiplier - 1 # net odds return (p * b - q) / b # Purple Flea casino games — all return negative Kelly games = { "coin_flip": kelly_fraction(0.49, 1.96), # -0.021 "dice_u50": kelly_fraction(0.49, 1.98), # -0.010 "roulette_eu": kelly_fraction(0.486, 1.94), # -0.028 } for game, f in games.items(): verdict = "DO NOT BET" if f <= 0 else f"BET {f:.1%} of bankroll" print(f"{game}: f* = {f:.4f} → {verdict}") def should_agent_bet(ev_per_unit: float, context: str) -> bool: """ An agent should only bet if: 1. EV >= 0 (promotions, bonuses with edge), OR 2. The purpose is non-financial (testing, demo, data collection) """ if ev_per_unit >= 0: return True allowed_contexts = {"entertainment", "testing", "demo", "research"} return context in allowed_contexts

Kelly never lies. When f* is negative, the formula is telling your agent that the optimal rational action is to bet nothing. Any positive bet in a negative-EV game is a deliberate choice to trade expected value for variance — which can make sense for specific purposes (see "When Agents Should Gamble" below) but should always be explicit and logged.

For positive-EV scenarios — such as a casino bonus that effectively gives you extra equity, or a bug that creates a momentary edge — Kelly gives you the precise fraction to bet to maximise expected logarithmic bankroll growth. Use half-Kelly (f*/2) in practice to reduce variance while retaining most of the growth benefit.


Why doubling down
always fails

The martingale is the oldest and most seductive betting system. It appears to guarantee profit because you always win eventually — but that guarantee requires infinite capital, which no agent has.

The Promise

Start with $1. Double after every loss. Eventually you win, recovering all losses plus $1 profit. With infinite bankroll, this always works. The problem is the word "infinite."

The Reality

After just 10 consecutive losses (probability: 0.51^10 = 0.12% per sequence), you need to bet $1,024 to recover $1. After 20 losses, you need over $1 million. Sequences like this occur regularly at any meaningful volume.

The Fundamental Theorem of Betting Systems

E[profit] = house_edge * total_volume_wagered

This identity holds for ALL betting systems regardless of bet sizing, sequence, or strategy.
Martingale, Fibonacci, D'Alembert, Labouchere — none escape this.

The only variable you control is total volume. Lower it.
martingale_sim.py
import random def simulate_martingale( starting_bankroll: float, base_bet: float, win_prob: float, max_rounds: int = 10_000 ) -> dict: bankroll = starting_bankroll bet = base_bet total_wagered = 0 rounds = 0 while rounds < max_rounds and bankroll >= bet: total_wagered += bet if random.random() < win_prob: bankroll += bet # net win bet = base_bet # reset else: bankroll -= bet bet *= 2 # double after loss rounds += 1 expected_loss = 0.02 * total_wagered # 2% house edge actual_loss = starting_bankroll - bankroll return { "rounds": rounds, "final_bankroll": bankroll, "total_wagered": total_wagered, "actual_loss": actual_loss, "expected_loss": expected_loss, "bust": bankroll < base_bet, } # Result: actual_loss converges to expected_loss, bust rate is high # Agents must NEVER use martingale for serious bankroll management

Auto-cashout strategy
for crash games

Crash is unique among casino games because the player chooses their cashout target. This gives agents a configurable parameter to reason about — though it does not change the negative EV.

In a crash game, a multiplier grows from 1x upward and crashes at a random point drawn from an exponential-like distribution engineered to produce a specific house edge. If you cash out before the crash, you win your bet multiplied by your cashout target. If the game crashes before you cash out, you lose your bet.

For a game with house edge h, the probability that the crash point exceeds a target multiplier m is approximately (1 - h) / m. At a 2% house edge and a 2x cashout target: P(survive to 2x) = 0.98 / 2 = 0.49. The expected value per bet is:

EV at any auto-cashout target (2% house edge)

P(crash above m) = 0.98 / m

EV(2x cashout) = 0.49 * 2 + 0.51 * 0 - 1 = -0.02
EV(10x cashout) = 0.098 * 10 + 0.902 * 0 - 1 = -0.02

EV = -0.02 regardless of cashout target. Target only affects variance.
crash_agent.py
import purpleflea client = purpleflea.Client(api_key="pf_sk_...") def play_crash( bet_amount: float, cashout_target: float, house_edge: float = 0.02 ) -> dict: """ Place a crash bet with automatic cashout at cashout_target. Lower targets: higher win rate, lower variance, same EV. Higher targets: lower win rate, higher variance, same EV. For agent testing, 2x is a reasonable default (49% win rate). """ win_prob = (1 - house_edge) / cashout_target ev = win_prob * cashout_target - 1 result = client.casino.crash( amount=bet_amount, auto_cashout=cashout_target, ) # Verify the outcome cryptographically verified = client.casino.verify( game_id=result["game_id"], server_seed=result["server_seed"], client_seed=result["client_seed"], ) assert verified["crash_point"] == result["crash_point"], "Fairness check failed!" return { "win": result["win"], "crash_point": result["crash_point"], "pnl": result["pnl"], "expected_ev": ev, "verified": True, }

When agents
should gamble

There are five legitimate reasons for an AI agent to engage with a casino API. Understanding the purpose before placing a bet is the most important guardrail of all.

  • 1
    Entertainment or demonstration. An agent showing its capabilities to a user may place a small number of bets with a pre-defined budget to demonstrate real financial activity. Set a hard cap (e.g., $5 total) before starting.
  • 2
    Testing provably fair verification pipelines. The mathematical integrity of the fairness proof matters for trust. Agents may place bets specifically to exercise their verification logic and confirm outcomes are auditable end-to-end.
  • 3
    Collecting data for strategy research. Running controlled trials across different bet sizes, cashout targets, or game configurations to build empirical distributions for analysis — provided the research budget is explicitly allocated and pre-approved.
  • 4
    Positive-EV promotional scenarios. When a casino bonus, reload offer, or promotional multiplier creates a scenario where EV >= 0, Kelly says bet. Calculate the adjusted win probability including the bonus before committing any bankroll.
  • 5
    Agent capability demonstrations. As part of a broader showcase of what the agent can do — send crypto, trade perps, register a domain, place a bet — casino play serves as a concrete proof of real-world action capability with verifiable on-chain effects.

Rules for responsible
agent gambling

Even when gambling is justified, disciplined bankroll management is non-negotiable. An agent that blows its entire budget on the first session cannot complete any other tasks.

Hard Stop-Loss

If bankroll drops 50% from starting value, stop entirely. No exceptions. Loss chasing is the most common failure mode for both human and agent gamblers. Code it as an assert, not a suggestion.

Fixed Fraction Betting

Bet between 1% and 5% of current bankroll per wager. This is a diluted Kelly approach that limits ruin risk while maintaining meaningful activity. Never bet more than 5% on a single game with negative EV.

Never Chase Losses

Increasing bet size after a loss to recover is mathematically equivalent to martingale — it magnifies volume and thus magnifies expected losses. Each bet should be sized on current bankroll, not on history.

Full Audit Trail

Every bet must be logged with: timestamp, game type, bet amount, outcome, cumulative P&L, and the provably fair verification hash. Agents operating with user funds must be fully auditable at all times.

bankroll_manager.py
from dataclasses import dataclass, field from datetime import datetime from typing import Optional import json @dataclass class BankrollManager: starting_bankroll: float max_bet_fraction: float = 0.02 # 2% per bet default stop_loss_fraction: float = 0.50 # halt at 50% drawdown current_bankroll: float = 0.0 bets: list = field(default_factory=list) def __post_init__(self): self.current_bankroll = self.starting_bankroll def can_bet(self) -> bool: drawdown = (self.starting_bankroll - self.current_bankroll) / self.starting_bankroll return drawdown < self.stop_loss_fraction def get_bet_size(self) -> float: if not self.can_bet(): raise RuntimeError("Stop-loss triggered. No more bets this session.") return self.current_bankroll * self.max_bet_fraction def record_bet(self, game: str, amount: float, pnl: float, game_id: str, verify_hash: str): self.current_bankroll += pnl self.bets.append({ "ts": datetime.utcnow().isoformat(), "game": game, "amount": amount, "pnl": pnl, "balance_after": self.current_bankroll, "game_id": game_id, "verify_hash": verify_hash, }) def export_log(self) -> str: return json.dumps(self.bets, indent=2) def summary(self) -> dict: total_wagered = sum(b["amount"] for b in self.bets) return { "bets_placed": len(self.bets), "total_wagered": total_wagered, "net_pnl": self.current_bankroll - self.starting_bankroll, "current_bankroll": self.current_bankroll, "active": self.can_bet(), }

Using the API
responsibly

All Purple Flea casino games are provably fair. Your agent can and should verify every single outcome independently — the cryptographic proof is included in every API response.

Provably Fair

Every game outcome is derived from a server seed committed before the bet and revealed after, combined with your client seed. Verify with POST /casino/verify.

📄

Bet History

Retrieve complete bet history via GET /casino/history. Filter by game type, date range, or outcome. Essential for your agent's audit trail and P&L reporting.

Agent Limits

The API has no built-in spending limits — your agent is responsible for enforcing them in code. Use BankrollManager above or equivalent logic. Never assume the API will stop you.

responsible_agent.py
import purpleflea from bankroll_manager import BankrollManager client = purpleflea.Client(api_key="pf_sk_...") bankroll = BankrollManager(starting_bankroll=10.0) # $10 demo budget def responsible_coin_flip() -> dict: # 1. Check stop-loss before every bet if not bankroll.can_bet(): return {"error": "Stop-loss active. Session ended."} # 2. Size bet using fixed-fraction rule bet_size = bankroll.get_bet_size() # 3. Place the bet result = client.casino.flip_coin(amount=bet_size, side="heads") # 4. Verify the outcome immediately proof = client.casino.verify(game_id=result["game_id"]) assert proof["valid"], "Fairness verification failed!" # 5. Record in audit log bankroll.record_bet( game="coin_flip", amount=bet_size, pnl=result["pnl"], game_id=result["game_id"], verify_hash=proof["hash"], ) return {"result": result, "summary": bankroll.summary()}

Ready to build a
smarter gambling agent?

Register your agent, get an API key, and start verifying provably fair outcomes programmatically.