Autonomous On-Chain Trading

Build an NFT Sniping
AI Agent

NFT markets move in milliseconds. Human traders cannot monitor hundreds of collections simultaneously or execute purchases the instant an underpriced listing appears. AI agents can. This guide walks through building a production-ready sniping agent backed by the Purple Flea Wallet API for zero-latency on-chain purchases.


What is NFT sniping,
and why agents win at it

NFT sniping is the practice of identifying and purchasing NFTs that are listed below their true market value before other buyers notice. These opportunities arise constantly: a holder in a hurry lists at the wrong price, a floor-price calculation lags reality, or a rare trait is incorrectly priced relative to the rest of a collection. The window to capture these trades is often ten to thirty seconds.

Human traders have a fundamental ceiling: attention bandwidth. You can watch one collection at a time, on one marketplace at a time, and your reaction time from seeing a listing to executing a purchase adds browser latency, human processing time, and wallet confirmation steps. An AI agent has none of these limitations. It monitors hundreds of collections across Blur, OpenSea, and Magic Eden simultaneously, computes expected value against floor price in real time, and calls a wallet API to sign and broadcast a transaction β€” all in under a second.

The edge is structural, not predictive. The agent does not need to forecast which NFTs will appreciate. It only needs to identify listings priced below the current market consensus, buy them, and list them back at or slightly below the current floor. Done at volume with tight risk controls, this produces consistent positive expectation.


How the agent
fits together

A sniping agent is a tight feedback loop: observe prices, evaluate opportunity, act, and track results. Every component has a single responsibility.

Architecture Overview

  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚                     NFT Sniping Agent                           β”‚
  β”‚                                                                 β”‚
  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
  β”‚  β”‚ Price Oracle  │───▢│  AI Agent    │───▢│  Wallet API      β”‚  β”‚
  β”‚  β”‚              β”‚    β”‚  (Evaluator) β”‚    β”‚  (Purple Flea)   β”‚  β”‚
  β”‚  β”‚ β€’ Blur API   β”‚    β”‚              β”‚    β”‚                  β”‚  β”‚
  β”‚  β”‚ β€’ OpenSea    β”‚    β”‚ β€’ Floor diff β”‚    β”‚ β€’ Sign tx        β”‚  β”‚
  β”‚  β”‚ β€’ Magic Eden β”‚    β”‚ β€’ Trait EV   β”‚    β”‚ β€’ Broadcast      β”‚  β”‚
  β”‚  β”‚ β€’ WebSockets β”‚    β”‚ β€’ Risk check β”‚    β”‚ β€’ Gas estimate   β”‚  β”‚
  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
  β”‚                             β”‚                     β”‚            β”‚
  β”‚                             β–Ό                     β–Ό            β”‚
  β”‚                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
  β”‚                       β”‚  Decision    β”‚    β”‚  NFT Marketplace β”‚  β”‚
  β”‚                       β”‚  Logger      β”‚    β”‚  (Buy executes)  β”‚  β”‚
  β”‚                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Price Oracle

Polls Blur, OpenSea, and Magic Eden APIs (plus WebSocket streams where available) to maintain a real-time order book for each monitored collection.

👁

AI Evaluator

Computes the discount relative to floor, adjusts for trait rarity, checks against daily spend limits, and returns a buy/skip decision with confidence score.

💸

Wallet API

The Purple Flea Wallet API holds ETH/SOL, estimates gas, signs transactions, and broadcasts to the network β€” all via a single REST call with no local keystore required.


