Moralis + Purple Flea

Combine Moralis Data with
Purple Flea Financial Execution

Moralis gives your agent a complete view of the blockchain — token prices, NFT metadata, wallet transaction histories, and DeFi protocol data. Purple Flea gives it the ability to act on that data: trade perpetuals, custody assets, settle peer-to-peer, and play casino games. Together they form a full-stack autonomous finance agent.

Start Trading Try Agent Escrow
275+
Trading Markets
1%
Escrow Fee
<50ms
Order Latency
$1
Free Faucet for New Agents
20%
Referral Revenue Share
Architecture

Data Layer + Execution Layer

Moralis is a read-optimized Web3 data platform — it abstracts RPC complexity and delivers clean, structured APIs for token prices, NFT collections, wallet histories, and DeFi protocol data. Purple Flea is a write-optimized financial execution platform for AI agents. Combining them gives you the complete read-execute loop for any autonomous finance strategy.

Moralis (Data Layer)

  • Token prices — real-time + historical
  • NFT metadata, floor prices, rarity scores
  • Wallet transaction history (all chains)
  • DeFi protocol data (Uniswap, Aave, Curve)
  • Token holders and whale tracking
  • Streams — real-time on-chain webhooks
  • Multi-chain: EVM, Solana, Aptos
signal
triggers
action

Purple Flea (Execution Layer)

  • Trading — 275+ perpetual markets
  • Wallet — EVM, Solana, BTC, XMR custody
  • Escrow — trustless agent-to-agent settlement
  • Casino — provably fair agent games
  • Faucet — $1 USDC free bootstrap capital
  • Domains — on-chain .agent identity handles
Use Case Deep Dive

Moralis Wallet History → Purple Flea Credit Scoring

Agents that transact with each other via Purple Flea Escrow need to trust each other. Moralis wallet history provides an objective on-chain credit signal: transaction frequency, average balances, DeFi participation, NFT activity. Use these signals to decide escrow terms.

📄
Fetch Agent Wallet History

Call Moralis GET /wallets/{address}/history to retrieve all transactions for the counterparty agent's wallet address.

Moralis
📈
Calculate Credit Score Features

Compute: wallet age (days), total TX count, average monthly volume, DeFi protocol count, NFT trades, and largest single transaction.

Moralis
Score and Decide Escrow Terms

Map the credit features to a 0–100 score. If score > 70, offer standard 1% escrow. If score 40–70, require a 10% hold deposit. Below 40, decline.

Purple Flea
💰
Create Escrow Contract

POST to Purple Flea Escrow with the agreed amount, buyer and seller agent IDs, and escrow conditions. Funds are held trustlessly until release or dispute.

Purple Flea

Moralis Price API → Purple Flea Trade

A simple momentum strategy: fetch the current price of a token via Moralis, compare to a moving average stored in memory, and fire a Purple Flea trade if the signal crosses a threshold.

moralis_price_trader.py Python
# Moralis Token Price API → Purple Flea Trade Execution
# pip install requests

import os, time, statistics, requests
from collections import deque

MORALIS_KEY = os.environ["MORALIS_API_KEY"]
PF_API_KEY  = os.environ["PURPLE_FLEA_API_KEY"]
PF_TRADE_EP = "https://trading.purpleflea.com/api/v1/orders"

# Token: Ethereum mainnet USDC/ETH price
TOKEN_ADDR  = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"  # WETH
CHAIN       = "eth"
MARKET      = "ETH-PERP"
SIZE_USD    = 250.0
MA_WINDOW   = 20   # 20-sample moving average
POLL_SECS   = 60   # poll price every 60s

price_history = deque(maxlen=MA_WINDOW)
position      = 0   # +1 long, -1 short, 0 flat

def get_moralis_price(address: str, chain: str) -> float:
    """Fetch current USD price from Moralis Token Price API."""
    url = f"https://deep-index.moralis.io/api/v2.2/erc20/{address}/price"
    r = requests.get(
        url,
        headers={"X-API-Key": MORALIS_KEY},
        params={"chain": chain, "include": "percent_change"},
        timeout=5,
    )
    r.raise_for_status()
    return float(r.json()["usdPrice"])

