This tutorial walks through building an AI agent that trades prediction markets using real Depthy data. We will use LangChain to define tools, connect them to Depthy's REST API, implement a concrete strategy — buy when smart money buys and volume anomalies confirm — and sketch a backtest against historical data. Everything here uses real endpoints you can call right now. No mock data, no placeholders. By the end, you will have a working agent that can scan Polymarket for high-conviction opportunities and explain its reasoning.

STEP 1

Get Your API Key

Register with a single curl command. No credit card, no approval process. You get a key back instantly.

curl -X POST https://depthy.io/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com"}'

Response:

{
  "api_key": "dpth_free_a1b2c3d4...",
  "tier": "free",
  "daily_limit": 100
}

Save this key. The free tier gives you 100 API calls per day — more than enough to prototype and test your agent logic. When you are ready to go live with real capital, upgrade to the Agent tier ($0.001–$0.01 per call, pay-per-query, no daily cap) for full wallet data, real-time SSE streaming, and access to backtesting endpoints.

STEP 2

Define LangChain Tools

Each Depthy endpoint becomes a LangChain tool. The @tool decorator turns a Python function into something the LLM can call. The docstring is critical — LangChain uses it to decide when and why to invoke each tool.

import requests
import json
from langchain.tools import tool

API_KEY = "dpth_free_your_key_here"
BASE = "https://depthy.io"
headers = {"Authorization": f"Bearer {API_KEY}"}

@tool
def get_active_markets() -> str:
    """Get active prediction markets ranked by 24h trade volume.
    Returns market titles, prices, trade counts, and signal activity."""
    resp = requests.get(f"{BASE}/v1/pm/markets/active", headers=headers)
    return resp.text

@tool
def get_smart_money_signals() -> str:
    """Get latest smart money signals -- trades by high-score wallets.
    Includes wallet address, trade size, market, and direction."""
    resp = requests.get(f"{BASE}/v1/pm/signals/latest", headers=headers)
    return resp.text

@tool
def get_volume_anomalies() -> str:
    """Get markets with unusual volume spikes (3x+ above 24h baseline).
    Returns spike ratio, hourly counts, and market details."""
    resp = requests.get(f"{BASE}/v1/pm/signals/volume-anomalies", headers=headers)
    return resp.text

@tool
def get_wallet_profile(wallet_address: str) -> str:
    """Get trade history and profile for a specific Polymarket wallet.
    Args: wallet_address: The 0x... address to look up."""
    resp = requests.get(
        f"{BASE}/v1/pm/wallets/{wallet_address}/history",
        headers=headers
    )
    return resp.text

Each tool returns raw JSON text so the LLM can reason about the full response. You could parse and summarize before returning, but in practice, models like GPT-4o handle raw JSON well and can extract exactly the fields they need. Keeping it raw also means the agent can surface unexpected data points you did not anticipate.

Note that get_wallet_profile requires a wallet address as input. The agent will typically discover addresses from signal data first, then drill into specific wallets to assess their track record before recommending a trade. This chain of calls — signals, then wallet lookup — is how the agent builds conviction.

STEP 3

Build the Strategy

The strategy is simple and explicit: buy when smart money buys AND volume anomalies confirm. Either signal alone is noisy. Both together represent a meaningful convergence — an experienced wallet is putting capital to work in a market that is simultaneously seeing unusual attention.

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_core.prompts import ChatPromptTemplate

llm = ChatOpenAI(model="gpt-4o", temperature=0)