What you need
before starting

  • 1
    Purple Flea wallet with funded ETH or SOL. Create one at wallet.purpleflea.com. Fund it with enough ETH to cover purchases plus gas. A reasonable starting float is 0.5 ETH for Ethereum collections or 20 SOL for Solana collections. The wallet API exposes balance, send, and swap endpoints β€” no browser extension needed.
  • 2
    ETH for gas (Ethereum sniping). Each failed transaction still costs gas. Budget for failed bids: high-competition collections see 5-10 competing agents on every underpriced listing. Keep 0.05–0.1 ETH reserved purely for gas so purchase budget is never drained by failed transactions.
  • 3
    Target collection list with floor price baselines. Start with 3–5 collections you understand. For each, record: current floor price, 30-day floor price average, volume traded daily, and typical listing depth within 5% of floor. Thin markets (under 1 ETH daily volume) give fewer opportunities but less competition.
  • 4
    Marketplace API credentials. Blur and OpenSea both require API keys for high-frequency polling. Magic Eden has a free tier. Sign up for each. WebSocket access (Blur in particular) is the fastest signal for new listings β€” reduce your polling to a fallback only.
  • 5
    Python 3.11+ with aiohttp, web3.py, and requests. The agent runs asynchronously β€” synchronous HTTP will miss opportunities during I/O waits. Use asyncio event loops and aiohttp sessions for all marketplace API calls.

Building the agent
step by step

Every function below is production-realistic. Mock responses are labelled clearly. The wallet integration uses real Purple Flea API endpoints.

Step 1 — Create and fund the agent wallet

wallet_setup.py
import requests PURPLEFLEA_API_KEY = "pf_sk_..." BASE_URL = "https://wallet.purpleflea.com/v1" HEADERS = { "Authorization": f"Bearer {PURPLEFLEA_API_KEY}", "Content-Type": "application/json", } def create_agent_wallet(label: str = "nft-sniper-agent") -> dict: """ Create a custodial ETH wallet for the agent. Returns wallet address, wallet_id, and API credentials. No local private key management required. """ resp = requests.post( f"{BASE_URL}/wallet/create", headers=HEADERS, json={"chain": "ethereum", "label": label}, ) resp.raise_for_status() wallet = resp.json() print(f"Agent wallet created: {wallet['address']}") return wallet # { "wallet_id": "...", "address": "0x...", "chain": "ethereum" } def get_wallet_balance(wallet_id: str) -> dict: """Returns ETH balance plus any ERC-20 tokens held.""" resp = requests.get( f"{BASE_URL}/wallet/{wallet_id}/balance", headers=HEADERS, ) resp.raise_for_status() return resp.json() # { "eth": "0.482", "usd_value": "1204.50", ... } def reserve_gas_budget(total_eth: float, gas_reserve_pct: float = 0.15) -> tuple: """ Split wallet balance into purchase budget and gas reserve. Never spend the gas reserve on NFT purchases. """ gas_reserve = total_eth * gas_reserve_pct purchase_budget = total_eth - gas_reserve return purchase_budget, gas_reserve

Step 2 — Monitor floor prices across marketplaces

price_oracle.py
import asyncio import aiohttp from typing import Dict, List, Optional from dataclasses import dataclass @dataclass class Listing: token_id: str price_eth: float marketplace: str seller: str traits: dict listing_url: str @dataclass class CollectionStats: slug: str floor_price_eth: float floor_7d_avg: float volume_24h_eth: float listings_below_floor: int async def fetch_blur_floor(session: aiohttp.ClientSession, collection: str) -> float: """Fetch current floor price from Blur API.""" url = f"https://api.blur.io/v1/collections/{collection}/floor" async with session.get(url) as resp: data = await resp.json() return float(data["floorPrice"]["amount"]) # mock response shape async def fetch_opensea_listings( session: aiohttp.ClientSession, collection_slug: str, max_price_eth: float, limit: int = 20 ) -> List[Listing]: """Fetch active listings below max_price_eth from OpenSea v2 API.""" url = f"https://api.opensea.io/v2/listings/collection/{collection_slug}/all" params = {"limit": limit, "order_by": "eth_price"} headers = {"X-API-KEY": "YOUR_OPENSEA_KEY"} async with session.get(url, params=params, headers=headers) as resp: data = await resp.json() listings = [] for item in data.get("listings", []): price = float(item["price"]["current"]["value"]) / 1e18 # wei to ETH if price <= max_price_eth: listings.append(Listing( token_id=item["protocol_data"]["parameters"]["offer"][0]["identifierOrCriteria"], price_eth=price, marketplace="opensea", seller=item["protocol_data"]["parameters"]["offerer"], traits={}, # fetch separately via /nft endpoint listing_url=f"https://opensea.io/assets/ethereum/{collection_slug}/{item['..']}", )) return listings async def get_consensus_floor(session: aiohttp.ClientSession, collection: str) -> float: """ Fetch floor from multiple sources and return the median. A single API can lag or be manipulated β€” use 3 sources. """ prices = await asyncio.gather( fetch_blur_floor(session, collection), # fetch_magic_eden_floor(session, collection), # for Solana # fetch_opensea_floor(session, collection), return_exceptions=True, ) valid = [p for p in prices if isinstance(p, float)] return sorted(valid)[len(valid) // 2] # median

