sifting/io
Developer Tutorials
13 min readSiftingIO Team

What Is x402? A Market Data API Guide with Working Examples

Learn how x402 payments work and request SiftingIO market data without an API key. Includes JavaScript examples, historical candles, pricing and spending limits.

What Is x402? A Market Data API Guide with Working Examples

x402 lets software pay for an API response as part of an ordinary web request. The server states the price, the client authorises a payment, and the server returns the requested data.

With the SiftingIO x402 market data API, that means getting Forex prices, cryptocurrency data, commodity prices, US stock data and historical candles without creating a SiftingIO account or managing an API key. Requests start at $0.002 USDC.

This guide starts with a free request you can run immediately. It then walks through HTTP 402, a complete payment-aware JavaScript client, historical OHLCV data and a practical spending budget.

What is x402?#

x402 is an open protocol for paying for online resources over HTTP. It gives the HTTP status code 402 Payment Required a practical role: telling an application what it needs to pay to receive a response.

Think of a small research script that needs one current currency price. It asks for the price. The API replies with the cost and payment details. The script checks those terms, signs a payment authorisation and repeats the request with proof of authorisation attached.

The same approach works for an AI agent fetching a price, a scheduled report collecting historical candles or a developer exploring a dataset.

The protocol is separate from the asset used to pay. SiftingIO currently accepts USDC on Base mainnet, identified in the protocol as eip155:8453, using x402 version 2.

How does an x402 API request work?#

There are five steps:

  1. Your application requests a SiftingIO endpoint.
  2. The server returns HTTP 402 and a PAYMENT-REQUIRED header containing the payment terms.
  3. Your client checks the network, token and amount, then signs an authorisation with its wallet.
  4. The client repeats the request with a PAYMENT-SIGNATURE header.
  5. The server verifies the authorisation, obtains the data and settles payment for a successful response. A PAYMENT-RESPONSE header carries the settlement receipt.

A payment-aware client handles the second request automatically. You do not need to construct the payment headers by hand.

The payment facilitator is the service that verifies and settles the authorisation. For SiftingIO's current payment flow, the buyer signs the authorisation and the facilitator pays the settlement gas fee. Funding the wallet is a separate step.

The official x402 buyer guide explains the client protocol in more detail.

What market data is available through SiftingIO x402?#

The live catalog contains 41 REST endpoint definitions as of 27 November 2026. These are API operations, not a count of supported instruments.

Data categoryWhat you can requestExample use
Current prices and quotesLatest trade and bid and ask data for Forex, crypto, commodities and US stocksRetrieve a price for a dashboard or analysis
Historical candlesOpen, high, low, close and volume fields at supported intervalsBuild a chart or calculate an indicator
Previous close and end-of-day dataThe relevant completed close or daily barPrepare a daily market report
Technical signalsCurrent signals and signal historyAdd indicator readings to a research workflow
Market summariesSnapshots, movers and most-active instrumentsIdentify instruments to examine
Company dataProfiles, ratios, financial statements, filings, earnings, insider activity, ownership and institutional holdingsAdd business context to stock research
Market schedulesMarket status, trading hours and holiday calendarsRun a job at an appropriate time
Economic eventsUS economic calendar dataPlace a price move alongside an event
Instrument lookup and conversionSymbol catalogs, instrument details and currency conversionResolve a symbol or convert an amount

For commodities, the range includes metals, energy and agricultural instruments. Gold uses XAUUSD, silver uses XAGUSD, and WTI oil uses WTIUSD. Use the symbol lookup routes to confirm the instrument you need before building a request.

The live endpoint catalog lists every operation and its current price. The OpenAPI specification provides the exact paths, parameters and response schemas. For an explanation of how SiftingIO builds its data, read our data methodology.

How much does an x402 market data request cost?#

SiftingIO currently has four per-request prices:

Price in USDCTypical operations
$0.002Latest trade, quote, symbol lookup, conversion and market schedules
$0.005Previous close, end-of-day bar, current signals, movers, company profiles and filings, economic events
$0.01A page of historical candles or signal history
$0.02Market snapshots, full financial statements, financial concept series, screening and risk-factor comparisons

For example, 1,000 successful latest-trade requests cost $2 at the listed rate. One hundred historical requests cost $1. Historical pricing is per response page, with up to 5,000 rows per page where the endpoint supports that limit.

There is no monthly subscription or minimum commitment for this access method. Check the current catalog when setting a budget; the payment terms returned by the endpoint identify the amount for the request.

Step 1: make a free request without a wallet#

Start with a sample response. It requires no payment, account or API key:

curl -sS https://x402.sifting.io/samples/getLastTrade

The response contains an operation name, a note, the paid endpoint URL, its price and a sample object. Here is the recorded sample returned when this guide was checked:

{
  "s": "USDTRY",
  "p": "50.77834",
  "P": "41498",
  "t": 1795773293420
}

This is a recorded sample, not a current market quote. It is useful for learning the response format before making a paid request.

The fields are compact: s is the symbol, p is the price, P is the size field and t is a Unix timestamp in milliseconds. The price is returned as a string.

