How to Build a Simple Solana Trading Bot: Beginner's Guide (2026)
Step-by-step guide to building a basic Solana trading bot using the Jupiter API and Helius webhooks. Covers setup, swap execution, event monitoring, and common pitfalls for beginners.

Disclosure: This article contains affiliate links. If you sign up through them, MadeOnSol may earn a commission at no extra cost to you. This never affects our rankings, ratings, or reviews.
A small trading bot has three jobs: observe a market, decide whether a condition is met, and submit a transaction. Keeping those jobs separate makes failures easier to understand. This tutorial uses TypeScript, Jupiter's current Swap v2 API, and optional Helius event notifications.
Start with a read-only monitor. Jupiter's public swap flow uses Solana mainnet liquidity; it is not a devnet swap simulator. Use mocks for Jupiter responses and devnet/localnet for your own program tests. Only test actual swaps with an explicitly funded mainnet development wallet.
Project setup
Use a maintained Node.js LTS release and install:
mkdir solana-bot
cd solana-bot
npm init -y
npm install @solana/web3.js@1 bs58 dotenv
npm install --save-dev typescript @types/node tsx
Create .env and add it to .gitignore:
JUPITER_API_KEY=your_api_key
TARGET_MINT=token_mint_to_observe
TAKER_ADDRESS=your_public_wallet_address
# PRIVATE_KEY is only needed by a separate, explicitly enabled execution step.
Get the API key from Jupiter Portal. A configured RPC from Helius, QuickNode, or Triton is useful for independent transaction inspection. This example lets Jupiter manage swap submission rather than maintaining its own RPC resend loop.
Read prices without inventing a zero
The Jupiter Price API is a market-data endpoint, not an executable quote. A missing price must not become a zero-dollar buy signal.
// src/price.ts
import "dotenv/config";
export async function getTokenPrice(mint: string): Promise<number> {
const key = process.env.JUPITER_API_KEY;
if (!key) throw new Error("Set JUPITER_API_KEY");
const url = new URL("https://api.jup.ag/price/v3");
url.searchParams.set("ids", mint);
const response = await fetch(url, {
headers: { "x-api-key": key },
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) throw new Error("Price HTTP " + response.status);
const body = await response.json() as Record<string, { usdPrice?: unknown }>;
const price = body[mint]?.usdPrice;
if (typeof price !== "number" || !Number.isFinite(price) || price <= 0) {
throw new Error("No usable price for this mint");
}
return price;
}
Keep the source's observation time when your strategy needs age checks. A successful request is not proof of liquidity or a guarantee that a trade can fill at the displayed price.
Request an order with Swap v2
The Swap API now uses /swap/v2. Its assembled-transaction flow is GET /order followed by POST /execute. The older Metis /swap/v1 documentation is marked superseded; new code should not copy the former keyless lite-api setup.
This module requests an order and exposes a separate execution function:
// src/swap.ts
import "dotenv/config";
import { Keypair, VersionedTransaction } from "@solana/web3.js";
const base = "https://api.jup.ag/swap/v2";
export interface Order {
requestId: string;
transaction: string | null;
inputMint: string;
outputMint: string;
inAmount: string;
outAmount: string;
slippageBps?: number;
errorCode?: number;
errorMessage?: string;
}
function headers() {
const key = process.env.JUPITER_API_KEY;
if (!key) throw new Error("Set JUPITER_API_KEY");
return { "x-api-key": key, "Content-Type": "application/json" };
}
export async function getOrder(
inputMint: string, outputMint: string, amount: string, taker: string,
): Promise<Order> {
if (!/^[1-9][0-9]*$/.test(amount)) throw new Error("Use positive base units");
const url = new URL(base + "/order");
url.search = new URLSearchParams({
inputMint, outputMint, amount, taker,
maxSupportedTransactionVersion: "0",
}).toString();
const response = await fetch(url, {
headers: headers(), signal: AbortSignal.timeout(10_000),
});
if (!response.ok) throw new Error("Order HTTP " + response.status);
const order = await response.json() as Order;
if (!order.requestId || !order.transaction || order.errorCode != null) {
throw new Error(order.errorMessage || "No executable order");
}
if (order.inputMint !== inputMint || order.outputMint !== outputMint
|| order.inAmount !== amount) {
throw new Error("Order differs from requested swap");
}
return order;
}
export async function executeApprovedOrder(order: Order, signer: Keypair) {
if (!order.transaction) throw new Error("Order has no transaction");
const tx = VersionedTransaction.deserialize(
Buffer.from(order.transaction, "base64"),
);
tx.sign([signer]);
const response = await fetch(base + "/execute", {
method: "POST",
headers: headers(),
signal: AbortSignal.timeout(30_000),
body: JSON.stringify({
requestId: order.requestId,
signedTransaction: Buffer.from(tx.serialize()).toString("base64"),
}),
});
if (!response.ok) {
throw new Error("Execute outcome needs reconciliation: HTTP " + response.status);
}
const result = await response.json() as {
status?: string; signature?: string; code?: number;
};
if (result.status !== "Success" || !result.signature) {
throw new Error("Swap not confirmed successful: " + JSON.stringify(result));
}
return result.signature;
}
The code requests transaction version 0 to match web3.js v1. The order's amount is an integer string in the input token's base units: lamports only when the input is SOL. Read the returned fees, expected output, slippage, and transaction instructions before approving an order. The illustrated field checks are not a full transaction-policy validator.
Jupiter handles landing in the /execute flow. Do not overwrite its blockhash or change the returned message. See the order/execute contract for current optional parameters and fee accounting.
Building a product on Solana or Robinhood Chain data?
Skip the Geyser pipeline — embed KOL flow, deployer reputation, and the all-DEX firehose over REST, WebSocket, or webhooks. The Business tier (€400/mo) is the self-serve embed license at 500k calls/day — Enterprise adds white-label & redistribution.
Run a monitor that cannot place an order
// src/bot.ts
import "dotenv/config";
import { getTokenPrice } from "./price";
const mint = process.env.TARGET_MINT;
if (!mint) throw new Error("Set TARGET_MINT");
const observedMint: string = mint;
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function main() {
while (true) {
try {
const price = await getTokenPrice(observedMint);
console.log(new Date().toISOString(), observedMint, price);
// Record an observation. This loop has no signing or execution call.
} catch (error) {
console.error("Observation unavailable:", error);
}
await sleep(10_000);
}
}
main().catch(console.error);
Run npx tsx src/bot.ts. Each observation finishes before the next begins, so a slow request cannot create overlapping timer callbacks.
To add execution, make it a separate state machine: idle → order reviewed → submission pending → confirmed/failed/unknown. Persist the pending order before submitting. A timeout after signing or submission is an unknown outcome, not permission to buy again. Reconcile the request/signature before creating a replacement order. An in-memory hasBought flag set only after confirmation cannot prevent duplicate buys across overlapping requests or process restarts.
Keep a durable position record, an input-amount ceiling, a fee budget, and explicit enablement for live trading. Test these controls with recorded responses before connecting a signer. Never log a private key or place one in a browser-facing application.
Add Helius webhooks as observations
Helius webhooks can notify your backend of supported address activity. They are transaction events, not a replacement for every price query. Enhanced payloads are arrays of transactions; swap details can be nested under events.swap, so do not assume tokenInputs and tokenOutputs live at the transaction root.
Configure the webhook's authentication header, validate it at your HTTPS receiver, and validate the body before accepting work. Deduplicate by transaction identity, durably enqueue the event, then acknowledge promptly. Treat retries and out-of-order delivery as normal cases. A webhook should feed the observation/state machine rather than call the signing function directly.
For MadeOnSol-specific signals, see the webhook integration guide. Each provider has its own payload and authentication contract.
Test failures before trading
A useful test set includes: price missing, HTTP 429, malformed response, no available route, stale order, signer mismatch, execution failure, and a timeout after submission. Assert that every unknown outcome pauses further execution for that order.
Do not assume an RPC acknowledgement means a swap succeeded. Do not rebuild a signed transaction's blockhash without obtaining a valid new order. Slippage is a limit on execution price, not a profit target; increasing it or paying a larger priority fee does not guarantee success or MEV protection. See Solana slippage explained for how the tolerance is applied.
For custom execution, Jito bundles offer a different submission mechanism with its own constraints. Atomic bundle execution is not a blanket promise that trades cannot be sandwiched or that all submission paths are private.
Where to go next
For application development, Solana Playground and Anchor help with your own programs. For richer inputs, evaluate Birdeye, DEXScreener, and the MadeOnSol trading-bot data layer against the markets you need to cover. The Jito tool page and the Solana Cookbook are useful references, and How to Build on Solana covers broader Solana development.
Solana Agent Kit can add agent tooling, but a model's recommendation should still pass the same execution controls. Tax treatment depends on your jurisdiction; retain transaction records and consult the tax guide as a starting point for that separate question.
Plans and limits for the MadeOnSol API are on the pricing page.
Sources: Jupiter Swap v2, order and execute, legacy v1 status, and Helius webhooks.
Tools mentioned
Compare features and read reviews.
Live health scores, average ratings, and direct links on MadeOnSol.
Build your own trading bot
KOL copy-trading, deployer sniping, and DEX trade streaming — all via API.
import { MadeOnSol } from "madeonsol";
const client = new MadeOnSol({ apiKey: "msk_your_key" });
// Mirror KOL trades in real-time
const { trades } = await client.kol.feed({ action: "buy" });
// Set up webhooks for instant alerts
const webhook = await client.webhooks.create({
url: "https://your-bot.com/hook",
events: ["kol:trade", "deployer:alert"],
});Building a product on Solana or Robinhood Chain data?
MadeOnSol isn't an RPC or another generic token API — it's Solana & Robinhood Chain memecoin intelligence that's painful to build in-house, pulled from dual-region gRPC shred streams and our own Robinhood Chain node, pushed to your app as events land.
Signals you'd otherwise build
KOL & smart-money flow from 2,000+ labeled wallets, deployer reputation, coordination clusters, linked-wallet entity resolution, and an all-DEX firehose.
Embed it in your product
The Business tier (€400/mo, self-serve) licenses you to display MadeOnSol data inside your own product — 500k calls/day, 15 WS + 6 firehose connections. Enterprise above adds white-label & redistribution rights and custom endpoints.
Evaluate first, commit later
Test everything on a free ULTRA key — no commitment. If it fits, we scope volume or white-label pricing.
Keep reading
More from the blog.

Developer Tools
Copy-Trade Solana KOL Wallets: Build a Paper-Trading Bot in 5 Minutes
Watch live smart-money trades on Solana and paper-trade them in real time: open a virtual position when a tracked KOL buys, close when they sell, and track PnL from the market-cap multiple. This tutorial walks the open-source kol-copytrade-bot-starter — ~300 lines, one dependency, free API key — and shows how to filter by KOL win rate, deployer tier, and multi-KOL confirmation before risking anything real.

API Guides
DexScreener API Alternative: 5 Things It Can't Do (That MadeOnSol Can)
DexScreener's free API is a current-state read layer: a focused public endpoint set, no historical data, and no WebSocket. If you've hit those walls, here's what the MadeOnSol API gives you instead, and what each plan lets you build.

API Guides
Solana Deployer API: Track 900K+ Token Creators by Bonding Rate
The MadeOnSol Deployer Hunter API gives you programmatic access to 1.1M+ indexed Pump.fun token deployers (85K+ reputation-scored) by historical bonding rate, tier, and trajectory — plus real-time alerts when elite deployers launch. Here's the full endpoint surface.

Developer Tools
What Is a Solana API? A Developer's Guide to Building on Solana Data (2026)
Understand what Solana APIs are, what types exist, and how developers use them to build trading bots, portfolio trackers, and analytics dashboards. Covers RPC, enhanced APIs, data APIs, and when to use each.

Developer Tools
Find Tokens Before They Moon: Scout Leaderboard, KOL Consensus, and Peak History (2026)
How to chain three MadeOnSol API endpoints into a token discovery pipeline. Scout leaderboard surfaces early-mover KOLs, consensus confirms conviction, and peak history reveals lifecycle stage — with full TypeScript code for the complete workflow.

Developer Tools
How to Build Real-Time Solana Dip-Buying Price Alerts
Step-by-step guide to building an automated dip-buying bot for Solana memecoins. Uses MadeOnSol's price alert API for detection on a 250 ms tick, webhook delivery, and recovery tracking — with full TypeScript code examples.
Enjoyed this article?
Explore the live data.
Real-time KOL trades, Pump.fun deployer intel, and 1,200+ ranked Solana & Robinhood Chain tools — free to explore.
Open the KOL Tracker