Step 3 — Calculate expected value vs floor

evaluator.py
from dataclasses import dataclass @dataclass class BuyDecision: should_buy: bool listing: object floor_price: float discount_pct: float expected_profit_eth: float confidence: str # "high" | "medium" | "skip" def estimate_trait_premium(traits: dict, collection_slug: str) -> float: """ Returns an ETH premium above floor justified by rare traits. In production: query trait rarity APIs (rarity.tools, etc.) Here we return a conservative flat estimate. """ rare_traits = [t for t in traits.values() if t.get("rarity_pct", 100) < 5] return len(rare_traits) * 0.005 # 0.005 ETH per rare trait β€” tune per collection def evaluate_listing( listing, floor_price: float, min_discount_pct: float = 8.0, marketplace_fee_pct: float = 2.5, royalty_pct: float = 5.0, ) -> BuyDecision: """ Decide whether to buy a listing. min_discount_pct: minimum % below floor to trigger a buy. Set higher (10-15%) for thin markets with higher risk. marketplace_fee_pct + royalty_pct are costs on the SELL side. """ trait_premium = estimate_trait_premium(listing.traits, "collection") effective_floor = floor_price + trait_premium discount = (effective_floor - listing.price_eth) / effective_floor * 100 # Net sell price after fees (assuming we list at 99% of floor) sell_price = floor_price * 0.99 sell_proceeds = sell_price * (1 - (marketplace_fee_pct + royalty_pct) / 100) expected_profit = sell_proceeds - listing.price_eth should_buy = discount >= min_discount_pct and expected_profit > 0 confidence = "high" if discount >= 15 else ("medium" if discount >= min_discount_pct else "skip") return BuyDecision( should_buy=should_buy, listing=listing, floor_price=floor_price, discount_pct=discount, expected_profit_eth=expected_profit, confidence=confidence, )

Step 4 — Execute the buy via Purple Flea Wallet API

executor.py
import requests from web3 import Web3 BASE_URL = "https://wallet.purpleflea.com/v1" HEADERS = {"Authorization": "Bearer pf_sk_...", "Content-Type": "application/json"} def build_opensea_buy_calldata(listing) -> str: """ Build the calldata to fulfill an OpenSea Seaport order. In production, use the OpenSea SDK or encode via web3.py ABI. Returns hex-encoded calldata string. """ # Placeholder β€” in production, encode fulfillBasicOrder() or fulfillOrder() return "0x..." def execute_nft_buy( wallet_id: str, listing, decision, nft_contract: str, ) -> dict: """ Send a transaction via Purple Flea Wallet API to purchase the NFT. The wallet holds ETH and signs the transaction server-side β€” no local key management, no MetaMask, no browser extension. """ calldata = build_opensea_buy_calldata(listing) payload = { "wallet_id": wallet_id, "to": "0x00000000000000ADc04C56Bf30aC9d3c0aAF14dC", # Seaport 1.5 "value_eth": str(listing.price_eth), "data": calldata, "gas_strategy": "fast", # "slow" | "standard" | "fast" | "instant" "max_priority_fee_gwei": 3, # tune for snipe speed vs cost "idempotency_key": f"snipe-{listing.token_id}-{int(time.time())}", } resp = requests.post(f"{BASE_URL}/wallet/send", headers=HEADERS, json=payload) result = resp.json() if result.get("status") == "submitted": print(f"Snipe submitted: tx={result['tx_hash']} token={listing.token_id} price={listing.price_eth} ETH") print(f"Expected profit: {decision.expected_profit_eth:.4f} ETH") return result

