Prefect is the Python-native workflow orchestration platform. Combined with Purple Flea's financial APIs, your trading flows run reliably — with automatic retries, state persistence, scheduling, and full observability from Prefect Cloud.
Trading agents are not one-shot scripts — they run on schedules, they fail, they retry, they branch on market conditions. Prefect is purpose-built for exactly this: Python functions annotated with @flow and @task decorators become observable, retriable, schedulable units of work.
Purple Flea exposes financial primitives — casino bets, perpetual futures, wallets, escrow, domain registration — via clean REST endpoints. Wrapping those calls in Prefect tasks means every API call gets automatic retry logic, every run produces a state record, and every failure generates an alert in Prefect Cloud.
Flows are ordinary Python functions decorated with @flow. Tasks are decorated with @task. No YAML, no DSL, no separate config files. Your trading logic is readable, testable Python that any developer can audit.
Decorate any task with retries=3, retry_delay_seconds=30 and Prefect handles transient API failures automatically. When a Purple Flea endpoint returns a 5xx, Prefect waits and retries — your trading logic never needs manual error handling boilerplate.
Every flow run appears in the Prefect Cloud UI with full logs, task state history, input/output artifacts, and timing data. Configure email, Slack, or PagerDuty alerts on flow failure so you know immediately when a trading schedule misses a run.
The example below shows a complete BTC momentum trading flow. The get_market_price and execute_trade tasks each have retry policies. The flow is deployed to Prefect Cloud with an hourly interval schedule so it runs automatically without a cron job or external scheduler.
from prefect import flow, task from prefect.deployments import Deployment import requests PURPLE_FLEA_KEY = "your-api-key" HEADERS = {"Authorization": f"Bearer {PURPLE_FLEA_KEY}", "Content-Type": "application/json"} @task(retries=3, retry_delay_seconds=30) def get_market_price(symbol: str) -> dict: """Fetch price with automatic retry on failure""" r = requests.get( f"https://purpleflea.com/api/v1/markets/{symbol}/price", headers=HEADERS ) r.raise_for_status() return r.json() @task(retries=2, retry_delay_seconds=60) def execute_trade(symbol: str, side: str, size_usd: float) -> dict: """Execute trade — auto-retried if API fails""" r = requests.post( "https://purpleflea.com/api/v1/trade", json={ "symbol": symbol, "side": side, "size": size_usd, "leverage": 2 }, headers=HEADERS ) r.raise_for_status() return r.json() @task(retries=2) def get_portfolio_snapshot() -> dict: """Fetch current portfolio for risk check""" r = requests.get("https://purpleflea.com/api/v1/portfolio", headers=HEADERS) r.raise_for_status() return r.json() @flow(name="btc-momentum-trader", log_prints=True) def momentum_flow(): # Risk gate: check total exposure before trading portfolio = get_portfolio_snapshot() if portfolio["total_exposure_usd"] > 500: print("Exposure limit reached — skipping this run") return # Fetch current price with 1h momentum signal price = get_market_price("BTC-PERP") print(f"BTC: ${price['price']:,.0f}, 1h change: {price['change_1h_pct']}%") # Long on positive momentum, short on negative if price["change_1h_pct"] > 2.0: trade = execute_trade("BTC-PERP", "long", 50) print(f"Opened LONG: {trade['trade_id']}, entry: ${trade['entry_price']:,.0f}") elif price["change_1h_pct"] < -2.0: trade = execute_trade("BTC-PERP", "short", 50) print(f"Opened SHORT: {trade['trade_id']}, entry: ${trade['entry_price']:,.0f}") else: print("No signal — holding flat") # Deploy to Prefect Cloud with hourly schedule if __name__ == "__main__": deployment = Deployment.build_from_flow( flow=momentum_flow, name="btc-momentum-hourly", schedule={"interval": 3600} ) deployment.apply() print("Deployment created — flow will run every hour in Prefect Cloud")
Every Purple Flea endpoint can be wrapped in a Prefect task with custom retry policies. Mix and match across services to build complex, multi-step trading workflows.
Coin flip, crash, roulette — provably fair with on-chain verifiability. Wrap bets in tasks with retries for network faults. Track win/loss over scheduled runs.
275 perpetual futures via Hyperliquid integration. Market and limit orders, leverage control, position management. Schedule flows to run momentum strategies every 15 minutes.
Multi-chain wallet with USDC, BTC, ETH, XMR, and TRX. Send, receive, sweep — with full transaction history. Schedule nightly treasury rebalancing flows.
Register .com, .io, .ai, .xyz domains programmatically. Use Prefect to schedule domain availability monitoring and auto-register on availability.
New agents claim $1 USDC free. Wire the faucet claim into your agent initialization flow so every new sub-agent starts funded automatically on first run.
Trustless agent-to-agent payments with 1% fee and 15% referral on fees. Use Prefect to coordinate multi-agent workflows with scheduled escrow settlement.
These patterns are proven Prefect workflow architectures adapted for financial agents on Purple Flea. Each can be deployed to Prefect Cloud with a schedule and monitored via the Prefect UI.
A flow runs daily at a fixed time, fetches the current BTC or ETH price, and buys a fixed dollar amount regardless of price. Three tasks: check_balance, get_price, execute_buy. If the balance is insufficient the flow skips with a warning state rather than failing.
Fetch all positions, compute current allocation percentages, compare to target allocation (e.g. 60% BTC / 40% ETH), and execute the minimum number of trades to restore balance. Runs weekly with Slack notification on completion via Prefect automations.
Runs every 5 minutes. Fetches all open positions and checks if any exceed the maximum drawdown threshold. If a position is down more than 10%, it fires a close-position task and sends an alert. Zero human intervention required — the Prefect retry policy handles transient API errors.
Uses Prefect's task.submit() to fetch price and momentum data for 20 markets in parallel. Runs every 15 minutes. Markets showing momentum above the signal threshold get a trade task submitted — all in a single flow run with a single Prefect Cloud log.
Prefect Cloud is the managed control plane for your flows. Every run of your trading agent is recorded, logged, and visible in the Prefect UI at app.prefect.cloud. The free tier supports unlimited flow runs.
Every execution of your trading flow is logged with start time, duration, task states, parameters, and outputs. Replay any run to see exactly what data drove a trading decision.
Configure automations to send email, Slack, or PagerDuty alerts when a flow enters a Failed or Crashed state. Know immediately when your trading scheduler misses a run.
Pause, modify, or cancel schedules from the Prefect Cloud UI without redeploying code. Change your trading interval from hourly to every 15 minutes with a single click.
pip install prefect then prefect cloud login to connect your local environment to Prefect Cloud. Free tier available at prefect.io.
Copy the momentum flow example above. Replace the API key with your Purple Flea key from purpleflea.com/register. Add or remove tasks for the markets and strategies you want to run.
Run python btc_momentum_flow.py to create the deployment. Prefect Cloud registers the schedule and begins triggering runs automatically.
Open app.prefect.cloud to see your flow runs in real time. Configure Slack alerts for failures. View P&L artifacts logged by your tasks.
Prefect handles the orchestration, retries, and scheduling. Purple Flea handles the financial primitives. Register your agent and deploy your first trading flow in under 10 minutes.