def place_order(side: str) -> dict:
    """Submit a market order to Purple Flea Trading."""
    r = requests.post(
        PF_TRADE_EP,
        headers={"X-API-Key": PF_API_KEY, "Content-Type": "application/json"},
        json={"market": MARKET, "side": side, "type": "market", "size_usd": SIZE_USD},
        timeout=4,
    )
    r.raise_for_status()
    return r.json()

def run_loop():
    global position
    print("Starting Moralis → Purple Flea momentum agent...")

    while True:
        try:
            price = get_moralis_price(TOKEN_ADDR, CHAIN)
            price_history.append(price)
            print(f"[{time.strftime('%H:%M:%S')}] ETH: ${price:,.2f} | history: {len(price_history)}/{MA_WINDOW}")

            if len(price_history) < MA_WINDOW:
                time.sleep(POLL_SECS)
                continue

            ma = statistics.mean(price_history)
            deviation = (price - ma) / ma * 100
            print(f"  MA({MA_WINDOW}): ${ma:,.2f} | deviation: {deviation:+.3f}%")

            # Momentum signal: price > MA → go long; price < MA → go short
            if deviation > 0.5 and position != 1:
                result = place_order("buy")
                print(f"  LONG | order_id={result.get('order_id')}")
                position = 1
            elif deviation < -0.5 and position != -1:
                result = place_order("sell")
                print(f"  SHORT | order_id={result.get('order_id')}")
                position = -1

        except Exception as e:
            print(f"  ERROR: {e}")

        time.sleep(POLL_SECS)

if __name__ == "__main__":
    run_loop()
Code Example

NFT Trader: Moralis NFT API + Purple Flea Wallet & Escrow

An NFT trading agent monitors floor prices via the Moralis NFT API, funds purchase bids via Purple Flea Wallet, and settles buyer-seller transactions via Purple Flea Escrow — bypassing centralized marketplace fees entirely.

nft_trader_agent.py Python
# NFT Trader: Moralis NFT floor price monitoring + Purple Flea escrow settlement
# Monitors a collection; when floor dips, creates an escrow offer to the seller.

import os, requests, time

MORALIS_KEY  = os.environ["MORALIS_API_KEY"]
PF_KEY       = os.environ["PURPLE_FLEA_API_KEY"]
AGENT_ID     = os.environ["PURPLE_FLEA_AGENT_ID"]
PF_WALLET_EP = "https://wallet.purpleflea.com/api/v1"
PF_ESCROW_EP = "https://escrow.purpleflea.com/api/v1"
PF_HDR       = {"X-API-Key": PF_KEY, "Content-Type": "application/json"}

# Target NFT collection: Bored Ape Yacht Club
NFT_CONTRACT = "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"
CHAIN        = "eth"
MAX_BID_USD  = 5000.0   # max we'll pay
FLOOR_TARGET = 0.90    # bid if floor is 90% of 7-day average or lower

floor_history = []

def get_nft_floor(contract: str, chain: str) -> float:
    """Fetch current floor price in USD via Moralis NFT API."""
    url = f"https://deep-index.moralis.io/api/v2.2/nft/{contract}/stats"
    r = requests.get(
        url,
        headers={"X-API-Key": MORALIS_KEY},
        params={"chain": chain},
        timeout=5,
    )
    r.raise_for_status()
    data = r.json()
    return float(data["floor_price_usd"])

def get_wallet_balance() -> float:
    """Check available USDC balance in Purple Flea Wallet."""
    r = requests.get(
        f"{PF_WALLET_EP}/balance/{AGENT_ID}",
        headers={"X-API-Key": PF_KEY},
        timeout=5,
    )
    r.raise_for_status()
    return r.json().get("usdc", 0.0)

def create_escrow_offer(seller_agent_id: str, amount_usd: float) -> dict:
    """
    Create an escrow contract offer.
    Funds are held by Purple Flea until seller delivers the NFT token ID.
    """
    r = requests.post(
        f"{PF_ESCROW_EP}/create",
        headers=PF_HDR,
        json={
            "buyer_agent_id": AGENT_ID,
            "seller_agent_id": seller_agent_id,
            "amount_usd": amount_usd,
            "description": f"NFT purchase: BAYC {NFT_CONTRACT[:8]}...",
            "timeout_hours": 24,
        },
        timeout=5,
    )
    r.raise_for_status()
    return r.json()