Step 5 — List for sale after purchase

sell_strategy.py
import time def calculate_list_price( purchase_price_eth: float, current_floor_eth: float, strategy: str = "undercut", ) -> float: """ Determine the listing price after a successful snipe. Strategies: - "undercut": list 1-2% below current floor for fast exit - "hold": list at floor, wait for market to come to you - "premium": list above floor if rare traits justify it """ if strategy == "undercut": return round(current_floor_eth * 0.985, 4) elif strategy == "hold": return round(current_floor_eth, 4) else: return round(current_floor_eth * 1.05, 4) def list_nft_on_blur( wallet_id: str, token_id: str, contract_address: str, list_price_eth: float, expiry_hours: int = 24, ) -> dict: """ List the purchased NFT on Blur via Purple Flea Wallet API (wallet signs the Seaport listing order off-chain, then submits). Blur typically charges 0.5% marketplace fee. """ payload = { "wallet_id": wallet_id, "action": "sign_listing", "marketplace": "blur", "contract": contract_address, "token_id": token_id, "price_eth": list_price_eth, "expiry_unix": int(time.time()) + expiry_hours * 3600, } # POST to Purple Flea wallet API β€” returns signed order for submission # The wallet API handles EIP-712 signing without exposing the private key print(f"Listing token {token_id} at {list_price_eth} ETH on Blur") return {"status": "listed", "list_price": list_price_eth}

Complete agent
main loop

The main loop ties every component together: poll prices, evaluate, buy, list. Runs continuously until the daily spend limit is hit or the stop-loss triggers.

nft_sniper_agent.py
import asyncio import logging from datetime import datetime, date from wallet_setup import get_wallet_balance from price_oracle import fetch_opensea_listings, get_consensus_floor from evaluator import evaluate_listing from executor import execute_nft_buy from sell_strategy import calculate_list_price, list_nft_on_blur logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") # ── Agent configuration ────────────────────────────────────────── WALLET_ID = "wlt_..." TARGET_COLLECTIONS = [ {"slug": "azuki", "contract": "0xED5AF...", "chain": "ethereum"}, {"slug": "milady", "contract": "0x5AF0D...", "chain": "ethereum"}, {"slug": "pudgy-penguins", "contract": "0xBd3531...", "chain": "ethereum"}, ] MAX_SPEND_PER_DAY_ETH = 0.3 POLL_INTERVAL_SECONDS = 8 MIN_DISCOUNT_PCT = 8.0 # ── Risk tracking ───────────────────────────────────────────────── daily_spent_eth = 0.0 daily_reset_date = date.today() portfolio = [] # NFTs currently held def check_daily_limit(cost: float) -> bool: global daily_spent_eth, daily_reset_date if date.today() != daily_reset_date: daily_spent_eth = 0.0 daily_reset_date = date.today() return daily_spent_eth + cost <= MAX_SPEND_PER_DAY_ETH async def snipe_collection(session, collection: dict): global daily_spent_eth, portfolio slug = collection["slug"] floor = await get_consensus_floor(session, slug) # Look for listings at least (min_discount - 1)% below floor max_price = floor * (1 - (MIN_DISCOUNT_PCT - 1) / 100) listings = await fetch_opensea_listings(session, slug, max_price, limit=5) for listing in listings: decision = evaluate_listing(listing, floor, MIN_DISCOUNT_PCT) if not decision.should_buy: continue if not check_daily_limit(listing.price_eth): logging.warning("Daily spend limit reached. Pausing until midnight.") return logging.info( f"SNIPE {slug} #{listing.token_id} @ {listing.price_eth:.4f} ETH " f"(floor={floor:.4f}, discount={decision.discount_pct:.1f}%, " f"expected_profit={decision.expected_profit_eth:.4f} ETH)" ) result = execute_nft_buy(WALLET_ID, listing, decision, collection["contract"]) if result.get("status") == "submitted": daily_spent_eth += listing.price_eth list_price = calculate_list_price(listing.price_eth, floor, "undercut") list_nft_on_blur(WALLET_ID, listing.token_id, collection["contract"], list_price) portfolio.append({"token_id": listing.token_id, "cost": listing.price_eth, "list_price": list_price}) break # one buy per collection per cycle to avoid over-concentration async def main(): import aiohttp logging.info("NFT Sniper Agent starting...") bal = get_wallet_balance(WALLET_ID) logging.info(f"Wallet balance: {bal['eth']} ETH (${bal['usd_value']})") async with aiohttp.ClientSession() as session: while True: tasks = [snipe_collection(session, c) for c in TARGET_COLLECTIONS] await asyncio.gather(*tasks, return_exceptions=True) await asyncio.sleep(POLL_INTERVAL_SECONDS) if __name__ == "__main__": asyncio.run(main())

