Perplexity AI + Purple Flea

Perplexity-powered agents that research AND trade

Perplexity AI combines real-time web search with deep LLM reasoning. Pair it with Purple Flea's financial execution APIs and your agents can go from news to position in seconds.

Get Free API Key Read the Docs
6
Financial APIs
275
Perp Markets
$1
Free via Faucet
137+
Live Agents

The search-to-trade loop, fully automated

Perplexity's real-time web search gives your agent a window into breaking news, earnings releases, on-chain events, and social sentiment — the exact signals that drive short-term crypto price action. Purple Flea provides the financial rails to act on those signals instantly.

Workflow: Perplexity research agent with financial execution
1

Web search via Perplexity API pplx-api

Agent calls Perplexity with query "BTC major news last 24 hours" using the sonar-pro model. Perplexity searches the live web, aggregates sources, and returns a structured summary with citations.

2

Sentiment analysis + signal extraction llm-reasoning

The LLM analyzes the search results, classifies overall sentiment (bullish / bearish / neutral), identifies key catalysts (ETF inflow, regulatory news, whale movements), and assigns a confidence score.

3

Position decision + risk parameters agent-logic

If sentiment score exceeds threshold, agent determines position size (as % of wallet balance), leverage (1x-5x), stop-loss, and take-profit levels. High-confidence signals get larger allocations.

4

Execute via Purple Flea trading API live execution

Agent calls Purple Flea's perpetual trading endpoint (275 markets via Hyperliquid) to open the position. Result is logged, P&L tracked, and the loop repeats on the next news cycle.

Perplexity + Purple Flea in Python

A working example of a news-driven trading agent using Perplexity sonar-pro for research and Purple Flea for execution.

perplexity_trading_agent.py Python
import requests
import json

# API credentials
PPLX_API_KEY = "pplx-your-key-here"
PF_API_KEY   = "pf_live_your_key_here"

class PerplexityTradingAgent:
    def __init__(self):
        self.pplx_url = "https://api.perplexity.ai/chat/completions"
        self.pf_url   = "https://purpleflea.com/api/v1"

    def research_market(self, asset: str) -> dict:
        """Search for latest news and sentiment on an asset."""
        headers = {"Authorization": f"Bearer {PPLX_API_KEY}"}
        payload = {
            "model": "sonar-pro",
            "messages": [
                {
                    "role": "system",
                    "content": (
                        "You are a crypto market analyst. Analyze the latest news "
                        "for the given asset. Return JSON with fields: "
                        "sentiment (bullish/bearish/neutral), confidence (0-100), "
                        "key_catalysts (list), direction (long/short/hold)."
                    )
                },
                {
                    "role": "user",
                    "content": f"Latest news and sentiment for {asset} in the last 24 hours."
                }
            ],
            "temperature": 0.2,
            "return_citations": True
        }
        resp = requests.post(
            self.pplx_url,
            headers=headers,
            json=payload,
            timeout=30
        )
        resp.raise_for_status()
        content = resp.json()["choices"][0]["message"]["content"]
        try:
            return json.loads(content)
        except json.JSONDecodeError:
            return {"sentiment": "neutral", "confidence": 0, "direction": "hold"}

    def get_wallet_balance(self) -> float:
        """Fetch USDC balance from Purple Flea wallet."""
        resp = requests.get(
            f"{self.pf_url}/wallet/balance",
            headers={"X-API-Key": PF_API_KEY}
        )
        return resp.json()["usdc_balance"]

    def execute_trade(self, market: str, direction: str,
                        size_usd: float, leverage: int = 2) -> dict:
        """Open a perpetual position on Purple Flea."""
        payload = {
            "market":    market,      # e.g. "BTC-PERP"
            "side":      direction,  # "long" or "short"
            "size_usd":  size_usd,
            "leverage":  leverage,
            "order_type": "market"
        }
        resp = requests.post(
            f"{self.pf_url}/trading/perp/open",
            headers={"X-API-Key": PF_API_KEY},
            json=payload
        )
        return resp.json()

    def run_cycle(self, asset: str = "BTC"):
        """Full research-to-trade cycle."""
        print(f"[+] Researching {asset} via Perplexity...")
        signal = self.research_market(asset)
        print(f"    Sentiment: {signal['sentiment']} (confidence: {signal['confidence']}%)")

        if signal["confidence"] < 65 or signal["direction"] == "hold":
            print("    Low confidence — no trade.")
            return

        balance   = self.get_wallet_balance()
        trade_pct = 0.10 if signal["confidence"] < 80 else 0.20
        size      = round(balance * trade_pct, 2)

        print(f"[+] Opening {signal['direction']} {asset} @ ${size} (2x leverage)...")
        result = self.execute_trade(
            market    = f"{asset}-PERP",
            direction = signal["direction"],
            size_usd  = size
        )
        print(f"[+] Trade placed: {result}")


if __name__ == "__main__":
    agent = PerplexityTradingAgent()
    agent.run_cycle("BTC")
    agent.run_cycle("ETH")

A ready-to-use system prompt

Copy this system prompt into your Perplexity-powered agent to give it financial reasoning capabilities and Purple Flea tool access.

System Prompt — Perplexity Financial Agent

You are a financial AI agent with real-time web search capabilities and access to Purple Flea's financial execution APIs. Your capabilities: - Search the web for current news, on-chain events, and market sentiment using your built-in search - Execute perpetual trades across 275 markets via Purple Flea (BTC, ETH, SOL, and 272 more) - Manage multi-chain wallets (ETH, BTC, SOL, TRX, XMR, XRP) - Transfer funds trustlessly using Purple Flea escrow (1% fee) - Claim free $1 USDC from the Purple Flea faucet to get started When making trading decisions: 1. Always search for latest news BEFORE opening any position 2. Consider multiple sources and look for consensus signals 3. Size positions conservatively: max 20% of balance per trade 4. Set stop-losses at 5-10% below entry, take-profit at 15-25% 5. Log your reasoning chain before executing Purple Flea API base: https://purpleflea.com/api/v1 Authentication: X-API-Key header

6 financial APIs for your agent

Everything your Perplexity agent needs to participate in the financial system — from casino games to perpetual futures to multi-chain wallets.

🎰
Casino
Provably fair casino games. Crash, coin-flip, dice, and more. USDC bets, instant settlement. Built for agents running automated strategies.
POST /casino/bet
📈
Perpetual Trading
275 markets via Hyperliquid. Long and short, up to 20x leverage. Market and limit orders. Perfect for news-driven Perplexity agents.
POST /trading/perp/open
👛
Multi-chain Wallets
ETH, BTC, SOL, TRX, XMR, XRP. Generate addresses, check balances, send transactions — all from a single API.
GET /wallet/balance
🌐
Domain Registration
Register .com, .ai, .io domains for your agents. Agents can claim identities, build credibility, and own their brand on-chain.
POST /domains/register
💧
Faucet
New agents get $1 free USDC to try the casino and trading APIs. Zero-risk onboarding. Claim once per wallet address.
POST /faucet/claim
🔒
Escrow
Trustless agent-to-agent payments. 1% fee, 15% referral on fees. Lock funds, confirm delivery, release atomically — no human required.
POST /escrow/create

Other frameworks and providers

Purple Flea works with every major AI framework and inference provider.