How to Buy Solana Tokens Programmatically with the Sniperoo API #
If you’ve ever tried to buy a Solana token the moment it launches, you know the drill: frantically clicking buttons, fumbling with confirmation dialogs, and watching the price slip away while you’re still copy-pasting addresses. There has to be a better way – and there is.
With the Sniperoo API, you can write scripts that buy tokens instantly, set up conditional buy orders that execute while you sleep, and even run risk checks before committing a single lamport. No more manual clicking. No more missed opportunities.
Unlike most Solana trading bots that force you into a Telegram chat, Sniperoo gives you a proper REST API. That means you can integrate it into your own tools, dashboards, bots, or automated workflows using any programming language you like.
In this guide, you’ll learn how to:
- Buy a token instantly with a single API call
- Buy with multiple wallets simultaneously
- Set up conditional buy orders that trigger on price drops or market cap targets
- Attach auto-sell strategies at buy time for hands-free profit taking
- Run risk checks before buying to avoid scam tokens
- Handle errors gracefully so your bot keeps running
Let’s get started.
Prerequisites #
Before diving into the code, make sure you have the following ready:
- A Sniperoo account – sign up at sniperoo.app if you haven’t already
- An API key – generate one from the API Access section of your dashboard
- At least one wallet with SOL – you’ll need SOL to buy tokens (obviously!)
- A development environment – pick your flavor below
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
- Node.js (version 16 or higher) – download from nodejs.org
- npm or yarn (comes with Node.js)
Install the HTTP client:
npm install axios{% /tab %} {% tab label=“Python” %}
- Python (version 3.7 or higher) – download from python.org
- pip (comes with Python)
Install the HTTP client:
pip install requests{% /tab %} {% /tabs %}
{% admonition type=“warning” name=“Keep Your API Key Safe” %}
Your API key grants full access to your Sniperoo account. Never commit it to public repositories, share it in chat, or include it in client-side code. Store it in environment variables or a .env file.
{% /admonition %}
Quick Start – Your First Token Purchase #
Let’s start with the most basic operation: buying a token immediately. The endpoint you’ll use is:
POST https://api.sniperoo.app/trading/buy-tokenThe request body needs four required fields:
| Field | Type | Description |
|---|---|---|
walletAddresses |
string[] |
Array of wallet addresses to buy with |
tokenAddress |
string |
The Solana token address (base58 format) |
inputAmount |
number |
Amount of SOL to spend (before fees and slippage) |
isBuying |
boolean |
Must be set to true |
On success (HTTP 201), the API returns a BuyTokenResponseDto with:
| Field | Description |
|---|---|
purchases |
Array of purchase details (one per wallet) |
purchases[].txSignature |
The on-chain transaction signature |
purchases[].tokenAmount |
Amount of tokens received |
purchases[].tokenAmountInUSD |
USD value of tokens at purchase time |
purchases[].tokenPriceInUSD |
Token price in USD at purchase time |
solPriceInUSD |
SOL price in USD at the time of purchase |
Here’s a complete, runnable example that buys 0.1 SOL worth of a token:
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
Create a file called buy-token.js:
const axios = require('axios');
// --- Configuration ---
const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
const BASE_URL = 'https://api.sniperoo.app';
// Replace with your actual wallet address and target token
const WALLET_ADDRESS = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
const TOKEN_ADDRESS = '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr';
const SOL_AMOUNT = 0.1; // Spend 0.1 SOL
async function buyToken() {
try {
const response = await axios.post(
`${BASE_URL}/trading/buy-token`,
{
walletAddresses: [WALLET_ADDRESS],
tokenAddress: TOKEN_ADDRESS,
inputAmount: SOL_AMOUNT,
isBuying: true,
},
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
}
);
const data = response.data;
console.log('Purchase successful!');
console.log(`SOL Price: $${data.solPriceInUSD}`);
data.purchases.forEach((purchase, index) => {
console.log(`\n--- Purchase #${index + 1} ---`);
console.log(` TX Signature: ${purchase.txSignature}`);
console.log(` Tokens Received: ${purchase.tokenAmount}`);
console.log(` Value (USD): $${purchase.tokenAmountInUSD}`);
console.log(` Token Price: $${purchase.tokenPriceInUSD}`);
console.log(` Explorer: https://solscan.io/tx/${purchase.txSignature}`);
});
} catch (error) {
if (error.response) {
console.error(`API Error (${error.response.status}):`, error.response.data);
} else {
console.error('Request failed:', error.message);
}
}
}
buyToken();Run it:
node buy-token.js{% /tab %} {% tab label=“Python” %}
Create a file called buy_token.py:
import requests
# --- Configuration ---
API_KEY = "YOUR_API_KEY" # Replace with your actual API key
BASE_URL = "https://api.sniperoo.app"
# Replace with your actual wallet address and target token
WALLET_ADDRESS = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
TOKEN_ADDRESS = "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr"
SOL_AMOUNT = 0.1 # Spend 0.1 SOL
def buy_token():
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"walletAddresses": [WALLET_ADDRESS],
"tokenAddress": TOKEN_ADDRESS,
"inputAmount": SOL_AMOUNT,
"isBuying": True,
}
response = requests.post(
f"{BASE_URL}/trading/buy-token",
json=payload,
headers=headers,
)
if response.status_code == 201:
data = response.json()
print("Purchase successful!")
print(f"SOL Price: ${data['solPriceInUSD']}")
for i, purchase in enumerate(data["purchases"]):
print(f"\n--- Purchase #{i + 1} ---")
print(f" TX Signature: {purchase['txSignature']}")
print(f" Tokens Received: {purchase['tokenAmount']}")
print(f" Value (USD): ${purchase['tokenAmountInUSD']}")
print(f" Token Price: ${purchase['tokenPriceInUSD']}")
print(f" Explorer: https://solscan.io/tx/{purchase['txSignature']}")
else:
print(f"API Error ({response.status_code}): {response.text}")
if __name__ == "__main__":
buy_token()Run it:
python buy_token.py{% /tab %} {% /tabs %}
{% admonition type=“info” name=“Where Do I Find Token Addresses?” %} Every Solana token has a unique base58-encoded address (32-44 characters). You can find them on Solscan, Birdeye, or directly from the Sniperoo platform. The address in the example above is just a placeholder – replace it with the token you actually want to buy. {% /admonition %}
Buying with Multiple Wallets #
One of the most powerful features of the Sniperoo API is the ability to buy tokens with multiple wallets in a single API call. Just pass more addresses into the walletAddresses array.
Important: When you specify multiple wallets, each wallet buys the full inputAmount independently. So if you pass 3 wallets with inputAmount: 0.5, each wallet spends 0.5 SOL, for a total of 1.5 SOL across all three.
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
Create a file called multi-wallet-buy.js:
const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.sniperoo.app';
// Three wallets buying simultaneously
const WALLETS = [
'7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',
'BUX7s2ef2htTGb2KKoPHWkmzxPj4nTWMWRgs5CSbQxf9',
'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263',
];
const TOKEN_ADDRESS = '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr';
const SOL_PER_WALLET = 0.5; // Each wallet spends 0.5 SOL (total: 1.5 SOL)
async function buyWithMultipleWallets() {
try {
console.log(`Buying with ${WALLETS.length} wallets...`);
console.log(`Each wallet spending: ${SOL_PER_WALLET} SOL`);
console.log(`Total SOL: ${WALLETS.length * SOL_PER_WALLET} SOL\n`);
const response = await axios.post(
`${BASE_URL}/trading/buy-token`,
{
walletAddresses: WALLETS,
tokenAddress: TOKEN_ADDRESS,
inputAmount: SOL_PER_WALLET,
isBuying: true,
},
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
}
);
const data = response.data;
console.log('All purchases successful!');
console.log(`SOL Price: $${data.solPriceInUSD}\n`);
let totalTokens = 0;
data.purchases.forEach((purchase, index) => {
console.log(`Wallet #${index + 1}:`);
console.log(` TX: ${purchase.txSignature}`);
console.log(` Tokens: ${purchase.tokenAmount}`);
console.log(` Value: $${purchase.tokenAmountInUSD}`);
totalTokens += parseFloat(purchase.tokenAmount);
});
console.log(`\nTotal tokens acquired: ${totalTokens}`);
} catch (error) {
if (error.response) {
console.error(`API Error (${error.response.status}):`, error.response.data);
} else {
console.error('Request failed:', error.message);
}
}
}
buyWithMultipleWallets();Run it:
node multi-wallet-buy.js{% /tab %} {% tab label=“Python” %}
Create a file called multi_wallet_buy.py:
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.sniperoo.app"
# Three wallets buying simultaneously
WALLETS = [
"7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
"BUX7s2ef2htTGb2KKoPHWkmzxPj4nTWMWRgs5CSbQxf9",
"DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",
]
TOKEN_ADDRESS = "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr"
SOL_PER_WALLET = 0.5 # Each wallet spends 0.5 SOL (total: 1.5 SOL)
def buy_with_multiple_wallets():
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"walletAddresses": WALLETS,
"tokenAddress": TOKEN_ADDRESS,
"inputAmount": SOL_PER_WALLET,
"isBuying": True,
}
print(f"Buying with {len(WALLETS)} wallets...")
print(f"Each wallet spending: {SOL_PER_WALLET} SOL")
print(f"Total SOL: {len(WALLETS) * SOL_PER_WALLET} SOL\n")
response = requests.post(
f"{BASE_URL}/trading/buy-token",
json=payload,
headers=headers,
)
if response.status_code == 201:
data = response.json()
print("All purchases successful!")
print(f"SOL Price: ${data['solPriceInUSD']}\n")
total_tokens = 0
for i, purchase in enumerate(data["purchases"]):
print(f"Wallet #{i + 1}:")
print(f" TX: {purchase['txSignature']}")
print(f" Tokens: {purchase['tokenAmount']}")
print(f" Value: ${purchase['tokenAmountInUSD']}")
total_tokens += float(purchase["tokenAmount"])
print(f"\nTotal tokens acquired: {total_tokens}")
else:
print(f"API Error ({response.status_code}): {response.text}")
if __name__ == "__main__":
buy_with_multiple_wallets()Run it:
python multi_wallet_buy.py{% /tab %} {% /tabs %}
{% admonition type=“info” name=“Why Use Multiple Wallets?” %} Buying with multiple wallets is a common strategy. It lets you spread risk across wallets, sell from different positions independently, or manage different strategies per wallet – all from a single API call. {% /admonition %}
Conditional Buy Orders (Auto-Buy) #
Sometimes you don’t want to buy at the current price. You want to buy when a condition is met – like when the price dips 25% or when the market cap reaches a certain level. That’s where conditional buy orders come in.
When you include an autoBuy object in your buy request, Sniperoo creates an order instead of buying immediately. The order stays active until the conditions are met (and then it executes automatically) or until it expires.
The autoBuy object structure:
{
"autoBuy": {
"enabled": true,
"strategy": {
"priceMetric": { ... },
"expiresAt": {
"value": 2,
"unit": "hours"
}
}
}
}There are two types of price metrics you can use:
- Price Change (
metricType: "price_change") – triggers when price moves up or down by a percentage - Market Cap (
metricType: "market_cap") – triggers when market cap reaches a range
When an order is created, the response is a CreateOrderResponseDto:
| Field | Description |
|---|---|
orderId |
Unique ID to track or manage this order |
expiresAt |
Unix timestamp (ms) when the order will expire |
Example 1: Buy When Price Drops 25% #
This creates an order that will automatically buy the token if its price drops between 20% and 30% from the current level:
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
Create a file called conditional-buy-dip.js:
const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.sniperoo.app';
const WALLET_ADDRESS = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
const TOKEN_ADDRESS = '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr';
async function buyOnDip() {
try {
const response = await axios.post(
`${BASE_URL}/trading/buy-token`,
{
walletAddresses: [WALLET_ADDRESS],
tokenAddress: TOKEN_ADDRESS,
inputAmount: 0.5,
isBuying: true,
autoBuy: {
enabled: true,
strategy: {
priceMetric: {
metricType: 'price_change',
minusOrPlus: 'minus', // We want a price DECREASE
enabled: true,
minValue: 20, // At least 20% drop
maxValue: 30, // No more than 30% drop
},
expiresAt: {
value: 4,
unit: 'hours', // Order expires in 4 hours
},
},
},
},
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
}
);
const data = response.data;
const expiryDate = new Date(data.expiresAt);
console.log('Conditional buy order created!');
console.log(` Order ID: ${data.orderId}`);
console.log(` Expires at: ${expiryDate.toLocaleString()}`);
console.log(' Condition: Buy when price drops 20-30%');
console.log('\nThe order will execute automatically when the condition is met.');
} catch (error) {
if (error.response) {
console.error(`API Error (${error.response.status}):`, error.response.data);
} else {
console.error('Request failed:', error.message);
}
}
}
buyOnDip();Run it:
node conditional-buy-dip.js{% /tab %} {% tab label=“Python” %}
Create a file called conditional_buy_dip.py:
import requests
from datetime import datetime
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.sniperoo.app"
WALLET_ADDRESS = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
TOKEN_ADDRESS = "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr"
def buy_on_dip():
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"walletAddresses": [WALLET_ADDRESS],
"tokenAddress": TOKEN_ADDRESS,
"inputAmount": 0.5,
"isBuying": True,
"autoBuy": {
"enabled": True,
"strategy": {
"priceMetric": {
"metricType": "price_change",
"minusOrPlus": "minus", # We want a price DECREASE
"enabled": True,
"minValue": 20, # At least 20% drop
"maxValue": 30, # No more than 30% drop
},
"expiresAt": {
"value": 4,
"unit": "hours", # Order expires in 4 hours
},
},
},
}
response = requests.post(
f"{BASE_URL}/trading/buy-token",
json=payload,
headers=headers,
)
if response.status_code == 201:
data = response.json()
expiry_date = datetime.fromtimestamp(data["expiresAt"] / 1000)
print("Conditional buy order created!")
print(f" Order ID: {data['orderId']}")
print(f" Expires at: {expiry_date.strftime('%Y-%m-%d %H:%M:%S')}")
print(" Condition: Buy when price drops 20-30%")
print("\nThe order will execute automatically when the condition is met.")
else:
print(f"API Error ({response.status_code}): {response.text}")
if __name__ == "__main__":
buy_on_dip()Run it:
python conditional_buy_dip.py{% /tab %} {% /tabs %}
Example 2: Buy When Market Cap Reaches $500K #
This creates an order that triggers when the token’s market cap is between $400K and $600K:
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
Create a file called conditional-buy-mcap.js:
const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.sniperoo.app';
const WALLET_ADDRESS = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
const TOKEN_ADDRESS = '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr';
async function buyAtMarketCap() {
try {
const response = await axios.post(
`${BASE_URL}/trading/buy-token`,
{
walletAddresses: [WALLET_ADDRESS],
tokenAddress: TOKEN_ADDRESS,
inputAmount: 1.0,
isBuying: true,
autoBuy: {
enabled: true,
strategy: {
priceMetric: {
metricType: 'market_cap',
unit: 'thousand', // Values are in thousands
enabled: true,
minValue: 400, // Minimum market cap: $400K
maxValue: 600, // Maximum market cap: $600K
},
expiresAt: {
value: 24,
unit: 'hours', // Order expires in 24 hours
},
},
},
},
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
}
);
const data = response.data;
const expiryDate = new Date(data.expiresAt);
console.log('Market cap buy order created!');
console.log(` Order ID: ${data.orderId}`);
console.log(` Expires at: ${expiryDate.toLocaleString()}`);
console.log(' Condition: Buy when market cap is $400K - $600K');
} catch (error) {
if (error.response) {
console.error(`API Error (${error.response.status}):`, error.response.data);
} else {
console.error('Request failed:', error.message);
}
}
}
buyAtMarketCap();Run it:
node conditional-buy-mcap.js{% /tab %} {% tab label=“Python” %}
Create a file called conditional_buy_mcap.py:
import requests
from datetime import datetime
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.sniperoo.app"
WALLET_ADDRESS = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
TOKEN_ADDRESS = "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr"
def buy_at_market_cap():
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"walletAddresses": [WALLET_ADDRESS],
"tokenAddress": TOKEN_ADDRESS,
"inputAmount": 1.0,
"isBuying": True,
"autoBuy": {
"enabled": True,
"strategy": {
"priceMetric": {
"metricType": "market_cap",
"unit": "thousand", # Values are in thousands
"enabled": True,
"minValue": 400, # Minimum market cap: $400K
"maxValue": 600, # Maximum market cap: $600K
},
"expiresAt": {
"value": 24,
"unit": "hours", # Order expires in 24 hours
},
},
},
}
response = requests.post(
f"{BASE_URL}/trading/buy-token",
json=payload,
headers=headers,
)
if response.status_code == 201:
data = response.json()
expiry_date = datetime.fromtimestamp(data["expiresAt"] / 1000)
print("Market cap buy order created!")
print(f" Order ID: {data['orderId']}")
print(f" Expires at: {expiry_date.strftime('%Y-%m-%d %H:%M:%S')}")
print(" Condition: Buy when market cap is $400K - $600K")
else:
print(f"API Error ({response.status_code}): {response.text}")
if __name__ == "__main__":
buy_at_market_cap()Run it:
python conditional_buy_mcap.py{% /tab %} {% /tabs %}
{% admonition type=“info” name=“Market Cap Units” %}
The unit field accepts "thousand" or "million". So { unit: "thousand", minValue: 500 } means $500,000, while { unit: "million", minValue: 5 } means $5,000,000. Choose whichever makes your values easier to read.
{% /admonition %}
Attaching Auto-Sell at Buy Time #
Here’s a pro move: you can attach an auto-sell strategy directly to your buy request. This means the moment your purchase goes through, Sniperoo will automatically monitor the position and sell when your profit or stop-loss targets are hit. Zero manual intervention required.
To do this, add an autoSell object to your buy request body:
{
"walletAddresses": ["YOUR_WALLET_ADDRESS"],
"tokenAddress": "TOKEN_ADDRESS",
"inputAmount": 0.5,
"isBuying": true,
"autoSell": {
"enabled": true,
"strategy": {
"strategyName": "simple",
"profitPercentage": 100,
"stopLossPercentage": 25
}
}
}In the example above, the “simple” strategy will:
- Take profit when the token price doubles (100% gain)
- Stop loss if the token drops 25% from your entry price
That’s it – buy and forget. Sniperoo handles the exit for you.
{% admonition type=“info” name=“More Auto-Sell Strategies” %} The simple strategy is just the beginning. Sniperoo supports 4 auto-sell strategies: Simple, Grid (with static stop-loss), Trailing Grid (with trailing stop-loss), and DevSell (sell when the token creator sells). For a deep dive into all of them, see our Mastering Auto-Sell Strategies guide. {% /admonition %}
Risk Check Before Buying #
Buying blindly on Solana is a recipe for disaster. Rug pulls, honeypots, and sketchy tokens are everywhere. Fortunately, Sniperoo includes a built-in risk assessment endpoint so you can check a token before putting money on the line.
The endpoint:
GET https://api.sniperoo.app/solana/risk?tokenAddress={address}The response includes:
| Field | Description |
|---|---|
risks |
Array of identified risk factors |
risks[].name |
Short name for the risk (e.g., “Low Liquidity”) |
risks[].description |
Detailed explanation |
risks[].level |
Severity: "danger", "warn", or "warning" |
risks[].score |
Numerical weight of this risk |
score |
Overall risk score (higher = riskier) |
tokenProgram |
The Solana program managing this token |
tokenType |
Token standard type |
Here’s a complete example that checks the risk first and only buys if the score is below a threshold:
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
Create a file called safe-buy.js:
const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.sniperoo.app';
const WALLET_ADDRESS = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
const TOKEN_ADDRESS = '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr';
const SOL_AMOUNT = 0.1;
const MAX_RISK_SCORE = 5000; // Only buy if risk score is below this
const headers = {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
};
async function checkRisk(tokenAddress) {
console.log(`Checking risk for token: ${tokenAddress}...`);
const response = await axios.get(`${BASE_URL}/solana/risk`, {
params: { tokenAddress },
headers,
});
return response.data;
}
async function buyToken(tokenAddress, amount) {
const response = await axios.post(
`${BASE_URL}/trading/buy-token`,
{
walletAddresses: [WALLET_ADDRESS],
tokenAddress,
inputAmount: amount,
isBuying: true,
},
{ headers }
);
return response.data;
}
async function safeBuy() {
try {
// Step 1: Check the risk
const riskData = await checkRisk(TOKEN_ADDRESS);
console.log(`\nRisk Assessment:`);
console.log(` Overall Score: ${riskData.score}`);
console.log(` Token Program: ${riskData.tokenProgram}`);
console.log(` Token Type: ${riskData.tokenType}`);
console.log(` Risks Found: ${riskData.risks.length}`);
// Print each risk
riskData.risks.forEach((risk) => {
const icon =
risk.level === 'danger' ? '[DANGER]' :
risk.level === 'warn' || risk.level === 'warning' ? '[WARN]' : '[INFO]';
console.log(` ${icon} ${risk.name}: ${risk.description} (score: ${risk.score})`);
});
// Step 2: Decide whether to buy
if (riskData.score >= MAX_RISK_SCORE) {
console.log(`\nRisk score ${riskData.score} exceeds threshold ${MAX_RISK_SCORE}. Skipping purchase.`);
return;
}
console.log(`\nRisk score ${riskData.score} is below threshold ${MAX_RISK_SCORE}. Proceeding with purchase...`);
// Step 3: Buy the token
const buyData = await buyToken(TOKEN_ADDRESS, SOL_AMOUNT);
console.log('\nPurchase successful!');
buyData.purchases.forEach((purchase, index) => {
console.log(` Purchase #${index + 1}:`);
console.log(` TX: ${purchase.txSignature}`);
console.log(` Tokens: ${purchase.tokenAmount}`);
console.log(` Value: $${purchase.tokenAmountInUSD}`);
});
} catch (error) {
if (error.response) {
console.error(`API Error (${error.response.status}):`, error.response.data);
} else {
console.error('Request failed:', error.message);
}
}
}
safeBuy();Run it:
node safe-buy.js{% /tab %} {% tab label=“Python” %}
Create a file called safe_buy.py:
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.sniperoo.app"
WALLET_ADDRESS = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
TOKEN_ADDRESS = "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr"
SOL_AMOUNT = 0.1
MAX_RISK_SCORE = 5000 # Only buy if risk score is below this
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
def check_risk(token_address):
print(f"Checking risk for token: {token_address}...")
response = requests.get(
f"{BASE_URL}/solana/risk",
params={"tokenAddress": token_address},
headers=HEADERS,
)
response.raise_for_status()
return response.json()
def buy_token(token_address, amount):
payload = {
"walletAddresses": [WALLET_ADDRESS],
"tokenAddress": token_address,
"inputAmount": amount,
"isBuying": True,
}
response = requests.post(
f"{BASE_URL}/trading/buy-token",
json=payload,
headers=HEADERS,
)
response.raise_for_status()
return response.json()
def safe_buy():
try:
# Step 1: Check the risk
risk_data = check_risk(TOKEN_ADDRESS)
print(f"\nRisk Assessment:")
print(f" Overall Score: {risk_data['score']}")
print(f" Token Program: {risk_data['tokenProgram']}")
print(f" Token Type: {risk_data['tokenType']}")
print(f" Risks Found: {len(risk_data['risks'])}")
# Print each risk
for risk in risk_data["risks"]:
level = risk["level"]
icon = "[DANGER]" if level == "danger" else "[WARN]"
print(f" {icon} {risk['name']}: {risk['description']} (score: {risk['score']})")
# Step 2: Decide whether to buy
if risk_data["score"] >= MAX_RISK_SCORE:
print(f"\nRisk score {risk_data['score']} exceeds threshold {MAX_RISK_SCORE}. Skipping purchase.")
return
print(f"\nRisk score {risk_data['score']} is below threshold {MAX_RISK_SCORE}. Proceeding with purchase...")
# Step 3: Buy the token
buy_data = buy_token(TOKEN_ADDRESS, SOL_AMOUNT)
print("\nPurchase successful!")
for i, purchase in enumerate(buy_data["purchases"]):
print(f" Purchase #{i + 1}:")
print(f" TX: {purchase['txSignature']}")
print(f" Tokens: {purchase['tokenAmount']}")
print(f" Value: ${purchase['tokenAmountInUSD']}")
except requests.exceptions.HTTPError as e:
print(f"API Error ({e.response.status_code}): {e.response.text}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
if __name__ == "__main__":
safe_buy()Run it:
python safe_buy.py{% /tab %} {% /tabs %}
{% admonition type=“warning” name=“Risk Scores Are Not Guarantees” %} A low risk score doesn’t guarantee a token is safe – it just means no obvious red flags were detected. Always do your own research (DYOR) and never invest more than you can afford to lose. {% /admonition %}
Error Handling #
Things don’t always go smoothly in the world of Solana trading. Transactions can fail, tokens can become untradeable, and wallets can run dry. Here are the most common errors you’ll encounter and how to handle them:
| Error | Cause | Fix |
|---|---|---|
SLIPPAGE_TOLERANCE |
Price moved too much between quote and execution | Increase slippage tolerance in your user settings on the Sniperoo platform |
INSUFFICIENT_FUNDS |
Wallet doesn’t have enough SOL | Top up your wallet balance before retrying |
TOKEN_NOT_TRADABLE |
Token’s liquidity pool is missing or locked | This token can’t be traded right now – nothing you can do |
TIMEOUT |
Transaction didn’t confirm in time | Retry with a higher Jito tip for faster inclusion |
INVALID_TOKEN_ADDRESS |
The token address format is wrong | Double-check the address is a valid Solana base58 string (32-44 chars) |
Rate Limiting #
The API enforces rate limits to ensure fair usage. If you send too many requests too quickly, you’ll get a 429 Too Many Requests response. The best practice is to implement exponential backoff: wait 1 second, then 2, then 4, and so on.
Here’s a reusable helper with retry logic built in:
{% tabs syncId=“programming-language” %} {% tab label=“JavaScript” %}
Create a file called buy-with-retry.js:
const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.sniperoo.app';
const headers = {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
};
async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function buyTokenWithRetry(payload, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await axios.post(
`${BASE_URL}/trading/buy-token`,
payload,
{ headers }
);
return response.data;
} catch (error) {
const status = error.response?.status;
const errorData = error.response?.data;
// Rate limited -- back off and retry
if (status === 429) {
const waitTime = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s
console.log(`Rate limited. Waiting ${waitTime / 1000}s before retry (${attempt}/${maxRetries})...`);
await sleep(waitTime);
continue;
}
// Timeout -- retry with same settings
if (errorData?.message === 'TIMEOUT' && attempt < maxRetries) {
console.log(`Transaction timed out. Retrying (${attempt}/${maxRetries})...`);
await sleep(1000);
continue;
}
// Non-retryable errors
if (errorData?.message === 'INSUFFICIENT_FUNDS') {
throw new Error('Wallet has insufficient SOL. Please top up and try again.');
}
if (errorData?.message === 'TOKEN_NOT_TRADABLE') {
throw new Error('This token cannot be traded at this time.');
}
if (errorData?.message === 'INVALID_TOKEN_ADDRESS') {
throw new Error('Invalid token address. Check the address format.');
}
throw error;
}
}
throw new Error(`Failed after ${maxRetries} retries.`);
}
// Usage example
async function main() {
try {
const result = await buyTokenWithRetry({
walletAddresses: ['7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU'],
tokenAddress: '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr',
inputAmount: 0.1,
isBuying: true,
});
console.log('Purchase successful!');
result.purchases.forEach((p) => {
console.log(` TX: ${p.txSignature}`);
console.log(` Tokens: ${p.tokenAmount}`);
});
} catch (error) {
console.error(`Failed: ${error.message}`);
}
}
main();Run it:
node buy-with-retry.js{% /tab %} {% tab label=“Python” %}
Create a file called buy_with_retry.py:
import requests
import time
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.sniperoo.app"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
def buy_token_with_retry(payload, max_retries=3):
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
f"{BASE_URL}/trading/buy-token",
json=payload,
headers=HEADERS,
)
# Rate limited -- back off and retry
if response.status_code == 429:
wait_time = (2 ** attempt) # 2s, 4s, 8s
print(f"Rate limited. Waiting {wait_time}s before retry ({attempt}/{max_retries})...")
time.sleep(wait_time)
continue
if response.status_code == 201:
return response.json()
# Parse error message
error_data = response.json() if response.text else {}
error_message = error_data.get("message", "Unknown error")
# Timeout -- retry
if error_message == "TIMEOUT" and attempt < max_retries:
print(f"Transaction timed out. Retrying ({attempt}/{max_retries})...")
time.sleep(1)
continue
# Non-retryable errors
if error_message == "INSUFFICIENT_FUNDS":
raise Exception("Wallet has insufficient SOL. Please top up and try again.")
if error_message == "TOKEN_NOT_TRADABLE":
raise Exception("This token cannot be traded at this time.")
if error_message == "INVALID_TOKEN_ADDRESS":
raise Exception("Invalid token address. Check the address format.")
raise Exception(f"API Error ({response.status_code}): {response.text}")
except requests.exceptions.RequestException as e:
if attempt < max_retries:
print(f"Network error. Retrying ({attempt}/{max_retries})...")
time.sleep(2 ** attempt)
continue
raise
raise Exception(f"Failed after {max_retries} retries.")
# Usage example
def main():
try:
result = buy_token_with_retry({
"walletAddresses": ["7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"],
"tokenAddress": "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr",
"inputAmount": 0.1,
"isBuying": True,
})
print("Purchase successful!")
for purchase in result["purchases"]:
print(f" TX: {purchase['txSignature']}")
print(f" Tokens: {purchase['tokenAmount']}")
except Exception as e:
print(f"Failed: {e}")
if __name__ == "__main__":
main()Run it:
python buy_with_retry.py{% /tab %} {% /tabs %}
{% admonition type=“info” name=“Optimize Your Transactions” %}
If you’re seeing frequent TIMEOUT or SLIPPAGE_TOLERANCE errors, your transaction settings might need tuning. To learn how to configure Jito tips, slippage tolerance, and priority fees for faster and more reliable transactions, see our Jito Tips & Priority Fees guide.
{% /admonition %}
What’s Next #
You now know how to buy tokens programmatically, set conditional orders, run risk checks, and handle errors like a pro. But buying is only half the story – here’s where to go from here:
- How to Sell Tokens & Manage Positions – learn how to sell tokens, manage open positions, and close trades at the right time
- Mastering Auto-Sell Strategies – set up Simple, Grid, Trailing Grid, and DevSell strategies to automate your exits
- Jito Tips & Priority Fees – fine-tune transaction speed and reliability with Jito bundles and priority fees
- Wallet Management – create, import, and manage wallets, plus transfer SOL between them
Happy trading!