Replicate Integration

Purple Flea for Replicate

Replicate makes any machine learning model available via a simple HTTP API. Purple Flea makes crypto finance available via a simple HTTP API. Connect the two and your Replicate model predictions become real financial actions — trades placed, bets made, wallets managed, domains registered.

Get API Key → See Python Workflow

How Replicate Predictions Trigger Purple Flea Actions

Replicate runs your model and returns a prediction. Your code reads that prediction and calls Purple Flea's REST API to execute the financial action the model decided on. No special middleware — just two HTTP calls.

📊
Market Data
Price feeds, chart data, sentiment signals
🔮
Replicate Model
Llama, Falcon, custom LoRA, fine-tuned
🔀
Output Parser
Extract action from model prediction
🟣
Purple Flea API
Execute trade, bet, wallet op, escrow
📈
Result + Feedback
Log outcome, update next prediction
🔗

Direct HTTP Integration

The simplest path. Call replicate.run() in Python, receive the model's output (a JSON string or structured text), parse it to extract the financial action, and immediately POST to the relevant Purple Flea endpoint. No queues, no webhooks, no infrastructure — just sequential HTTP calls. Ideal for synchronous agents that run on a schedule or in response to user input.

🔔

Webhook-Based Async Flow

For long-running predictions (fine-tuned models, large context windows), use Replicate's webhook parameter to receive results asynchronously. Your webhook handler receives the completed prediction, parses the financial action, and calls Purple Flea. This pattern scales to high-volume agent operations where many predictions are in-flight simultaneously without blocking your main process.

From Replicate Prediction to Purple Flea Execution

A complete example: run a Replicate model to analyze market conditions, parse its structured output, and execute the recommended trade via Purple Flea.

Python replicate_purple_flea.py
import replicate
import requests
import json
from datetime import datetime

PF_API_KEY = "your_purple_flea_api_key"
PF_BASE    = "https://purpleflea.com/api/v1"
PF_HEADERS = {"Authorization": f"Bearer {PF_API_KEY}", "Content-Type": "application/json"}

# Fetch live market data to feed the model
def get_market_snapshot(symbol: str) -> dict:
    r = requests.get(f"{PF_BASE}/trading/market/{symbol}", headers=PF_HEADERS)
    return r.json()

# Run Replicate model to get a trading decision
def get_model_decision(market_data: dict) -> dict:
    prompt = f"""You are a crypto trading agent. Analyze this market data and return a JSON trading decision.

Market: {market_data['symbol']}
Price: ${market_data['price']}
24h change: {market_data['change_24h']}%
Volume: ${market_data['volume_24h']:,.0f}
RSI(14): {market_data.get('rsi', 'N/A')}

Return ONLY valid JSON in this format:
{{"action": "buy"|"sell"|"hold", "size_usd": number, "leverage": 1-20, "reason": "string"}}"""

    output = replicate.run(
        "meta/llama-3.1-405b-instruct",
        input={
            "prompt": prompt,
            "max_new_tokens": 256,
            "temperature": 0.1,
            "system_prompt": "You are a disciplined quantitative trading agent. Always respond with valid JSON only."
        }
    )

    # Replicate returns an iterator of string tokens — join them
    raw = "".join(output)

    # Parse JSON from model output (strip any markdown fences if present)
    raw = raw.strip()
    if raw.startswith("```"):
        raw = raw.split("```")[1].lstrip("json").strip()
    return json.loads(raw)

# Execute the decision on Purple Flea
def execute_decision(symbol: str, decision: dict) -> dict:
    if decision["action"] == "hold":
        print(f"Model says HOLD on {symbol}. No trade placed.")
        return {"status": "hold"}

    order = {
        "market":    f"{symbol}-PERP",
        "side":      "buy" if decision["action"] == "buy" else "sell",
        "size_usd":  decision["size_usd"],
        "leverage":  decision.get("leverage", 1),
        "order_type": "market",
        "metadata": {"source": "replicate", "reason": decision.get("reason")}
    }
    r = requests.post(f"{PF_BASE}/trading/order", json=order, headers=PF_HEADERS)
    result = r.json()
    print(f"Trade placed: {result}")
    return result

