xAI Grok + Purple Flea

Grok-powered agents with real-time data and financial execution

xAI's Grok models have live access to X (Twitter) — the world's fastest-moving financial signal. Pair that with Purple Flea's execution APIs and your agent has a genuine edge in crypto markets.

Get Free API Key Read the Docs
Real-time
X/Twitter Data
275
Perp Markets
6
Financial APIs
$1
Free Faucet

Why Grok is different for financial agents

Most LLMs have a knowledge cutoff. Grok doesn't. Its native integration with X (Twitter) gives it continuous access to the fastest-moving financial signals available anywhere — whale alerts, developer announcements, regulatory leaks, and market-moving rumors.

Data source GPT-4o Claude Perplexity Grok
X/Twitter real-time feed Web scrape Native API
Breaking crypto news Search Native + Search
Chain-of-thought reasoning Yes Yes (extended) Limited Yes (Grok 3)
Knowledge cutoff Periodic Periodic Real-time Real-time
Humor / unconventional takes Unique
Workflow: Grok social sentiment trader
1

Monitor crypto Twitter via Grok grok-3

Grok continuously monitors X for posts from key crypto accounts: whales, developers, VCs, and major exchanges. It detects emerging narratives 10–60 minutes before they hit mainstream news.

2

Identify trending signals reasoning

Grok's chain-of-thought reasoning evaluates signal quality: Is this original information or amplification? Who posted it — insider or retail? Does it contradict or confirm on-chain data?

3

Cross-reference on-chain data verification

Purple Flea's wallet APIs can pull on-chain balances and movements to verify Twitter signals. Whale wallet moving large BTC while tweet claims "accumulation"? High-conviction signal.

4

Execute perp trade on Purple Flea execution

High-conviction signals trigger perpetual positions across 275 markets. Grok can go long on the trending asset or short a competitor. All executed via Purple Flea's Hyperliquid-backed API.

Grok + Purple Flea in Python

A working Grok-based agent that monitors X sentiment and executes trades via Purple Flea. Uses xAI's OpenAI-compatible API endpoint.

grok_sentiment_trader.py Python
from openai import OpenAI
import requests
import json

# xAI uses OpenAI-compatible API — just swap the base_url
XAI_API_KEY = "xai-your-key-here"
PF_API_KEY  = "pf_live_your_key_here"

client = OpenAI(
    base_url = "https://api.x.ai/v1",
    api_key  = XAI_API_KEY
)

class GrokSentimentTrader:

    def analyze_x_sentiment(self, asset: str) -> dict:
        """Use Grok's live X access to analyze crypto sentiment."""
        response = client.chat.completions.create(
            model = "grok-3",
            messages = [
                {
                    "role": "system",
                    "content": (
                        "You are a crypto trading agent with live access to X. "
                        "Analyze recent posts about the given asset from the last 2 hours. "
                        "Look for: whale movements, developer announcements, exchange news, "
                        "notable influencer posts, and on-chain event references. "
                        "Respond only with valid JSON: {sentiment, confidence, direction, "
                        "signal_quality, key_accounts, reasoning}"
                    )
                },
                {
                    "role": "user",
                    "content": f"Analyze X sentiment for {asset} — last 2 hours."
                }
            ],
            temperature = 0.1
        )
        content = response.choices[0].message.content
        try:
            return json.loads(content)
        except:
            return {"sentiment": "neutral", "confidence": 0, "direction": "hold"}

    def verify_with_onchain(self, asset: str, signal: dict) -> bool:
        """Cross-reference signal against on-chain wallet data."""
        # In production: call Purple Flea wallet API to check
        # large address movements for the asset
        if signal["signal_quality"] == "high" and signal["confidence"] > 70:
            return True
        return signal["confidence"] > 85

    def execute_trade(self, market: str, direction: str,
                        size_usd: float) -> dict:
        """Open perpetual position on Purple Flea (275 markets)."""
        resp = requests.post(
            "https://purpleflea.com/api/v1/trading/perp/open",
            headers = {"X-API-Key": PF_API_KEY},
            json = {
                "market":    market,
                "side":      direction,
                "size_usd":  size_usd,
                "leverage":  3,
                "order_type": "market"
            }
        )
        return resp.json()

    def run_cycle(self, assets: list):
        """Run one full sentiment scan + execution cycle."""
        for asset in assets:
            print(f"[+] Grok analyzing X sentiment for {asset}...")
            signal = self.analyze_x_sentiment(asset)

            confirmed = self.verify_with_onchain(asset, signal)
            if not confirmed:
                print(f"    {asset}: signal not confirmed — skip")
                continue

            size = 50.0 if signal["confidence"] < 80 else 100.0
            result = self.execute_trade(
                market    = f"{asset}-PERP",
                direction = signal["direction"],
                size_usd  = size
            )
            print(f"    Trade: {result['status']} @ {result.get('entry_price','?')}")


if __name__ == "__main__":
    trader = GrokSentimentTrader()
    trader.run_cycle(["BTC", "ETH", "SOL", "DOGE"])

System prompt for a Grok financial agent

Drop this into your Grok agent configuration. It primes Grok to use its X access advantage for financial decision-making.

System Prompt — Grok Financial Agent

You are a financial AI agent with native access to X (Twitter) real-time data and Purple Flea's financial execution APIs. Your unique advantage: You can read live X posts, identify breaking news before it hits mainstream media, and act on it within seconds via Purple Flea. Your capabilities: - Monitor X for whale alerts, project announcements, regulatory news, and sentiment shifts - Execute perpetual trades across 275 markets (BTC, ETH, SOL, and 272 altcoins) - Manage multi-chain wallets: ETH, BTC, SOL, TRX, XMR, XRP - Transfer funds trustlessly via escrow (1% fee, atomic settlement) Signal quality framework: - HIGH: Announcement from verified project account + on-chain confirmation - MEDIUM: Multiple credible accounts posting same info independently - LOW: Single source, unverified, or contradicted by on-chain data Position sizing: - HIGH signal: up to 20% of portfolio, 3x leverage - MEDIUM signal: up to 10%, 2x leverage - LOW signal: no trade Always reason through the signal chain before executing. Show your work.

6 financial APIs powering your Grok agent

Grok identifies the signals. Purple Flea executes the trades. Here is everything your agent needs.

🎰
Casino
Provably fair games — crash, coin-flip, dice. USDC bets with instant, on-chain-verifiable outcomes. Grok can run statistical betting strategies autonomously.
POST /casino/bet
📈
Perpetual Trading
275 markets via Hyperliquid. Long and short positions, up to 20x leverage. Market and limit orders. Grok's real-time X data feeds directly into trade decisions.
POST /trading/perp/open
👛
Multi-chain Wallets
Full wallet management across ETH, BTC, SOL, TRX, XMR, XRP. Check balances, verify whale movements on-chain, and cross-reference with X signals.
GET /wallet/balance
🌐
Domain Registration
Register .com, .ai, .io domains for agents and projects. Agents can claim identities matching trending X handles before they go viral.
POST /domains/register
💧
Faucet
New agents get $1 USDC free to start. Zero-risk onboarding — claim the faucet, try the casino, open a small perp position, all without depositing first.
POST /faucet/claim
🔒
Escrow
Trustless agent-to-agent payments. 1% protocol fee, 15% referral commission. Lock funds, confirm delivery, release atomically — zero trust required.
POST /escrow/create

Other inference providers

Purple Flea integrates with every major AI provider and framework.