Build a real-time AI trading agent on Base with GoldRush: streaming signal, cost gate and PnL backfill

Covalent TeamUpdated 19 min read

Build a trading agent on Base: stream OHLCV candles with GoldRush, score them with a z-score, trade only when the edge beats costs, then backfill realized PnL.

This guide builds a small, real-time AI trading agent on Base, end to end. It watches one Uniswap v3 pool through the GoldRush Streaming API, turns each one-minute candle into a deterministic z-score signal, prices every trade it is tempted to make (network fee, pool fee, slippage and a safety margin), and only trades when the expected edge beats all of them. Afterwards it pulls its own wallet history from GoldRush and works out realized profit and loss per trade, so you can tell whether the signal actually pays and tune it with evidence.

It runs in dry-run mode by default: the full loop, with every decision logged and no transaction sent.

About the Streaming API docs. The GoldRush Streaming API's multi-chain reference is being rebuilt and returns in January 2027; Hyperliquid streaming is live today. The stream code here follows the types published in the GoldRush SDK (@covalenthq/client-sdk 3.0.9), which list Base for the OHLCV Pairs stream. Ask GoldRush support to confirm Base streaming is enabled for your key before you rely on it.

What "AI agent" means here

An onchain agent is a program that perceives chain state, decides with a policy, and acts through its own account, within limits you set. Here, the policy is a transparent statistical rule rather than a language model, because a trading decision should be reproducible: the same candles always give the same decision, and every decision is logged with its reasons. You can put an LLM planner on top later; if it writes the same decision shape, nothing downstream changes.

The agent runs one loop:

Step What it does File
See Streams one-minute OHLCV candles for a WETH/USDC pool on Base stream.ts
Decide Scores the latest return with a rolling z-score predict.ts
Price Gets a firm quote and converts every cost to basis points quote.ts, costs.ts
Act Trades only if expected edge > total cost, and only when live trade.ts, agent.ts
Remember Backfills the wallet's swaps and computes realized PnL per trade pnl.ts

Base suits this kind of agent because transactions are cheap and confirm quickly, so a small edge isn't automatically eaten by fees. It is still not free: every Base transaction pays an L2 execution fee and an L1 data fee (Base docs), and the cost gate prices both.

Architecture and guardrails

Keep each responsibility small, with a clear interface, so a failure is easy to isolate:

  • Stream ingestion. One WebSocket connection, normalised into a bar shape your code owns. No model logic.
  • Signal. A pure function of the bars. Same input, same output, easy to test and replay.
  • Cost gate. Turns a firm quote into costs in basis points and makes one comparison.
  • Execution. Sends exactly the transaction the quote returned, after an approval check. Off unless you switch it on.
  • Ledger and backfill. An append-only log of decisions (decisions.jsonl) and a PnL report from the chain itself.
  • Safety. Dry run by default, one decision at a time, no trading on stale or backfilled bars, and a wallet that holds only what the agent may lose.

Set up the project

