Anyscale Integration

Purple Flea for Anyscale

Anyscale is the platform for building and scaling AI workloads with Ray. Combined with Purple Flea's financial infrastructure, you can run thousands of trading agents in parallel, backtest strategies across years of data simultaneously, and scale from 1 to 1000 agents with a single command.

Get Your API Key → View API Docs

Why Ray + Purple Flea

Sequential trading agents are bottlenecked by network I/O and API rate limits per symbol. With Ray actors, you break out of that constraint — each actor manages a different market or strategy, all running simultaneously across a cluster. Purple Flea's per-agent API key model maps cleanly to this: each Ray actor is an independent agent with its own registered identity and wallet.

275
Perpetual markets to cover
100x
Throughput vs sequential
1→1K
Agent scaling range
0
Code changes to scale

Parallel Agents: 100 Strategies at Once

Each Ray actor is an independent trading agent covering a different market symbol, strategy, or time horizon. Run 100 momentum strategies simultaneously across BTC, ETH, SOL, AVAX, and 96 other perpetual markets — all firing signals and executing trades in parallel with zero interference between actors.

📊

Distributed Backtesting Across Years of Data

Partition historical market data across a Ray cluster and run strategy validation in parallel. What takes 8 hours sequentially — backtesting 50 parameter combinations across 3 years of minute-level data — completes in minutes with Ray's distributed task scheduler. Then promote winners to live Purple Flea execution.

📈

Auto-Scale on Volatility Spikes

Anyscale can grow or shrink your Ray cluster based on workload. During high-volatility market events — liquidation cascades, major macro releases, exchange outages — spawn additional agent actors to capture the signal. During calm periods, scale to minimum to minimize cloud costs.

Ray Actor Pattern for Purple Flea

The Ray actor model maps cleanly to autonomous trading agents. Each actor maintains its own state (symbol, strategy parameters, position tracking), makes independent API calls to Purple Flea, and runs truly concurrently — not just asynchronously — across CPU cores or cluster nodes.

Python — parallel_agents.py
import ray
import requests
import os
import time
from typing import Optional

API_KEY = os.environ.get("PURPLE_FLEA_API_KEY", "")
PF_BASE = "https://purpleflea.com/api/v1"

@ray.remote
class TradingAgent:
    def __init__(self, agent_id: str, api_key: str, symbol: str, strategy: str = "momentum"):
        self.agent_id = agent_id
        self.api_key  = api_key
        self.symbol   = symbol
        self.strategy = strategy
        self.headers  = {"Authorization": f"Bearer {api_key}"}
        self.position = None
        self.pnl      = 0.0

    def get_price(self) -> Optional[dict]:
        try:
            resp = requests.get(
                f"{PF_BASE}/markets/{self.symbol}/price",
                headers=self.headers,
                timeout=5
            )
            return resp.json()
        except Exception:
            return None

    def check_and_trade(self) -> dict:
        # Get current market price and momentum
        price_data = self.get_price()
        if not price_data:
            return {"agent": self.agent_id, "error": "price fetch failed"}

        change_1h  = price_data.get("change_1h_pct", 0)
        change_24h = price_data.get("change_24h_pct", 0)
        price      = price_data.get("price", 0)

        action = "hold"
        trade  = None

        if self.strategy == "momentum":
            # Simple momentum: buy if price up 2%+ in last hour
            if change_1h > 2.0 and not self.position:
                trade = requests.post(
                    f"{PF_BASE}/trade",
                    json={"symbol": self.symbol, "side": "long", "size_usd": 50},
                    headers=self.headers, timeout=8
                ).json()
                self.position = trade.get("position_id")
                action = "buy"

            # Exit if reversal signal
            elif change_1h < -1.5 and self.position:
                trade = requests.delete(
                    f"{PF_BASE}/trade/{self.position}",
                    headers=self.headers, timeout=8
                ).json()
                self.pnl += trade.get("realized_pnl", 0)
                self.position = None
                action = "close"

        return {
            "agent":    self.agent_id,
            "symbol":   self.symbol,
            "price":    price,
            "change_1h": change_1h,
            "action":   action,
            "trade":    trade,
            "total_pnl": self.pnl,
        }

    def get_state(self) -> dict:
        return {
            "agent_id": self.agent_id,
            "symbol":   self.symbol,
            "position": self.position,
            "pnl":      self.pnl,
        }


# --- Launch 10 agents in parallel across different symbols ---

ray.init()  # or ray.init(address="auto") for Anyscale cluster

symbols = [
    "BTC-PERP", "ETH-PERP", "SOL-PERP", "AVAX-PERP", "ARB-PERP",
    "OP-PERP",  "MATIC-PERP", "DOGE-PERP", "APT-PERP", "SUI-PERP"
]

# Create agents — each is a persistent Ray actor with its own state
agents = [
    TradingAgent.remote(
        agent_id=f"agent-{i:03d}",
        api_key=API_KEY,
        symbol=sym,
        strategy="momentum"
    )
    for i, sym in enumerate(symbols)
]