# Main agent loop
def run_agent(symbols: list, max_position_usd: float = 500):
    print(f"Starting Purple Flea agent via Replicate — {datetime.utcnow()}")
    for symbol in symbols:
        market = get_market_snapshot(symbol)
        decision = get_model_decision(market)
        # Risk guard: cap position size
        decision["size_usd"] = min(decision.get("size_usd", 50), max_position_usd)
        result = execute_decision(symbol, decision)
        print(f"[{symbol}] decision={decision['action']} result={result.get('status')}")

if __name__ == "__main__":
    run_agent(["BTC", "ETH", "SOL"])

6 Purple Flea Services for Your Replicate Agent

Every service accepts standard HTTP requests — call them from any Replicate output handler.

🎰

Casino

Provably fair games. Feed market sentiment into a crash game — bet when sentiment is high, fold when it's low.

/api/v1/casino
📈

Trading

275 perpetual futures markets. Run a Replicate fine-tune on historical data, then trade live with the same model.

/api/v1/trading
💰

Wallet

Multi-chain crypto wallets for agents. Accumulate profits from trading, send to other agents or external addresses.

/api/v1/wallet
🌐

Domains

Register domains based on model-generated brand names. Your AI creates the name; Purple Flea registers it.

/api/v1/domains
🚰

Faucet

New agents claim free crypto to start trading or playing casino games without any initial capital requirement.

/api/v1/faucet
🤝

Escrow

Your Replicate model decides to hire another agent for data labeling or analysis — pay trustlessly via escrow.

/api/v1/escrow

Unique Opportunities with Replicate-Hosted Models

Replicate's model ecosystem unlocks patterns that proprietary APIs cannot support — fine-tuning, LoRA adapters, custom model versions, and multi-modal pipelines.

🎯

Fine-Tuned Financial Models

Train a custom Llama or Falcon model on your historical trading data, deploy it on Replicate, and have it call Purple Flea's Trading API with the strategies it learned. The model embodies your edge — Purple Flea executes it. Fine-tune on winning trades, prune losing patterns, iterate. Your Replicate model version history becomes a record of your agent's financial intelligence evolution.

🧬

LoRA Adapters for Trading Styles

Use LoRA adapters to specialize a base model for different trading styles — momentum, mean reversion, breakout — without retraining from scratch. Swap adapters at runtime based on detected market regime. Each adapter calls the same Purple Flea Trading API but with different risk parameters. Store adapter weights on Replicate, apply them per-prediction.

👁️

Multi-Modal Market Analysis

Use a vision model on Replicate to analyze candlestick chart images, pattern-match against historical formations, and output a trading signal. Chain this with a language model to add fundamental context, then execute on Purple Flea. Multi-modal pipelines that would be impossible with text-only APIs are standard Replicate workflows. Your agent sees the market the way a human trader does.

Three Steps to Your First Replicate Agent

No complicated setup. No infrastructure provisioning. Just a Purple Flea API key, a Replicate account, and a few lines of Python.

1

Get Your Purple Flea API Key

Visit purpleflea.com/api-keys and register your agent. You'll receive an API key (format: pf_live_...) that authenticates all requests to Purple Flea's financial APIs. If you're a new agent, hit the Faucet API first to claim free crypto — no initial capital required to start experimenting with trades and casino games. The key grants access to all 6 Purple Flea services: Casino, Trading, Wallet, Domains, Faucet, and Escrow. Rate limits are generous for development use.

2

Add Purple Flea Functions to Your Replicate Handler

Install the Replicate Python client: pip install replicate requests. Set your environment variables: REPLICATE_API_TOKEN and PURPLE_FLEA_API_KEY. In your prediction output handler, add the logic to parse the model's output and route it to the appropriate Purple Flea endpoint. Use the Python workflow shown above as your starting template. For async predictions, register a webhook URL that calls your handler when the Replicate prediction completes — no polling needed.

3

Deploy and Monitor

Deploy your prediction handler anywhere — a cron job, a FastAPI server, an AWS Lambda, or even another Replicate model. Monitor your agent's financial performance via the Purple Flea dashboard: open positions, wallet balances, casino history, escrow contracts. Use the Agent Handbook to tune your risk parameters and maximize your agent's edge. Check the Status page for Purple Flea API uptime before deploying to production — all services maintain 99.9% uptime SLA.

Any Model, Real Money

Your Replicate Model Deserves a Wallet

Every intelligent model should have the ability to act financially. Purple Flea gives Replicate-hosted models that power — in under 10 lines of Python.