Protecting the
agent portfolio

NFT sniping carries real financial risk. Floor prices can crater overnight. A single bad collection can wipe out weeks of snipe profits. These rules are non-negotiable.

🔓

Max Spend Per Day

Hard-code a daily ETH cap in the agent. Once reached, the agent stops buying until the next calendar day. Start at 0.1-0.3 ETH while calibrating. The cap prevents a bug or bad market from draining the wallet in a single session.

🚫

Portfolio Stop-Loss

Track the total ETH value of held NFTs (mark-to-market at current floor). If portfolio value drops more than 25% from its peak, halt all new purchases. Floor crashes propagate across collections β€” stop early.

Max Hold Period

Set a maximum hold time (e.g., 72 hours). If an NFT has not sold within the window, lower the listing price by 2% every 12 hours until it clears. Illiquidity is the second biggest risk after floor crashes.

📈

Concentration Limit

No single collection should represent more than 30% of total NFT portfolio value. Correlation within a single collection is 1.0 β€” if it crashes, everything in it crashes together. Diversify across collections and chains.

Gas Budget Reserve

Keep 15% of wallet ETH reserved exclusively for gas. Failed transactions on Ethereum still consume gas. High competition on popular collections means a 40-60% failure rate on snipe attempts. Budget for it.

📄

Full Audit Log

Every snipe attempt, successful purchase, and sale must be logged with timestamp, token ID, prices, floor at time of purchase, tx hash, and P&L. Essential for tuning the minimum discount threshold and for debugging bad decisions.


The Wallet API built
for autonomous agents

Most crypto wallets are designed for humans with browsers. Purple Flea is built for agents that need to transact programmatically, reliably, and fast.

🔒

No Local Key Storage

The private key never leaves Purple Flea's HSM. Your agent authenticates with an API key and the wallet signs on the server. No risk of key theft from agent memory or logs.

Multi-Chain, One API

ETH for OpenSea and Blur sniping. SOL for Magic Eden sniping on Solana. Both chains through the same REST API. No chain-switching logic, no separate keystores.

Gas Strategy Control

Select slow, standard, fast, or instant gas strategy per transaction. For sniping, use fast or instant to outrun competing agents.

📈

Portfolio Balance API

Query ETH, SOL, and any ERC-20 balance in real time. Know your exact purchasing power before evaluating each listing. No stale balance estimates.

🔄

Idempotent Sends

Every send endpoint accepts an idempotency_key. If your agent retries a failed request, the transaction is not re-broadcast. No accidental double-purchases during network hiccups.

🌐

Your NFT Sniping Agent Can Refer Other Agents

Your agent can programmatically generate and distribute referral links for Purple Flea. When another sniping agent, DeFi bot, or trading agent signs up via your link, you earn 10–20% of their transaction fees in perpetuity β€” a passive revenue stream that compounds as the wider agent ecosystem grows. One sniping agent that onboards five others earns income on every snipe they collectively execute.


How Purple Flea's Wallet API
enables NFT sniping

Speed and capital availability are the two bottlenecks in NFT sniping. The Purple Flea Wallet API eliminates both: instant USDC-to-ETH swaps keep dry powder ready on any chain, and a single balance endpoint tells the agent exactly what it can spend before it bids.

🔀

Fast USDC / ETH Swaps

Keep idle capital in USDC to earn yield, then call the Wallet API swap endpoint to convert to ETH in milliseconds when a snipe opportunity appears. Your agent always has dry powder ready without leaving ETH sitting idle between opportunities.

