Developers
How to build an autonomous trading bot with XAUConnect
End-to-end Node.js pattern: quote polling, route selection, viem signing, and swap recording.
All posts
8 min read
This guide walks through a minimal server-side bot that swaps on BNB Chain using the XAUConnect API and viem. The same pattern applies to other EVM chains — change chainKey and RPC.
1. Configure the SDK client
import { XauApiClient } from "@xauconnect/sdk";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { bsc } from "viem/chains";
const api = new XauApiClient({
baseUrl: "https://xauconnect.com/api",
clientId: "treasury-rebalancer",
clientName: "Treasury Rebalancer",
clientSource: "agent",
});
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const wallet = createWalletClient({ account, chain: bsc, transport: http() });2. Quote and pick the best executable route
const quote = await api.quote({
chainKey: "bsc",
tokenIn: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", // WBNB
tokenOut: "0x55d398326f99059fF775485246999027B3197955", // USDT
amountIn: "1000000000000000000",
slippageBps: 50,
taker: account.address,
});
const route = quote.best ?? quote.quotes.find((q) => q.executable);
if (!route) throw new Error("No executable route");3. Build, approve if needed, sign, and record
Call GET /swap/allowance before swapping ERC-20 tokens. After the transaction confirms, always POST /swap/record with source: agent so volume shows in admin.
const built = await api.buildSwap({
request: { chainKey: "bsc", tokenIn, tokenOut, amountIn, slippageBps: 50, taker: account.address },
route,
minAmountOut: quote.minAmountOut!,
});
const hash = await wallet.sendTransaction({
to: built.evm!.to as `0x${string}`,
data: built.evm!.data as `0x${string}`,
value: BigInt(built.evm!.value),
});
await api.recordSwap({
chainKey: "bsc",
dexId: route.dexId,
tokenIn, tokenOut,
amountIn, amountOut: route.amountOutAfterFee,
protocolFee: route.protocolFee,
feeBps: quote.protocolFeeBps,
txHash: hash,
address: account.address,
status: "confirmed",
source: "agent",
});Ready to integrate?
Follow the quickstart or explore the OpenAPI reference.