You need Node.js 22 or later, a GoldRush API key, a Base RPC endpoint (the public https://mainnet.base.org is rate-limited; use a provider for anything beyond testing), and, to trade, a 0x API key and a fresh wallet funded with a little ETH for gas and the USDC it may trade.

mkdir base-agent && cd base-agentnpm init -y && npm pkg set type=modulenpm install @covalenthq/client-sdk ethersnpm install --save-dev tsx typescript @types/node

Create .env. PAIR_ADDRESS must be a pool, not a token: the example is the Uniswap v3 WETH/USDC 0.05% pool on Base (check it on Uniswap's Base deployments or an explorer before you trade against it).

GOLDRUSH_API_KEY=your_goldrush_keyPAIR_ADDRESS=0xd0b53D9277642d899DF5C87A3966A349A798F224BASE_RPC_URL=https://your-base-provider.exampleZEROX_API_KEY=your_0x_keyBOT_WALLET_PK=0x...   # a fresh wallet for the agent only; never commit this fileLIVE=false            # dry run: decide and log, never send

Every setting lives in src/config.ts. The defaults are a cautious starting point, not tuned values:

// Every setting in one place, read from .env. The defaults are a safe starting point, not tuned values.const env = (name: string, fallback?: string) => {    const value = process.env[name] ?? fallback;    if (value === undefined) throw new Error(`Set ${name} in .env`);    return value;}; export const CONFIG = {    goldrushApiKey: env("GOLDRUSH_API_KEY"),    pairAddress: env("PAIR_ADDRESS").toLowerCase(), // a WETH/USDC pool on Base, not a token address    rpcUrl: env("BASE_RPC_URL", "https://mainnet.base.org"),    zeroExApiKey: env("ZEROX_API_KEY", ""),    privateKey: env("BOT_WALLET_PK", ""),    live: env("LIVE", "false") === "true", // dry run unless you set LIVE=true    windowBars: Number(env("WINDOW_BARS", "60")), // z-score window: 60 one-minute returns    zEntry: Number(env("Z_ENTRY", "2.5")), // act only when |z| is at least this    bpsPerSigma: Number(env("BPS_PER_SIGMA", "10")), // your guess at edge per unit of z; the backfill calibrates it    tradeUsdc: env("TRADE_USDC", "100"), // size of each buy, in USDC    poolFeeBps: Number(env("POOL_FEE_BPS", "5")), // the pool's fee tier: 5 for a 0.05% pool    slippageBps: Number(env("SLIPPAGE_BPS", "30")), // worst-case slippage you accept on the quote    safetyBps: Number(env("SAFETY_BPS", "10")), // margin for what you didn't price}; // Token addresses on Base (chain ID 8453).export const USDC = "0x833589fCD6EDb6E08f4c7C32D4f71B54Bda02913";export const WETH = "0x4200000000000000000000000000000000000006";

Stream OHLCV candles from a Base pool

OHLCV is open, high, low, close and volume: one candle per interval for one pool. The OHLCV Pairs stream takes pool addresses, an interval (the candle size, here one minute) and a timeframe (how much history to send first, here an hour, which warms the model up). Credit cost: 1 per minute.

Save this as src/stream.ts:

import { CONFIG, USDC } from "./config";import {    GoldRushClient,    StreamingChain,    StreamingInterval,    StreamingTimeframe,    type OHLCVPairsStreamResponse,} from "@covalenthq/client-sdk"; export type Bar = { time: number; close: number }; // close is always USDC per WETH // Turn one OHLCV event into a bar priced in USDC per WETH, whichever way round the pool lists its tokens.export function toBar(event: OHLCVPairsStreamResponse): Bar {    const usdcIsBase = event.base_token?.contract_address?.toLowerCase() === USDC.toLowerCase();    return { time: Date.parse(event.timestamp), close: usdcIsBase ? 1 / event.close : event.close };} // The stream sends the backfill first, then updates. A candle can be updated more than once while it is open,// so pass a bar on only once a newer one has started: every bar the model sees is final, and replays and// out-of-order updates are dropped.export class BarCloser {    private open: Bar | null = null;    constructor(private onClosed: (bar: Bar) => void) {}     push(bar: Bar) {        if (!this.open || bar.time === this.open.time) {            this.open = bar;        } else if (bar.time > this.open.time) {            this.onClosed(this.open);            this.open = bar;        }    }} export function startOhlcvStream(onClosed: (bar: Bar) => void): () => void {    const client = new GoldRushClient(        CONFIG.goldrushApiKey,        {},        {            onOpened: () => console.log("[stream] connected"),            onClosed: () => console.log("[stream] closed"),            onError: (err) => console.error("[stream] error", err),        }    );    const closer = new BarCloser(onClosed);    return client.StreamingService.subscribeToOHLCVPairs(        {            chain_name: StreamingChain.BASE_MAINNET,            pair_addresses: [CONFIG.pairAddress],            interval: StreamingInterval.ONE_MINUTE,            timeframe: StreamingTimeframe.ONE_HOUR, // about 60 bars of backfill to warm up the model        },        {            next: (events) => {                const bars = events.map(toBar).sort((a, b) => a.time - b.time);                for (const bar of bars) closer.push(bar);            },            error: (err) => console.error("[stream] subscription error", err),        }    );}

Three details keep the signal honest:

  • Price direction. The stream reports the pool's base token priced in its quote token. toBar always returns USDC per WETH, so the sign of z means the same thing whichever way round the pool lists its tokens.
  • Closed bars only. The candle that is still open can change. BarCloser passes a bar on only once a newer one starts, and drops replays and out-of-order updates, which also makes reconnects harmless.
  • The stream pushes arrays. Each message is a list of candles (the backfill arrives as one batch), so sort by time before use.

Turn candles into a deterministic z-score signal

A z-score says how unusual the latest one-minute return is compared with the recent window:

z = (r_t − mean) / sd, where r_t = ln(close_t / close_t−1) and the mean and standard deviation are over the last 60 returns.

A z of −3 means the last minute fell three standard deviations further than usual. The window is fixed for a run, and a flat market (standard deviation 0) gives z = 0, so the signal is deterministic and replayable. Save this as src/predict.ts:

// Rolling z-score of one-minute log returns. Pure and deterministic: the same bars always give the same z.export class ZScoreModel {    private lastClose: number | null = null;    private returns: number[] = [];    constructor(private window = 60) {}     push(close: number) {        if (this.lastClose !== null && close > 0) {            this.returns.push(Math.log(close / this.lastClose));            if (this.returns.length > this.window) this.returns.shift();        }        this.lastClose = close;    }     ready() {        return this.returns.length >= this.window;    }     z(): number {        if (!this.ready()) return 0;        const n = this.returns.length;        const mean = this.returns.reduce((a, b) => a + b, 0) / n;        const sd = Math.sqrt(this.returns.reduce((a, r) => a + (r - mean) ** 2, 0) / n);        return sd === 0 ? 0 : (this.returns[n - 1] - mean) / sd; // flat market: neutral    }}

The agent maps signal strength to an expected edge: edge_bps = |z| × BPS_PER_SIGMA. BPS_PER_SIGMA starts as a guess; the PnL backfill below is how you replace it with a measured number.

Price every trade: the cost gate

Most small strategies don't fail because the signal is wrong; they fail because acting on it costs more than it earns. So the agent puts everything in basis points (1 bp = 0.01%) of the trade size and trades only when:

expected_edge_bps > network_fee_bps + pool_fee_bps + slippage_bps + safety_bps

  • Network fee. Base's L2 execution fee (gas × max fee per gas) plus its L1 data fee, which the OP Stack GasPriceOracle predeploy prices. The agent uses its upper bound, so it errs towards skipping. Because the fee and the WETH leg of the trade are both in ETH, the ratio needs no price feed.
  • Pool fee. The pool's fee tier, 5 bps for a 0.05% pool. The quote already nets it out of what you receive, but the signal is measured against the pool's price, so it counts against the edge.
  • Slippage. The worst case you accept: the gap between the quote's buyAmount and its minBuyAmount, set by slippageBps.
  • Safety margin. For what you didn't price: drift between quote and inclusion, rounding. Tighten it once the backfill shows real fills.

A worked example with illustrative numbers: a 100 USDC buy, a network fee of 1.5 bps, a 5 bp pool fee, a 30 bp slippage cap and a 10 bp margin make a hurdle of 46.5 bps. At 10 bps per sigma, z = −6 (60 bps) trades and z = −4 (40 bps) is skipped.

The price comes from a firm quote: the exact transaction you'd send, with a guaranteed minimum output. This guide uses the 0x Swap API v2 on Base (chain ID 8453), which routes through Uniswap and other Base liquidity; a Uniswap quoter contract works too if you only want that one pool. Save this as src/quote.ts:

import { CONFIG } from "./config"; // The fields this agent reads from a 0x Swap API v2 firm quote.export type FirmQuote = {    liquidityAvailable: boolean;    sellAmount: string;    buyAmount: string;    minBuyAmount: string;    issues: { allowance: { spender: string; actual: string } | null };    transaction: { to: string; data: string; value: string; gas: string | null };}; // A firm quote on Base: the exact transaction to send, and the minimum you'll receive at your slippage cap.export async function getFirmQuote(sellToken: string, buyToken: string, sellAmount: bigint, taker: string) {    const url = new URL("https://api.0x.org/swap/allowance-holder/quote");    url.search = new URLSearchParams({        chainId: "8453",        sellToken,        buyToken,        sellAmount: sellAmount.toString(),        taker,        slippageBps: String(CONFIG.slippageBps),    }).toString();    const res = await fetch(url, { headers: { "0x-api-key": CONFIG.zeroExApiKey, "0x-version": "v2" } });    if (!res.ok) throw new Error(`0x quote failed: ${res.status} ${await res.text()}`);    const quote = (await res.json()) as FirmQuote;    if (!quote.liquidityAvailable) throw new Error("0x found no route for this size");    return quote;}

And the cost maths as src/costs.ts:

import type { FirmQuote } from "./quote";import { ethers } from "ethers"; // OP Stack predeploy on Base that prices the L1 data part of a transaction.const GAS_PRICE_ORACLE = "0x420000000000000000000000000000000000000F";const ORACLE_ABI = ["function getL1FeeUpperBound(uint256 unsignedTxSize) view returns (uint256)"]; // Network fee in wei: the L2 execution fee plus an upper bound on the L1 data fee.export async function networkFeeWei(provider: ethers.JsonRpcProvider, from: string, quote: FirmQuote) {    const tx = quote.transaction;    const gas = tx.gas        ? BigInt(tx.gas)        : await provider.estimateGas({ from, to: tx.to, data: tx.data, value: BigInt(tx.value) });    const { maxFeePerGas, gasPrice } = await provider.getFeeData();    const l2 = gas * (maxFeePerGas ?? gasPrice ?? 0n);    const oracle = new ethers.Contract(GAS_PRICE_ORACLE, ORACLE_ABI, provider);    const l1: bigint = await oracle.getL1FeeUpperBound(ethers.dataLength(tx.data) + 100); // calldata + tx envelope    return l2 + l1;} export type Gate = {    edgeBps: number;    feeBps: number;    poolFeeBps: number;    slippageBps: number;    safetyBps: number;    trade: boolean;}; // The one rule every trade passes: expected edge > network fee + pool fee + slippage + safety margin, all in bps.// notionalWei is the trade's size in ETH terms, so the network fee needs no price feed.export function costGate(    edgeBps: number,    quote: FirmQuote,    feeWei: bigint,    notionalWei: bigint,    poolFeeBps: number,    safetyBps: number): Gate {    const feeBps = Number((feeWei * 1_000_000n) / notionalWei) / 100;    const buy = BigInt(quote.buyAmount);    const slippageBps = Number(((buy - BigInt(quote.minBuyAmount)) * 1_000_000n) / buy) / 100;    const hurdle = feeBps + poolFeeBps + slippageBps + safetyBps;    return { edgeBps, feeBps, poolFeeBps, slippageBps, safetyBps, trade: edgeBps > hurdle };}

Execute only when the gate passes

src/trade.ts buys WETH with TRADE_USDC of USDC, or sells all the WETH the agent holds. It gets a firm quote, prices it, prints the gate, and stops there unless the gate passes and LIVE=true. If 0x reports that the token needs an allowance, it approves the spender the quote names, for that trade's amount only, then sends the quoted transaction as is:

import { CONFIG, USDC, WETH } from "./config";import { costGate, networkFeeWei } from "./costs";import { getFirmQuote } from "./quote";import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider(CONFIG.rpcUrl, 8453, { staticNetwork: true });const wallet = CONFIG.privateKey ? new ethers.Wallet(CONFIG.privateKey, provider) : null;const ERC20 = [    "function approve(address spender, uint256 amount) returns (bool)",    "function balanceOf(address owner) view returns (uint256)",]; // Buy WETH with USDC, or sell the WETH the agent holds, only if the cost gate passes.// In dry run (the default) it prints the decision and sends nothing.export async function tryTrade(side: "buy" | "sell", edgeBps: number, taker: string) {    const [sellToken, buyToken] = side === "buy" ? [USDC, WETH] : [WETH, USDC];    const sellAmount =        side === "buy"            ? ethers.parseUnits(CONFIG.tradeUsdc, 6)            : await new ethers.Contract(WETH, ERC20, provider).balanceOf(taker);    if (sellAmount === 0n) return { side, skipped: "nothing to sell" };     const quote = await getFirmQuote(sellToken, buyToken, sellAmount, taker);    const feeWei = await networkFeeWei(provider, taker, quote);    const notionalWei = side === "buy" ? BigInt(quote.buyAmount) : sellAmount; // WETH leg, in wei    const gate = costGate(edgeBps, quote, feeWei, notionalWei, CONFIG.poolFeeBps, CONFIG.safetyBps);    console.log("[gate]", side, gate);    if (!gate.trade || !CONFIG.live || !wallet) return { side, gate, sent: false };     if (quote.issues.allowance) {        // One-time approval of the 0x AllowanceHolder for this token, for this trade's amount.        const token = new ethers.Contract(sellToken, ERC20, wallet);        await (await token.approve(quote.issues.allowance.spender, sellAmount)).wait();    }    const tx = await wallet.sendTransaction({        to: quote.transaction.to,        data: quote.transaction.data,        value: BigInt(quote.transaction.value),    });    const receipt = await tx.wait();    return { side, gate, sent: true, txHash: tx.hash, status: receipt?.status };}

Sending quote.transaction unchanged matters: the minimum output is encoded in it, so if the price moves past your slippage cap the swap reverts instead of filling badly.

Run the agent

src/agent.ts wires the loop together. Every closed bar updates the model; only a fresh bar, after a full window, with |z| at or above Z_ENTRY, reaches the cost gate. It trades mean reversion: buy after an unusually sharp drop, sell after an unusually sharp rise. Each decision is appended to decisions.jsonl:

import { CONFIG } from "./config";import { ZScoreModel } from "./predict";import { startOhlcvStream } from "./stream";import { tryTrade } from "./trade";import { ethers } from "ethers";import { appendFileSync } from "node:fs"; const taker = CONFIG.privateKey ? new ethers.Wallet(CONFIG.privateKey).address : ethers.ZeroAddress;const model = new ZScoreModel(CONFIG.windowBars);const STALE_MS = 2 * 60_000; // two one-minute barslet lastBarAt = 0;let busy = false; console.log("[agent]", { pair: CONFIG.pairAddress, live: CONFIG.live, zEntry: CONFIG.zEntry, taker }); const stop = startOhlcvStream(async (bar) => {    lastBarAt = Date.now();    model.push(bar.close);    const z = model.z();    // Backfill bars warm the model up but are never traded on: act only on a bar that closed just now.    const fresh = Date.now() - (bar.time + 60_000) < STALE_MS;    const signal = { time: new Date(bar.time).toISOString(), close: bar.close, z: Number(z.toFixed(3)), fresh };    console.log("[bar]", signal);    if (!fresh || !model.ready() || busy || Math.abs(z) < CONFIG.zEntry) return;     // Mean reversion: buy after an unusually sharp drop, sell after an unusually sharp rise.    const side = z < 0 ? "buy" : "sell";    const edgeBps = Math.abs(z) * CONFIG.bpsPerSigma;    busy = true; // one decision at a time    try {        const result = await tryTrade(side, edgeBps, taker);        appendFileSync("decisions.jsonl", JSON.stringify({ ...signal, edgeBps, ...result }) + "\n");    } catch (err) {        console.error("[trade] skipped:", (err as Error).message);    } finally {        busy = false;    }}); // Staleness guard: if no bar has closed for two intervals, say so. The agent only acts on a fresh bar.setInterval(() => {    if (lastBarAt && Date.now() - lastBarAt > STALE_MS) console.warn("[stream] stale: no new bar for 2 minutes");}, 15_000); process.on("SIGINT", () => {    stop();    process.exit(0);});

Run it in dry-run mode:

npx tsx --env-file=.env src/agent.ts

You'll see [stream] connected, then a [bar] line per minute (the backfill bars arrive at once with fresh: false). When |z| crosses the threshold, a [gate] line prints the edge and each cost in basis points, and whether it would trade. Let it run for a few hours and read decisions.jsonl before you set LIVE=true.

Backfill realized PnL with GoldRush

The gate decides on expected numbers. The backfill checks them against what happened onchain. It pulls the agent wallet's Base history from the GoldRush Transactions API (credit cost: 0.1 per item), reads the decoded Transfer events of USDC and WETH in each transaction, and rolls them up into realized PnL per trade with the average-cost method, net of the gas each transaction paid (gas_quote, in USD). Save this as src/pnl.ts:

import { CONFIG, USDC, WETH } from "./config";import { GoldRushClient, type Transaction } from "@covalenthq/client-sdk";import { ethers } from "ethers"; export type TradeRow = {    time: string;    txHash: string;    side: "buy" | "sell";    usdc: number;    weth: number;    gasUsd: number;    realizedUsd: number;}; // Net change in one token for the wallet in one transaction, from the decoded Transfer events.function tokenDelta(tx: Transaction, token: string, wallet: string): bigint {    let delta = 0n;    for (const log of tx.log_events ?? []) {        if (log.sender_address?.toLowerCase() !== token.toLowerCase() || log.decoded?.name !== "Transfer") continue;        const param = (name: string) => log.decoded?.params.find((p) => p.name === name)?.value ?? "";        const value = BigInt(param("value") || "0");        if (param("from").toLowerCase() === wallet) delta -= value;        if (param("to").toLowerCase() === wallet) delta += value;    }    return delta;} // Realized PnL per trade, average-cost method, oldest transaction first. Gas comes from each transaction's gas_quote (USD).export function realizedPnl(txs: Transaction[], walletAddress: string) {    const wallet = walletAddress.toLowerCase();    let held = 0; // WETH held by the agent    let cost = 0; // USDC paid for it    const rows: TradeRow[] = [];    for (const tx of txs) {        if (!tx.successful || !tx.tx_hash) continue;        const usdc = Number(ethers.formatUnits(tokenDelta(tx, USDC, wallet), 6));        const weth = Number(ethers.formatUnits(tokenDelta(tx, WETH, wallet), 18));        if (usdc === 0 || weth === 0 || Math.sign(usdc) === Math.sign(weth)) continue; // not a USDC/WETH swap        const gasUsd = tx.gas_quote ?? 0;        const time = tx.block_signed_at ? new Date(tx.block_signed_at).toISOString() : "";        if (weth > 0) {            held += weth;            cost += -usdc;            rows.push({ time, txHash: tx.tx_hash, side: "buy", usdc, weth, gasUsd, realizedUsd: -gasUsd });        } else {            const sold = Math.min(-weth, held);            const basis = held > 0 ? (cost * sold) / held : 0;            held -= sold;            cost -= basis;            rows.push({                time,                txHash: tx.tx_hash,                side: "sell",                usdc,                weth,                gasUsd,                realizedUsd: usdc - basis - gasUsd,            });        }    }    const total = rows.reduce((sum, r) => sum + r.realizedUsd, 0);    return { rows, totalRealizedUsd: total, openWeth: held, openCostUsdc: cost };} // Pull the agent wallet's Base history from the GoldRush Transactions API, oldest first, with decoded logs.export async function backfill(walletAddress: string) {    const client = new GoldRushClient(CONFIG.goldrushApiKey);    const txs: Transaction[] = [];    for await (const page of client.TransactionService.getAllTransactionsForAddress("base-mainnet", walletAddress, {        quoteCurrency: "USD",        blockSignedAtAsc: true,    })) {        if (page.error) throw new Error(page.error_message ?? "GoldRush request failed");        txs.push(...(page.data?.items ?? []));    }    return realizedPnl(txs, walletAddress);}

And a small report, src/pnl-report.ts:

import { CONFIG } from "./config";import { backfill } from "./pnl";import { ethers } from "ethers"; const wallet = new ethers.Wallet(CONFIG.privateKey).address;const { rows, totalRealizedUsd, openWeth, openCostUsdc } = await backfill(wallet);console.table(rows);console.log({ totalRealizedUsd, openWeth, openCostUsdc });
npx tsx --env-file=.env src/pnl-report.ts

Buys show only their gas as realized PnL; each sell shows proceeds minus the average cost of the WETH sold, minus gas. Anything still held is reported as openWeth at its cost; to mark it to market, value it with a price from the token price API, as in the guide to calculating unrealized profit and loss.

Then recalibrate. Join the report to decisions.jsonl by transaction hash and compare the edge the agent expected with what each round trip realized:

  • If realized returns are consistently below the expected edge, lower BPS_PER_SIGMA (or raise Z_ENTRY).
  • If fills keep landing near the slippage limit, lower SLIPPAGE_BPS or trade smaller.
  • If gas is a large share of each trade, raise TRADE_USDC or trade less often.

Troubleshooting

  • Connected but no bars. PAIR_ADDRESS is probably a token address. Use the pool's address.
  • [stream] stale warnings. No bar has closed for two minutes. The agent won't trade on a bar that isn't fresh; check your network, as some proxies block WebSockets.
  • z stays at 0. The model needs a full window of returns (60 by default) before it scores anything.
  • 0x quote failed: 401. Check ZEROX_API_KEY. A no route error means there's no liquidity for that size: trade smaller.
  • Every decision is a skip. The gate is working. Costs exceed the edge at this size and threshold; look at which cost dominates in the [gate] line.

Frequently asked questions

What is an AI trading agent on Base?

A program that watches Base market data, decides with a policy, and trades from its own wallet within limits you set. In this guide the policy is a rolling z-score on one-minute OHLCV candles from the GoldRush Streaming API, and every trade must pass a cost gate before it is sent.

Is a z-score rule really an "AI" agent?

It is the decision core of one. Agents need decisions that are reproducible and auditable, and a statistical rule gives you that. You can add an LLM planner for multi-step tasks, for example through the GoldRush MCP Server, as long as it emits the same decision shape and still goes through the cost gate.

How does the agent decide whether a trade is worth it?

It converts every cost to basis points of the trade size (the L2 and L1 network fee, the pool's fee tier, the worst-case slippage from a firm quote, and a safety margin) and trades only when the expected edge from the z-score is larger than their sum.

How do I measure the agent's profit and loss?

Backfill its wallet with the GoldRush Transactions API, which returns each transaction with decoded log events and its gas cost in USD. Sum the USDC and WETH transfer legs per transaction and apply average cost to get realized PnL per trade, then compare it with the edge the agent expected.

Does it send transactions while I test it?

No. LIVE defaults to false, so the agent streams, scores, quotes and prints each cost-gate decision without sending anything. Set LIVE=true only after you've read the dry-run log.

Can I stream Base data with GoldRush today?

The GoldRush SDK lists Base for the OHLCV Pairs stream, and Hyperliquid streaming is live today. The Streaming API's multi-chain reference returns in January 2027; ask GoldRush support to confirm Base streaming for your key.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.