prompt = ChatPromptTemplate.from_messages([
    ("system", """You are a prediction market analyst. Your strategy:
1. Check smart money signals for recent high-conviction trades
2. Cross-reference with volume anomalies -- look for markets where BOTH signals fire
3. When smart money buys AND volume is spiking, that's a strong signal
4. Report the market, direction, wallet score, and volume ratio
Only recommend trades where both conditions are met."""),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

tools = [get_active_markets, get_smart_money_signals,
         get_volume_anomalies, get_wallet_profile]
agent = create_openai_functions_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = executor.invoke({
    "input": "Find prediction markets where smart money is active AND volume is anomalous. What should I buy?"
})
print(result["output"])

With verbose=True, you will see the agent's full chain of thought: which tools it calls, in what order, and how it reasons about the combined data. A typical run looks like this: the agent calls get_smart_money_signals first, identifies markets with recent high-score wallet activity, then calls get_volume_anomalies to check if any of those same markets are spiking. If it finds overlap, it calls get_wallet_profile on the relevant wallets to verify their track record before making a recommendation.

The system prompt is the entire strategy definition. Change it to encode different logic — contrarian plays, momentum following, or size-weighted scoring. The tools stay the same; the reasoning layer is what you customize.

STEP 4

Sketch a Backtest

Before risking real capital, backtest the strategy against historical data. Depthy's /v1/pm/backtest/trades endpoint exports raw trades for any market and time window, and /v1/pm/wallets/top gives you the smart money leaderboard.

# Backtest: "Follow smart money + volume anomaly" strategy
# Uses real Depthy backtest API

def backtest_strategy(market_id, start, end):
    # Get historical trades
    trades = requests.get(
        f"{BASE}/v1/pm/backtest/trades",
        params={"market": market_id, "from": start, "to": end},
        headers=headers
    ).json()

    # Get smart money wallet list
    top = requests.get(
        f"{BASE}/v1/pm/wallets/top?limit=20",
        headers=headers
    ).json()
    smart_wallets = {w["wallet"] for w in top["wallets"]}

    # Find entry points: smart money BUY trades
    entries = []
    for t in trades["trades"]:
        if t["proxy_wallet"] in smart_wallets and t["side"] == "BUY":
            entries.append(t)

    # Calculate PnL assuming market resolved Yes
    total_cost = sum(t["price"] * t["size"] for t in entries)
    total_payout = sum(t["size"] for t in entries)
    roi = (total_payout - total_cost) / total_cost * 100 if total_cost > 0 else 0

    return {
        "entries": len(entries),
        "total_cost": total_cost,
        "potential_payout": total_payout,
        "roi_pct": roi
    }

result = backtest_strategy(
    "0x4c96c7e8...",
    "2026-02-01T00:00:00Z",
    "2026-02-15T00:00:00Z"
)
print(f"Strategy found {result['entries']} entry points")
print(f"ROI if market resolves Yes: {result['roi_pct']:.1f}%")

This is a sketch — intentionally simplified to show the mechanics. A production backtest should cross-reference signal timestamps with volume anomaly windows (not just smart money addresses), account for slippage and the bid-ask spread on Polymarket, and handle markets that resolved No. The API provides all the raw data; the strategy logic is yours to refine.

One important nuance: the backtest/trades and wallets/top endpoints require the Metered (Agent) tier or higher. Free tier returns 403 on these. If you are still prototyping, you can test the live signal endpoints on free and save backtesting for when you upgrade.

Next Steps

You now have a working agent that can scan markets, cross-reference two signal types, and explain its reasoning. Here is where to go from here:

  • SSE streaming for real-time delivery — Instead of polling, open a persistent connection to /v1/pm/signals/stream and react to signals the moment they fire. See the Agent Docs for the full SSE integration guide.
  • MCP server for Claude integration — If you use Claude Desktop or Claude Code, the Depthy MCP server gives Claude native tool access to all 7 endpoints. No HTTP code needed. Setup takes 30 seconds.
  • Scale to Agent tier — When your strategy is validated and you are ready for production, the Metered tier unlocks unlimited calls, full wallet addresses, real-time SSE with no delay, and historical backtest data.
  • Combine all 4 signal types — This tutorial used smart money + volume anomalies. Depthy also detects whale movements and depth imbalance. Layering all four signal types into a composite scoring model can significantly improve signal-to-noise ratio.