Insights

Build an XRPL Trading App: Developer Tutorial

A step-by-step guide to building trading applications on the XRP Ledger using the XRPL.to API for data, WebSocket for real-time updates, and rippled for transaction submission.

What You Can Build

The XRP Ledger's open DEX and native token support make it ideal for building trading applications. With the XRPL.to API handling data aggregation, you can focus on your application logic instead of building infrastructure. Common projects include:

Portfolio trackers
Trading bots
Price alert apps
Analytics dashboards
DEX aggregators
NFT tools

Architecture

A typical XRPL trading app uses three layers:

Your App
XRPL.to REST API (data)
XRPL.to WebSocket (real-time)
rippled (transactions)

XRPL.to handles the heavy lifting of data aggregation, price calculations, and market analytics. Your app reads processed data via REST and WebSocket, then submits transactions directly to the XRP Ledger through rippled or xrpl.js.

Step 1: Fetch Token Data

Start by listing available tokens with prices, volume, and market cap:

// Top tokens by 24-hour volume
const res = await fetch('https://api.xrpl.to/v1/tokens?sortBy=vol24hxrp&sortType=desc&limit=20');
const { tokens } = await res.json();

for (const t of tokens) {
  // exch: price in XRP, usd: price in US dollars, vol24hxrp: XRP traded in 24 hours
  console.log(t.name, t.exch, t.usd, t.vol24hxrp);
}

Step 2: Get Live Prices

Connect to the WebSocket stream for real-time price updates without polling:

const ws = new WebSocket('wss://api.xrpl.to/ws/sync/');

ws.onopen = () => {
  ws.send(JSON.stringify({ type: 'subscribe', tokens: ['token_md5'], lightweight: true }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.snapshot || msg.seq) updatePriceDisplay(msg.tokens); // tokens[] may be empty on quiet updates
};

Step 3: Display Charts

Fetch OHLC (candlestick) data for any token to render price charts:

// 1-hour candles for the last day
curl "https://api.xrpl.to/v1/ohlc/{md5}?range=1D&interval=1h"

The response’s ohlc array holds one row per candle: [time in milliseconds, open, high, low, close, volume in XRP] (candle API guide).

Step 4: Execute Trades

Ask the quote endpoint for the best route, build the Payment from it, sign it with xrpl.js, and submit it (swap API guide, tested end to end):

const { Wallet, Client, PaymentFlags, xrpToDrops } = require('xrpl');
const seed = process.env.SEED;  // never in the code
const wallet = Wallet.fromSeed(seed, { algorithm: seed.startsWith('sEd') ? 'ed25519' : 'ecdsa-secp256k1' });

// 1. Quote: spend 10 XRP on RLUSD (tokens are given by md5)
const { quote } = await fetch('https://api.xrpl.to/v1/dex/quote', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    source_account: wallet.address,
    source_token: '84e5efeb89c4eae8f68188982dc290d8',      // XRP
    source_value: '10',
    destination_token: '0dd550278b74cb6690fdae351e8e0df3', // RLUSD
  }),
}).then((r) => r.json());

// 2. A Payment to yourself, capped by the quote (the swap API guide explains each field)
const isXrp = (a) => typeof a === 'string' || a.currency === 'XRP';
const valueOf = (a) => (typeof a === 'string' ? Number(a) / 1e6 : Number(a.value));
const amount = (a, v) => (isXrp(a) ? xrpToDrops(v.toFixed(6)) : { currency: a.currency, issuer: a.issuer, value: v.toPrecision(15) });
const give = quote.source_amount, get = quote.destination_amount, out = valueOf(get);
const payment = {
  TransactionType: 'Payment', Account: wallet.address, Destination: wallet.address,
  SendMax: amount(give, valueOf(give)),
  Amount: amount(get, out * 2),
  DeliverMin: amount(get, out * (1 - quote.suggested_slippage / 100)),
  Flags: PaymentFlags.tfPartialPayment,
  ...(quote.paths?.length ? { Paths: quote.paths } : {}),
};

// 3. Sign locally, then submit through the API
const client = new Client('wss://xrplcluster.com');
await client.connect();
const signed = wallet.sign(await client.autofill(payment));
await fetch('https://api.xrpl.to/v1/submit', {
  method: 'POST', headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ tx_blob: signed.tx_blob }),
});

Step 5: Track Portfolio

Combine balance, trustline, and LP position endpoints for a complete portfolio view:

const account = 'rYourAddress...';

// Parallel requests for full portfolio data
const [balance, trustlines, lpPositions] = await Promise.all([
  fetch(`https://api.xrpl.to/v1/account/balance/${account}`).then(r => r.json()),
  fetch(`https://api.xrpl.to/v1/trustlines/${account}`).then(r => r.json()),
  fetch(`https://api.xrpl.to/v1/lp-positions/${account}`).then(r => r.json()),
]);

console.log('XRP spendable:', balance.balance);
console.log('Token lines:', trustlines.total, 'worth', trustlines.totalValue);
console.log('LP positions:', Object.keys(lpPositions.positions || {}).length);

Example Projects

Price Ticker Widget

Embeddable widget showing live XRPL token prices on any website.

Whale Alert Bot

Monitor large trades and wallet movements, send notifications via Telegram or Discord.

Portfolio Rebalancer

Track token allocations and suggest rebalancing trades based on target weights.

Arbitrage Scanner

Compare prices across AMM pools and DEX orderbooks to find profitable spreads.

Start Building

Everything you need to build on the XRP Ledger is available for free. Explore the documentation and related guides: