In the fast-evolving world of decentralized finance (DeFi), speed is everything. On high-performance blockchains like Solana, new tokens can moon within seconds of launch. To capitalize on these opportunities, traders are turning to automation—specifically, Solana sniper bots that detect new token pools the moment they’re created and execute trades in milliseconds.
This guide walks you through building your own Solana sniper bot using Bitquery’s real-time Solana subscriptions for instant on-chain monitoring and the Jupiter Swap API for rapid token swaps. Whether you're a developer exploring DeFi automation or a trader looking to gain an edge, this tutorial delivers a functional, low-latency solution.
Prerequisites
Before diving into the code, ensure your development environment meets the following requirements:
- Node.js and npm installed (download from npmjs.com)
- A free Bitquery developer account with an OAuth token (generate one here)
- A Solana wallet with a small amount of SOL for transaction fees
These tools form the foundation of your bot’s execution and monitoring capabilities.
Step 1: Set Up Your Development Environment
Start by initializing a new Node.js project:
mkdir solana-sniper-bot
cd solana-sniper-bot
npm init -yNext, install the required dependencies:
npm install @solana/web3.js cross-fetch lodash @project-serum/anchor bs58These packages provide essential functionality:
@solana/web3.js: Interact with the Solana blockchaincross-fetch: Make HTTP requests in Node.jslodash: Utility functions for data handling@project-serum/anchor: Wallet integrationbs58: Base58 encoding for Solana keys
👉 Discover how real-time blockchain data can power your next trading strategy.
Step 2: Build the Sniper Bot
Initialize the Project File
Create a file named index.js and begin by importing the required modules:
const {
Connection,
PublicKey,
VersionedTransaction,
Keypair,
} = require("@solana/web3.js");
const fetch = require("cross-fetch");
const lodash = require("lodash");
const { Wallet } = require("@project-serum/anchor");
const bs58 = require("bs58");Define the GraphQL Query for Real-Time Monitoring
To detect new token pools instantly, use Bitquery’s subscription system. The following GraphQL subscription listens for initializeUserWithNonce instructions from Raydium, a leading Solana DEX:
const gql = (strings, ...values) =>
strings.reduce((final, str, i) => final + str + (values[i] || ""), "");
const subscriptionQuery = gql`
subscription {
Solana {
Instructions(
where: {
Transaction: { Result: { Success: true } }
Instruction: {
Program: {
Method: { is: "initializeUserWithNonce" }
Address: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" }
}
}
}
) {
Instruction {
Accounts {
Address
}
}
}
}
}
`;This real-time feed ensures your bot reacts the moment a new liquidity pool is created—critical for sniping newly launched tokens.
Configure Solana Connection and Wallet
Set up your connection to the Solana mainnet and authenticate your wallet:
const connection = new Connection("https://api.mainnet-beta.solana.com");
const walletPublicKey = new PublicKey("YOUR_PUBLIC_KEY");
const secretKeyUint8Array = new Uint8Array([/* YOUR_SECRET_KEY_ARRAY */]);
const wallet = new Wallet(Keypair.fromSecretKey(secretKeyUint8Array));🔐 Security Tip: Never hardcode secret keys in production. Use environment variables or secure key management tools.
Fetch Real-Time Data from Bitquery
Create a helper function to query Bitquery’s streaming API:
async function fetchGraphQL(query) {
const response = await fetch("https://streaming.bitquery.io/eap", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer YOUR_BITQUERY_OAUTH_TOKEN",
},
body: JSON.stringify({ query }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}Extract Pool and Token Addresses
Parse the response to extract relevant token addresses:
async function getPoolAddresses() {
try {
const data = await fetchGraphQL(subscriptionQuery);
const instructions = lodash.get(data, "data.Solana.Instructions", []);
return instructions.map(({ Instruction: { Accounts } }) => ({
poolAddress: Accounts.length > 4 ? Accounts[4].Address : undefined,
tokenA: Accounts.length > 8 ? Accounts[8].Address : undefined,
tokenB: Accounts.length > 9 ? Accounts[9].Address : undefined,
}))[0];
} catch (error) {
console.error("Error fetching data:", error);
return { poolAddress: "", tokenA: "", tokenB: "" };
}
}Execute Token Swaps via Jupiter API
Automate trading using Jupiter’s swap API. This function fetches a quote and executes the trade:
async function swapTokens(tokenA, tokenB) {
try {
const quoteUrl = `https://quote-api.jup.ag/v6/quote?inputMint=${tokenB}&outputMint=${tokenA}&amount=10000&slippageBps=150`;
const quoteResponse = await fetch(quoteUrl);
const quoteData = await quoteResponse.json();
if (
quoteData["errorCode"] !== "TOKEN_NOT_TRADABLE" &&
quoteData["errorCode"] !== "COULD_NOT_FIND_ANY_ROUTE"
) {
const swapTransactionResponse = await fetch(
"https://quote-api.jup.ag/v6/swap",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
quoteResponse: quoteData,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true,
}),
}
);
const { swapTransaction } = await swapTransactionResponse.json();
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
transaction.sign([wallet.payer]);
const rawTransaction = transaction.serialize();
const txid = await connection.sendRawTransaction(rawTransaction, {
skipPreflight: false,
maxRetries: 4,
preflightCommitment: "confirmed",
commitment: "confirmed",
});
await connection.confirmTransaction(txid, "confirmed");
console.log(`Transaction successful: https://solscan.io/tx/${txid}`);
}
} catch (error) {
console.error("Error during token swap:", error);
}
}👉 See how advanced trading tools can enhance your DeFi performance.
Main Execution Loop
Orchestrate the entire process:
async function main() {
const { tokenA, tokenB } = await getPoolAddresses();
if (tokenA && tokenB) {
await swapTokens(tokenA, tokenB);
}
}
main();Step 3: Run the Bot
Replace placeholders:
YOUR_PUBLIC_KEY→ Your Solana wallet public keyYOUR_SECRET_KEY_ARRAY→ Your wallet’s secret key (as Uint8Array)YOUR_BITQUERY_OAUTH_TOKEN→ Your Bitquery API token
Start the bot:
node index.js
The bot will now listen for new Raydium pool creations and execute swaps automatically.
Frequently Asked Questions
Q: Is it legal to use a sniper bot on Solana?
A: Using automation tools is not illegal, but always comply with platform terms of service and exercise ethical trading practices.
Q: Can this bot work on testnet?
A: Yes. Switch the Solana endpoint to a testnet URL and use test SOL from a faucet.
Q: How fast is the bot’s reaction time?
A: With optimized infrastructure and low-latency APIs, reaction times can be under 500ms—fast enough to catch early trades.
Q: What risks are involved?
A: Market volatility, failed transactions, and smart contract risks exist. Always start with small amounts.
Q: Can I modify it to sell tokens too?
A: Absolutely. Extend the logic to monitor price changes or use Jupiter’s reverse swap functionality.
👉 Access powerful trading APIs to supercharge your bot strategies.
Final Thoughts
You’ve now built a fully functional Solana sniper bot capable of detecting new tokens in real time and executing instant trades via Jupiter. This setup combines on-chain monitoring, low-latency execution, and automated decision-making—the trifecta of modern DeFi trading.
While this tutorial focuses on educational implementation, refining your bot with error handling, rate limiting, and security best practices will make it production-ready.
Remember: speed gives you an edge, but smart risk management ensures long-term success.
Core Keywords: Solana sniper bot, real-time Solana subscriptions, Jupiter Swap API, Bitquery, automated trading bot, DeFi trading automation, blockchain data API, on-chain monitoring