🌎

ETH, Base & Polygon Simultaneously

One API key controls wallets on Ethereum mainnet, Base, and Polygon. Snipe Blur listings on Ethereum, low-fee collections on Base, and high-volume drops on Polygon β€” all from a single agent loop with no chain-switching complexity.

📈

Check Capital Before Every Bid

Call GET /v1/wallet/balance before evaluating each listing. The response includes ETH, USDC, and USD value in real time so the agent never attempts a purchase it cannot afford and never wastes gas on a transaction that will revert.

wallet_api_integration.py
import requests PURPLEFLEA_API_KEY = "pf_sk_..." BASE_URL = "https://wallet.purpleflea.com/v1" HEADERS = { "Authorization": f"Bearer {PURPLEFLEA_API_KEY}", "Content-Type": "application/json", } # ── 1. Check available capital before sniping ──────────────────── def check_available_capital(wallet_id: str, chain: str = "ethereum") -> dict: """ GET /v1/wallet/balance β€” returns real-time ETH, USDC, and USD value. Call this before each evaluation cycle so the agent never bids more than it holds. Responses are sub-50ms; safe to call per cycle. """ resp = requests.get( f"{BASE_URL}/wallet/{wallet_id}/balance", headers=HEADERS, params={"chain": chain}, ) resp.raise_for_status() data = resp.json() # { "eth": "0.482", "usdc": "1200.00", "usd_value": "2405.20", "chain": "ethereum" } return data # ── 2. Swap USDC β†’ ETH when dry powder is needed ──────────────── def swap_usdc_to_eth( wallet_id: str, usdc_amount: float, chain: str = "ethereum", slippage_pct: float = 0.5, ) -> dict: """ Convert USDC to ETH via Purple Flea's on-chain swap. Use when ETH balance drops below the snipe threshold but USDC reserves are available. Slippage of 0.5% is tight enough for sniping capital without missing the opportunity window. """ resp = requests.post( f"{BASE_URL}/wallet/{wallet_id}/swap", headers=HEADERS, json={ "from_token": "USDC", "to_token": "ETH", "amount": str(usdc_amount), "chain": chain, "max_slippage_pct": slippage_pct, }, ) resp.raise_for_status() result = resp.json() print(f"Swapped {usdc_amount} USDC β†’ {result['eth_received']} ETH on {chain}") return result # { "eth_received": "0.25", "tx_hash": "0x...", "status": "confirmed" } # ── 3. Multi-chain capital check (ETH + Base + Polygon) ────────── def get_total_snipe_capital(wallet_id: str) -> dict: """ Aggregate available ETH across Ethereum mainnet, Base, and Polygon. Agent can route each snipe to whichever chain has the best opportunity and sufficient balance β€” no manual chain management required. """ chains = ["ethereum", "base", "polygon"] capital = {} for chain in chains: bal = check_available_capital(wallet_id, chain) capital[chain] = { "eth": float(bal["eth"]), "usdc": float(bal["usdc"]), "usd_total": float(bal["usd_value"]), } return capital # Example output: # { "ethereum": {"eth": 0.48, "usdc": 500.0, "usd_total": 1705.0}, # "base": {"eth": 0.10, "usdc": 200.0, "usd_total": 452.0}, # "polygon": {"eth": 2.50, "usdc": 100.0, "usd_total": 156.0} }

Full sniping workflow:
detect, buy, reinvest

A production NFT sniping agent is more than a buy loop. It monitors floors continuously, executes the moment an underpriced listing appears, and moves proceeds to a trading account for reinvestment β€” compounding profits rather than leaving them idle.

1

Monitor NFT floors and detect underpriced listings

The price oracle polls Blur, OpenSea, and Magic Eden every 5–8 seconds and maintains a consensus floor price for each watched collection. Any listing that arrives below floor * (1 - min_discount_pct / 100) is flagged for evaluation. WebSocket streams from Blur reduce latency to under one second for new listings on high-volume collections.

2

Verify capital via GET /v1/wallet/balance before bidding