To read the sample in JavaScript, save this as free-sample.mjs:

const response = await fetch('https://x402.sifting.io/samples/getLastTrade');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const result = await response.json();
console.log(result.note);
console.log({
  symbol: result.sample.s,
  price: result.sample.p,
  timeUTC: new Date(result.sample.t).toISOString(),
});

Run it with Node.js 22 or later:

node free-sample.mjs

The script prints the sample note, symbol, price and a readable UTC timestamp. It makes no payment.

Step 2: inspect the payment request#

Now call the paid endpoint without a wallet signature:

curl -sS -i https://x402.sifting.io/v1/last/trade/forex/USDTRY

An HTTP 402 response is expected here. The server is telling you the payment terms. This unsigned request does not make a payment.

The PAYMENT-REQUIRED header contains an encoded JSON object. In the decoded payment terms for this endpoint, the relevant fields are:

{
  "scheme": "exact",
  "network": "eip155:8453",
  "amount": "2000",
  "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
}

USDC has six decimal places. An amount of 2000 therefore means 0.002 USDC. The full terms also identify the payment recipient and the requested resource.

The payment-aware client below reads these terms, checks them against the allowed amount and handles signing.

Step 3: prepare a wallet and install the client#

For a paid request, you need Node.js 22 or later and a wallet funded with USDC on Base mainnet. A balance on another network will not pay this endpoint.

Use a dedicated wallet with a small balance for development. The private key belongs in your backend or local script environment, never in public frontend code.

Create a folder and install the package versions used for this example:

mkdir siftingio-x402-example
cd siftingio-x402-example
npm init -y
npm install @x402/fetch@2.30.0 @x402/core@2.30.0 @x402/evm@2.30.0 viem@2.57.18

Create a .env file and enter the private key for that dedicated wallet:

X402_WALLET_PRIVATE_KEY=0xYOUR_PRIVATE_KEY

The value shown is a placeholder. Replace it locally with your wallet's private key. Add .env to .gitignore so it is not committed to your repository.

Step 4: make a paid request with JavaScript#

Save the following complete example as x402-market-data.mjs. It supports two commands: quote for a latest price and history for a page of hourly candles.

The code restricts payment to the selected SiftingIO URL, USDC on Base and the listed price for that operation. Each run requests one paid response page.

import { pathToFileURL } from 'node:url';
import { wrapFetchWithPaymentFromConfig } from '@x402/fetch';
import { decodePaymentResponseHeader } from '@x402/core/http';
import { ExactEvmScheme } from '@x402/evm';
import { privateKeyToAccount } from 'viem/accounts';

const BASE_USDC = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
const ORIGIN = 'https://x402.sifting.io';

export const examples = {
  quote: {
    path: '/v1/last/trade/forex/USDTRY',
    price: '$0.002',
    maxUnits: 2000n,
  },
  history: {
    path: '/v1/hist/crypto/BTCUSD/bars?start=2026-11-01&end=2026-11-02&interval=1h&limit=24',
    price: '$0.01',
    maxUnits: 10000n,
  },
};

export function createPaidFetch(privateKey, example, transport = fetch) {
  const signer = privateKeyToAccount(privateKey);
  const checkedFetch = (input, init) => {
    const url = new URL(input instanceof Request ? input.url : String(input));
    if (url.href !== ORIGIN + example.path) {
      throw new Error('This example only permits its selected SiftingIO URL.');
    }
    return transport(input, { ...init, redirect: 'error' });
  };

  return wrapFetchWithPaymentFromConfig(checkedFetch, {
    schemes: [{ network: 'eip155:8453', client: new ExactEvmScheme(signer) }],
    spendControls: { maxAmountPerPayment: example.price },
    policies: [(_version, offers) => offers.filter((offer) =>
      offer.scheme === 'exact' &&
      offer.network === 'eip155:8453' &&
      offer.asset.toLowerCase() === BASE_USDC &&
      BigInt(offer.amount) <= example.maxUnits
    )],
  });
}

export async function main() {
  const mode = process.argv[2] ?? 'quote';
  const example = examples[mode];
  if (!example) throw new Error('Choose quote or history.');

  const privateKey = process.env.X402_WALLET_PRIVATE_KEY;
  if (!privateKey || !/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
    throw new Error('Set X402_WALLET_PRIVATE_KEY to a valid wallet private key.');
  }

  const paidFetch = createPaidFetch(privateKey, example);
  const response = await paidFetch(ORIGIN + example.path, {
    headers: { 'Accept-Encoding': 'gzip', Accept: 'application/json' },
  });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  }

  console.log(JSON.stringify(await response.json(), null, 2));
  const receipt = response.headers.get('PAYMENT-RESPONSE');
  if (receipt) {
    console.log('Payment receipt:', decodePaymentResponseHeader(receipt));
  }
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  main().catch((error) => {
    console.error(error.message);
    process.exitCode = 1;
  });
}

Run the latest-price example:

node --env-file=.env x402-market-data.mjs quote