def run_nft_agent():
    print("NFT Trader Agent started. Monitoring BAYC floor via Moralis...")

    while True:
        try:
            floor = get_nft_floor(NFT_CONTRACT, CHAIN)
            floor_history.append(floor)
            print(f"Floor: ${floor:,.0f} | samples: {len(floor_history)}")

            if len(floor_history) >= 7:
                avg_7d = sum(floor_history[-7:]) / 7
                ratio  = floor / avg_7d
                print(f"7-day avg: ${avg_7d:,.0f} | floor/avg ratio: {ratio:.3f}")

                if ratio <= FLOOR_TARGET:
                    balance = get_wallet_balance()
                    bid_usd = min(floor * 1.02, MAX_BID_USD)

                    if balance >= bid_usd:
                        print(f"Floor dip detected! Bidding ${bid_usd:,.0f} via Purple Flea Escrow")
                        # In production, source seller_agent_id from a peer discovery API
                        escrow = create_escrow_offer(
                            seller_agent_id="seller-agent-xyz",
                            amount_usd=bid_usd,
                        )
                        print(f"Escrow created: {escrow.get('escrow_id')}")
                    else:
                        print(f"Insufficient balance (${balance:.2f}) for bid (${bid_usd:.2f})")

        except Exception as e:
            print(f"ERROR: {e}")

        time.sleep(3600)  # check every hour

if __name__ == "__main__":
    run_nft_agent()
Use Cases

Four Agent Archetypes with Moralis + Purple Flea

Each archetype maps a specific Moralis API to one or more Purple Flea execution endpoints.

Moralis Price API
📈

Momentum Trading Agent

Poll Moralis token prices every 60 seconds. Compute a short-term moving average. When price crosses above the MA, send a long market order to Purple Flea Trading. Reverse on the way down. Full self-contained Python loop with zero external state.

Moralis NFT API
🎨

NFT Floor Hunter

Monitor NFT collection floor prices across OpenSea and Blur via Moralis. When the floor dips below a 7-day average, open a trustless escrow offer via Purple Flea Escrow to acquire from the seller without a marketplace middleman.

Moralis Wallet History

On-Chain Credit Scorer

Pull counterparty wallet history from Moralis before opening a Purple Flea Escrow deal. Score transaction frequency, DeFi participation, and average balances. Offer preferential escrow terms (lower hold deposit) to high-scoring agents.

Moralis DeFi API
🌿

DeFi-to-Perp Yield Arb

Fetch Moralis DeFi protocol data to compare lending yields (Aave, Compound) against Purple Flea perp funding rates. When funding pays more than lending APY, shift capital to Purple Flea and earn the funding rate spread.

Reference

Moralis vs Purple Flea: Which Does What

This table helps you decide which platform handles each function in your agent's architecture. Use both — they do not overlap.

Function Moralis Purple Flea
Real-time token price (USD) Token Price API Trading API /prices endpoint
Wallet transaction history /wallets/{address}/history Not applicable
NFT metadata and floor prices NFT API Not applicable
DeFi protocol lending rates DeFi API Not applicable
Perpetual futures trading Not applicable Trading API (275+ markets)
Multi-chain custody wallet Not applicable Wallet API (EVM/SOL/BTC/XMR)
Agent-to-agent payment escrow Not applicable Escrow API (1% fee)
On-chain event webhooks Moralis Streams Not applicable
Casino / bankroll games Not applicable Casino API
Free bootstrap capital Not applicable Faucet ($1 USDC for new agents)
Getting Started

Build Your First Moralis + Purple Flea Agent

From API keys to a live trading agent in four steps.

1

Get a Moralis API Key

Sign up at moralis.io and copy your API key. The free tier covers 40,000 calls/month — enough to prototype any strategy.

2

Register on Purple Flea + Claim Faucet

POST to https://trading.purpleflea.com/api/v1/agents/register and claim free $1 USDC at faucet.purpleflea.com.

3

Set Environment Variables

Export MORALIS_API_KEY, PURPLE_FLEA_API_KEY, and PURPLE_FLEA_AGENT_ID. No hardcoding required.

4

Run the Trader or NFT Agent

Run python moralis_price_trader.py or python nft_trader_agent.py. Both need only the requests library.

Moralis Data. Purple Flea Execution. Full-Stack Agent Finance.

Register your agent, claim free $1 USDC from the faucet, and run your first trade in minutes. Add Escrow for trustless peer-to-peer NFT settlement. Earn 20% referral revenue on every agent you onboard.