Access uncollateralized capital in a single transaction block. Purple Flea's flash loan API lets AI agents borrow millions, execute arbitrage or liquidations, and repay — all atomically, all within one API call.
Flash loans are uncollateralized loans that exist for exactly one blockchain transaction. If the loan isn't repaid within the same transaction, the entire operation reverts — making them risk-free for lenders and powerful for sophisticated agents.
Step 1
Borrow
Agent requests $500K USDC with zero collateral. Funds transferred instantly.
Step 2
Execute
Agent runs arbitrage, liquidates a position, or swaps collateral using borrowed capital.
Step 3
Repay
Agent repays loan + 0.09% fee from profits. All in the same transaction.
Step 4
Profit
Agent keeps the spread. If repayment fails, the entire tx reverts — no loss.
🔄
DEX Arbitrage
Exploit price discrepancies between Uniswap, Curve, and Balancer. Borrow $1M USDC, buy ETH cheap on one DEX, sell high on another, repay loan. Keep the spread minus 0.09%.
💧
Liquidation Bots
Liquidate undercollateralized Aave or Compound positions. Flash borrow the repayment amount, liquidate at a discount, sell collateral, repay flash loan — all atomically.
🔀
Collateral Swaps
Swap your loan's collateral type without closing the position. Flash borrow new asset, repay old collateral, swap, redeposit — collateral changed in one tx, position stays open.
📐
Self-Liquidation
Agents can self-liquidate unhealthy positions to avoid penalties. Flash borrow to repay debt, withdraw collateral, repay flash loan — avoids liquidator taking the discount.
⚖️
Interest Rate Arbitrage
Move debt between protocols atomically. Flash borrow to repay Aave, deposit elsewhere for lower rate, repay flash loan. Save basis points on large positions without closing anything.
🏗️
Leveraged Positions
Open leveraged yield positions in a single transaction. Flash borrow, deposit into yield vault for leveraged receipt tokens, use tokens as collateral, repay flash loan — instant leverage.
Flash Loan Arbitrage Bot
A complete DEX arbitrage agent using Purple Flea's flash loan API. The agent scans price discrepancies and executes profitable flips atomically.
# flash_arb_agent.py — DEX arbitrage with flash loansimport requests, time
from typing import Optional
PURPLE_FLEA_API = "https://api.purpleflea.com/v1"
API_KEY = "pf_your_key_here"
HEADERS = {"X-API-Key": API_KEY}
classFlashArbitragent:
def__init__(self, wallet_id: str, min_profit_usd: float = 50.0):
self.wallet_id = wallet_id
self.min_profit_usd = min_profit_usd
defscan_opportunities(self) -> list:
# Purple Flea returns arbitrage opportunities across DEXes
r = requests.get(
f"{PURPLE_FLEA_API}/flash-loans/opportunities",
headers=HEADERS,
params={"min_profit_usd": self.min_profit_usd, "chains": "eth,arb,matic"}
)
r.raise_for_status()
return r.json()["opportunities"]
defsimulate_flash_loan(self, opportunity: dict) -> dict:
# Simulate before executing — gas costs, slippage, net profit
r = requests.post(
f"{PURPLE_FLEA_API}/flash-loans/simulate",
json={"opportunity_id": opportunity["id"], "wallet_id": self.wallet_id},
headers=HEADERS
)
r.raise_for_status()
return r.json()
defexecute_flash_arb(self, opportunity: dict) -> Optional[dict]:
# First simulate — never execute without simulation
sim = self.simulate_flash_loan(opportunity)
if not sim["profitable"]:
print(f"Simulation unprofitable: {sim['reason']}")
return None
net_profit = sim["net_profit_usd"]
print(f"Simulated profit: ${net_profit:.2f}. Executing...")
# Execute atomic flash loan bundle
payload = {
"wallet_id": self.wallet_id,
"loan_asset": opportunity["asset"], # e.g., "USDC""loan_amount": opportunity["loan_amount"],
"strategy": opportunity["strategy"], # "dex_arbitrage""route": opportunity["route"], # buy on Uniswap, sell on Curve"slippage_tolerance": 0.005, # 0.5%"max_gas_gwei": 30
}
r = requests.post(f"{PURPLE_FLEA_API}/flash-loans/execute", json=payload, headers=HEADERS)
r.raise_for_status()
result = r.json()
if result["status"] == "success":
print(f"Flash arb executed: ${result['actual_profit_usd']:.2f} profit — tx: {result['tx_hash']}")
else:
print(f"Execution failed: {result['error']} (tx reverted, no loss)")
return result
defrun(self):
while True:
opps = self.scan_opportunities()
print(f"Found {len(opps)} opportunities above ${self.min_profit_usd}")
for opp in opps:
self.execute_flash_arb(opp)
time.sleep(5) # scan every 5 secondsif __name__ == "__main__":
bot = FlashArbitragent(wallet_id="wallet_abc123", min_profit_usd=25)
bot.run()
Flash Loan API Reference
# POST /flash-loans/execute# Execute an atomic flash loan bundle
{
"wallet_id": "wallet_abc123",
"loan_asset": "USDC", // Asset to borrow"loan_amount": 500000, // Amount in base units"strategy": "dex_arbitrage", // or "liquidation", "collateral_swap""route": {
"buy_dex": "uniswap_v3",
"sell_dex": "curve",
"token": "WETH"
},
"slippage_tolerance": 0.005, // 0.5%"max_gas_gwei": 30
}
# Response on success:
{
"status": "success",
"tx_hash": "0xabc...",
"loan_amount": 500000,
"loan_fee_usd": 450, // 0.09% of $500K"gross_profit_usd": 1820,
"gas_cost_usd": 47,
"actual_profit_usd": 1323,
"block_number": 19482710
}
# Response on revert (no loss):
{
"status": "reverted",
"error": "slippage_exceeded",
"actual_profit_usd": 0,
"gas_cost_usd": 0// Reverted txs cost no gas
}
Important Risk Disclosures
Flash loans are complex DeFi primitives. Before building agents that use them, understand:
Flash loan opportunities close within milliseconds — your agent competes with MEV bots running custom validators
Gas costs can exceed profit on congested networks — always simulate before executing
Reverted transactions still cost some gas (base fee) on EVM chains — failed simulations save this cost
Purple Flea's 0.09% fee applies to all flash loans — ensure the spread covers fees before executing
DEX price discovery is not guaranteed — slippage can eliminate or reverse profitability
Simulate Before Every Execution
The /flash-loans/simulate endpoint runs an off-chain simulation of the full flash loan bundle, including gas estimation, expected slippage, DEX routing, and net profit calculation. Only proceed with execution when the simulation confirms profitability — this is the discipline that separates successful flash loan bots from expensive failures.
Access Uncollateralized Capital Atomically
Purple Flea's flash loan API gives AI agents access to liquidity that would otherwise require millions in capital. Get started with an API key and run your first arbitrage simulation today.