With a funded wallet and a successful response, this command spends 0.002 USDC, prints the price response and prints the settlement receipt. The receipt includes the payment result and transaction reference.

The first unsigned request and the signed retry are parts of one purchase. You are not charged twice because the payment handshake uses two HTTP requests. Running the command again requests another paid response.

The response uses the same compact fields introduced in the free sample. Read t alongside p so your application knows the timestamp of the observation.

Step 5: request historical OHLCV candles#

Use the same file to request up to 24 hourly Bitcoin candles:

node --env-file=.env x402-market-data.mjs history

The historical URL in the example is:

https://x402.sifting.io/v1/hist/crypto/BTCUSD/bars?start=2026-11-01&end=2026-11-02&interval=1h&limit=24

This operation costs 0.01 USDC per successful page. Its parameters specify the time window, bar interval and maximum number of rows returned.

ParameterMeaning in this request
startInclusive start of the requested window
endInclusive end of the requested window
interval=1hOne-hour candles
limit=24Return at most 24 candles in this page
cursorContinue from a previous response when more rows are available

Because both window boundaries are inclusive, a midnight-to-midnight window can contain a candle at the next midnight. The limit controls the page size; it does not change the time window.

The supported intervals are 1m, 5m, 15m, 30m, 1h, 1d, 1w and 1mo. Use date strings or RFC3339 timestamps with an explicit timezone for the time boundaries.

Historical responses contain a data array and a meta object. This candle comes from the free historical sample:

{
  "t": 1793491200000,
  "o": 77531.80961301,
  "h": 77679.59165767,
  "l": 77487.62847069,
  "c": 77645.80716238,
  "v": 3349.7221405399996
}

t is the bar's opening timestamp in milliseconds. The remaining fields are open, high, low, close and volume. Check the relevant instrument documentation when interpreting volume because its meaning depends on the asset class.

For a chart, use t as the time coordinate and o, h, l and c as the candle values. For a close-price indicator, process the c values in time order. Our OHLCV guide explains the fields in more detail.

Historical endpoints require Accept-Encoding: gzip. The example includes that header, and the JavaScript runtime decompresses the response before response.json() reads it.

How to request the next page#

If meta.next_cursor is present and non-empty, make another request with the same window and interval, adding that value as the cursor parameter. Treat it as an opaque value and encode it with URLSearchParams.

Stop when no next cursor is returned, or when you reach your own page budget. Each page is another paid request. At the current historical price, a ten-page limit caps that job's data cost at $0.10.

The example intentionally reads one page. When you add pagination, update the permitted URL to match each requested page and keep a separate counter for the total number of pages.

Using x402 in an AI agent or research workflow#

An agent can discover the available operations from the machine-readable x402 guide and OpenAPI specification. Your application can then expose selected operations as tools.

For example, a research task might fetch one current price, one page of hourly candles and one economic calendar response. At the listed prices, those three successful requests cost $0.017.

Keep payment controls in the application. Give the agent a narrow tool such as getLatestPrice(symbol) while the backend validates the symbol, selects an approved endpoint and applies the spending limit. The model does not need the wallet's private key.

Use both a per-request limit and a total task budget. The example's payment cap limits each authorisation; it does not cap a long-running application's cumulative spending. Store the returned timestamps and receipts alongside the job results so you can trace which data the analysis used.

Common questions about SiftingIO x402#

Do I need a SiftingIO API key or subscription?#

No. Requests to the x402 gateway use wallet payment authorisation. The free sample endpoints need neither a wallet nor payment.

Can I get Forex, gold and cryptocurrency prices?#

Yes. The current-price route supports forex, commodities, crypto and stocks. Examples include /v1/last/trade/forex/USDTRY, /v1/last/trade/commodities/XAUUSD and /v1/last/trade/crypto/BTCUSD.

Does x402 provide a WebSocket stream?#

The current x402 catalog provides REST requests. For a persistent live stream, use the regular SiftingIO WebSocket service and its account-based access.

Are DEX endpoints included?#

The current x402 catalog covers the REST operations listed above. DEX routes are not currently part of that catalog. Check the live catalog for additions.

What happens if a request fails?#

SiftingIO does not settle payment for an API response with a 4xx or 5xx status. An initial 402 is the payment challenge. If a signed request is rejected, inspect its error before trying again. If a connection drops after sending a signed request, check the payment outcome before repeating a purchase.

Does payment determine the data's permitted use?#

x402 handles payment and access. Data usage remains governed by the applicable SiftingIO terms. If you are building a customer-facing product, contact SiftingIO to confirm the appropriate commercial arrangement.

When does a monthly plan make sense?#

x402 is useful for individual requests, occasional research jobs and tools that need a simple per-call budget. For ongoing applications and continuous streaming, review the regular SiftingIO plans around your expected usage.

Make your first request#

Run the free sample to learn the response format, choose an operation from the catalog, then use the payment-aware example with a funded wallet and an explicit budget.

Start with the SiftingIO x402 page, explore the live endpoint catalog, or open the API documentation for the dataset you want to use.

Keep reading

Related posts