# Run all agents simultaneously — true parallel execution
while True:
    # Fire all 10 agents at once, collect results concurrently
    futures = [agent.check_and_trade.remote() for agent in agents]
    results = ray.get(futures)

    # Aggregate results
    total_pnl = sum(r.get("total_pnl", 0) for r in results)
    active    = [r for r in results if r.get("action") != "hold"]

    print(f"Cycle complete | Active signals: {len(active)} | Total P&L: ${total_pnl:.2f}")
    for r in active:
        print(f"  {r['symbol']}: {r['action']} @ ${r['price']:,.2f} (1h: {r['change_1h']:+.1f}%)")

    time.sleep(60)  # poll every minute

Available Financial APIs

Every Purple Flea service is a REST endpoint callable from any Ray actor. Scale your agent fleet across all six services simultaneously.

🎲
Casino
2% house edge

Provably fair games. Run 100 parallel betting strategy agents each using a different bankroll management approach. Ray aggregates their outcomes for strategy selection.

📈
Trading
0.05% per trade

275 perpetual markets. One Ray actor per symbol — that is 275 simultaneous market monitors, each with their own Purple Flea agent identity and position tracking.

💰
Wallet
0.3% swap fee

Multi-chain wallets. Parallel actors can each hold different chains — one actor per chain — for simultaneous cross-chain rebalancing that completes in seconds rather than sequentially.

🌐
Domains
Market rate

Blockchain domains. Each Ray actor in your fleet registers its own on-chain identity. Domain actors can batch-register identities for an entire agent fleet in seconds.

💧
Faucet
FREE

New agent onboarding. A single Ray task can register and fund an entire fleet of new agents from the faucet before distributing them across the cluster as actors.

🔒
Escrow
1% + 15% referral

Trustless agent payments. Coordinate multi-actor escrow networks where agents hire each other for computation tasks and pay via Purple Flea's escrow system.

Scaling Patterns

Ray's actor model supports several architectural patterns that map well to financial agent systems. Pick the pattern that fits your strategy.

📊

Portfolio of Markets

One actor per symbol. A coordinator actor polls all symbols' actors for signals, aggregates position risk across the portfolio, and enforces overall exposure limits. Each symbol actor is fully independent and restartable.

🧪

A/B Strategy Testing

Multiple strategy actors on the same symbol simultaneously. Actor A runs momentum, Actor B runs mean-reversion, Actor C runs ML inference. Compare live P&L across strategies with the same market conditions, then promote the winner to larger size.

🔗

Multi-Agent Escrow Network

A coordinator actor decomposes complex tasks and hires worker agents via Purple Flea escrow. Workers complete subtasks (data fetching, model inference, trade execution), get paid via escrow release, and report results back to the coordinator actor.

🎮

Distributed Casino Fleet

Run parallel betting agents each using a different strategy: Martingale, Kelly Criterion, fixed fractional, d'Alembert. Track outcomes with Ray's distributed object store and converge on the best performing bankroll management approach.

What Anyscale Adds

Anyscale extends Ray with managed infrastructure, making it production-ready for financial agent workloads that run 24/7 across market hours.

☁️

Managed Ray Clusters

Anyscale provisions, monitors, and auto-repairs Ray clusters on AWS, GCP, or Azure. No head node management, no worker restart scripts — just define your cluster configuration and Anyscale keeps it healthy. Critical for trading systems that cannot tolerate downtime.

📅

Job Scheduling

Schedule backtesting jobs to run overnight, strategy selection jobs to run at market open, and position monitoring jobs to run throughout market hours — all with Anyscale's job scheduler and retry policies. Results pipe directly into your live agent fleet.

💻

Workspaces

Anyscale Workspaces give you a persistent development environment connected to a Ray cluster. Develop, test, and iterate on your Purple Flea agent code interactively — then promote to a production job with one command, no environment changes needed.

YAML — anyscale cluster config for Purple Flea agents
# anyscale-cluster.yaml
name: purple-flea-agent-cluster
compute_config:
  cloud: aws
  head_node_type:
    instance_type: m5.xlarge
  worker_node_types:
    - instance_type: m5.2xlarge
      min_workers: 2
      max_workers: 20   # auto-scale up to 20 workers on volatility

env_vars:
  PURPLE_FLEA_API_KEY: "{{ secrets.pf_api_key }}"

runtime_env:
  pip:
    - requests
    - pandas
    - numpy

Performance at Scale

The numbers below illustrate what becomes possible when you combine Ray's parallel execution with Purple Flea's financial API coverage.

100x
Throughput vs. sequential agents

A sequential agent checking 100 symbols with 200ms API latency each takes 20 seconds per cycle. 100 parallel Ray actors complete the same sweep in 200ms — the time of a single request. Same Purple Flea API, 100x the coverage.

275
Markets scanned simultaneously

Purple Flea's trading API covers all 275 perpetual markets on Hyperliquid. With Ray, you can run one actor per market — monitoring every single perpetual simultaneously in real time. No market moves without your agents noticing.

Related Integrations

From 1 Agent to 1000
Same Code, Same API

Register in 60 seconds. Get your API key. Wrap your first Purple Flea call in a Ray actor and watch it scale from 1 to 1000 agents without changing a line of trading logic.