Before submitting any transaction, call GET /v1/wallet/balance to confirm available ETH exceeds the listing price plus an estimated gas buffer. If ETH is low but USDC reserves exist, trigger the swap endpoint to top up automatically. This prevents reverted transactions and wasted gas fees.

3

Execute purchase via Wallet API when opportunity is detected

Call POST /v1/wallet/send with gas_strategy: "fast" and an idempotency key tied to the token ID and timestamp. The Purple Flea wallet signs and broadcasts the transaction server-side β€” no local keystore, no MetaMask pop-up, no human confirmation step. The agent completes the buy in the same time window that a human trader would still be opening their browser wallet.

4

List the purchased NFT immediately below current floor

On confirmed purchase, the agent constructs a Seaport listing order at 98.5% of the current floor price and submits it via the wallet's sign_listing action. Undercutting the floor by 1–2% ensures the position exits quickly without waiting for a floor buyer to appear organically.

5

Move sale proceeds to trading account for reinvestment

After a successful sale, the ETH proceeds land back in the wallet. The agent automatically transfers a configurable percentage (e.g., 80%) to a Purple Flea trading account via POST /v1/wallet/send, where the funds can be deployed into DeFi strategies or used to fund the next sniping cycle. The remaining 20% stays in the wallet as a gas and dry-powder reserve. This compounding loop means every successful snipe increases the capital base for the next opportunity.


Common questions
from builders

How do I minimise failed transactions and wasted gas? +
Use WebSocket streams from Blur instead of polling β€” you see new listings the moment they are indexed, giving you 2-4 seconds of lead time over polling competitors. Set gas_strategy: "fast" on buys, not "instant", unless the collection is extremely competitive (e.g., top-10 blue chips). The difference in cost between fast and instant adds up significantly across hundreds of failed attempts. Also use idempotency keys: if a submit times out, retry without fear of double-spending. Finally, maintain a local cache of recently seen listing IDs β€” do not attempt to buy the same listing twice if a previous attempt is still pending.
How do I handle collections with high royalties? +
Factor royalties into the evaluate_listing function as a cost on the sell side. A collection with 10% royalties requires a significantly larger discount to remain profitable than one with 2.5%. As a rule of thumb: minimum discount threshold = (marketplace fee + royalty + desired profit margin + expected failed-gas cost per successful buy). For a 10% royalty collection, your minimum discount is rarely below 15-18%. Some marketplaces (notably Blur) allow optional royalty payments β€” but skipping royalties can limit where your listing appears. Model this explicitly per marketplace.
What is the best polling interval for price feeds? +
For Blur, use WebSockets β€” polling is a fallback. For OpenSea, the v2 API supports polling down to around 5-second intervals before rate limiting kicks in. Magic Eden allows 2-second polling on free tier. Your consensus floor calculation can run at 30-60 second intervals since floor price moves slowly; it is the individual listing feed that needs low latency. Separate your two polling loops: fast (5-8s) for new listings, slow (30s) for floor updates.
Can I run the agent on multiple collections simultaneously? +
Yes β€” the asyncio.gather() pattern in the main loop handles this natively. Practical limits: Purple Flea Wallet API rate limits allow hundreds of transactions per minute, so the wallet is not the bottleneck. Marketplace API rate limits are the binding constraint. With standard API keys you can comfortably monitor 10-20 collections concurrently. Start with 3-5 collections you know well before scaling, so you can validate the minimum discount thresholds are correctly calibrated per collection.
How do I handle a floor crash after buying? +
The max hold period and portfolio stop-loss are your primary defences. If you bought at 8% below floor and the floor drops 20%, you have a -12% position. The agent should detect the floor drop via its oracle loop, lower the listing price to 1-2% below the new floor, and take the loss quickly. Holding through a crash hoping for recovery is a human bias. The agent should clear positions below its cost basis after a configurable threshold (e.g., floor drops more than 20% from purchase-time floor). Capital recovery and redeployment beats waiting.

Ready to deploy your
NFT sniping agent?

Create a Purple Flea wallet, fund it with ETH or SOL, and start executing on-chain purchases programmatically β€” no browser, no MetaMask, no manual signing.