API Tutorial
Complete step-by-step guide to integrating GETMEGABOT APIs into your Solana project. Build trading bots, track whale movements, and access reliable RPC infrastructure.
Getting Started
Set up your account and get your API key to start making requests to GETMEGABOT APIs.
Create Your Account
Visit the signup page and create your free account. No credit card required for the free tier.
✓ Instant API key generation ✓ Access to all three APIs ✓ 1,000 RPC requests/month ✓ 3,000 analytics requests/month ✓ Unlimited whale tracking
Get Your API Key
After signing up, you'll find your API key in the dashboard. This key authenticates all your API requests.
sk_live_abc123def456ghi789jkl012mno345pqr678
Test Your Connection
Verify your API key works with a simple health check request.
curl -X GET "https://api.getmegabot.com/health" \ -H "X-API-Key: YOUR_API_KEY"
{
"status": "ok",
"timestamp": 1702314567,
"apis": {
"rpc": "operational",
"analytics": "operational",
"whale": "operational"
}
}
.env file: MEGABOT_API_KEY=sk_live_your_key_here. Add .env to your .gitignore file to prevent accidental commits.
SolanaRouter Setup
Replace your RPC endpoint with SolanaRouter for 99.9% uptime and automatic failover across 10+ premium providers.
Why SolanaRouter?
- Never worry about RPC downtime
- Automatic failover when providers fail
- Intelligent load balancing based on latency
- Drop-in replacement for any Solana library
JavaScript Integration
Use SolanaRouter with web3.js by simply replacing your RPC URL.
import { Connection } from '@solana/web3.js';
// Replace your RPC URL with GETMEGABOT endpoint
const connection = new Connection(
'https://api.getmegabot.com/rpc',
{
commitment: 'confirmed',
httpHeaders: {
'X-API-Key': process.env.MEGABOT_API_KEY
}
}
);
// Use it exactly like normal web3.js
const slot = await connection.getSlot();
const balance = await connection.getBalance(publicKey);
console.log(`Current slot: ${slot}`);
Python Integration
Use SolanaRouter with the Solana Python SDK.
from solana.rpc.api import Client
import os
# Initialize with GETMEGABOT endpoint
client = Client(
"https://api.getmegabot.com/rpc",
headers={'X-API-Key': os.environ['MEGABOT_API_KEY']}
)
# Use it like normal Solana client
slot = client.get_slot()
balance = client.get_balance(public_key)
print(f"Current slot: {slot['result']}")
commitment: 'confirmed' for trading bots to get the perfect balance of speed and reliability. SolanaRouter optimizes routing based on your commitment level.
WebSocket Subscriptions
Monitor account changes with reliable WebSocket connections.
import { Connection, PublicKey } from '@solana/web3.js';
const connection = new Connection(
'https://api.getmegabot.com/rpc',
{
commitment: 'confirmed',
httpHeaders: { 'X-API-Key': process.env.MEGABOT_API_KEY }
}
);
const publicKey = new PublicKey('YourWalletAddress...');
// Monitor account changes with 99.9% reliability
connection.onAccountChange(
publicKey,
(accountInfo) => {
console.log('Account changed!', accountInfo);
// Execute your trading logic here
},
'confirmed'
);
PumpIntel Integration
Track every token graduating from Pump.fun to Raydium with real-time data and algorithmic quality scoring.
Get Recent Graduations
Fetch the latest tokens that graduated from Pump.fun to Raydium.
const response = await fetch(
'https://api.getmegabot.com/v1/analytics/graduations',
{
headers: {
'X-API-Key': process.env.MEGABOT_API_KEY,
'Content-Type': 'application/json'
}
}
);
const data = await response.json();
console.log(data.graduations);
[
{
"mint": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
"name": "Doge Killer",
"symbol": "DOGK",
"graduationTime": "2024-12-11T10:30:00Z",
"qualityScore": 75,
"safetyCheck": "SAFE",
"liquiditySOL": 125.5,
"holderCount": 1250
},
...
]
Understanding Quality Scores
Every graduation includes a quality score (0-100) based on multiple factors.
90-100: Excellent - High confidence, strong fundamentals 70-89: Good - Worth investigating, decent metrics 50-69: Average - Proceed with caution, mixed signals 0-49: Poor - High risk, weak fundamentals
- Liquidity Depth - How much SOL in the pool
- Holder Distribution - Not concentrated in few wallets
- Trading Volume - Healthy buy/sell activity
- Safety Checks - No rugpull indicators
Real-Time WebSocket Feed
Get instant notifications when high-quality tokens graduate.
const ws = new WebSocket(
'wss://api.getmegabot.com/v1/analytics/stream',
{
headers: { 'X-API-Key': process.env.MEGABOT_API_KEY }
}
);
ws.on('open', () => {
console.log('Connected to graduation feed!');
// Subscribe to graduations
ws.send(JSON.stringify({
type: 'subscribe',
channel: 'graduations'
}));
});
ws.on('message', (data) => {
const graduation = JSON.parse(data);
if (graduation.qualityScore > 70) {
console.log('High quality token graduated!', graduation);
// Execute your trading strategy
}
});
Filter by Quality Score
Only fetch graduations that meet your quality threshold.
// Only get high-quality graduations
const response = await fetch(
'https://api.getmegabot.com/v1/analytics/graduations?minQuality=75',
{
headers: {
'X-API-Key': process.env.MEGABOT_API_KEY
}
}
);
const { graduations } = await response.json();
graduations.forEach(token => {
console.log(`${token.symbol}: ${token.qualityScore}/100`);
});
WhaleAPI Usage
Track institutional wallets and smart money movements to discover profitable trading opportunities.
Track a Whale Wallet
Start monitoring a specific wallet for trading activity.
// Start tracking a whale wallet
const response = await fetch(
'https://api.getmegabot.com/v1/whale/track',
{
method: 'POST',
headers: {
'X-API-Key': process.env.MEGABOT_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
wallet: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',
notifyOnTrade: true
})
}
);
const data = await response.json();
console.log('Tracking whale:', data);
Get Whale Portfolio
Analyze the complete portfolio of a tracked wallet.
const portfolio = await fetch(
'https://api.getmegabot.com/v1/whale/portfolio/7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',
{
headers: { 'X-API-Key': process.env.MEGABOT_API_KEY }
}
).then(r => r.json());
console.log(`Total Value: $${portfolio.totalValue.toLocaleString()}`);
console.log(`Confidence Score: ${portfolio.confidenceScore}/100`);
{
"wallet": "7xKXtg2...",
"totalValue": 15000000,
"holdings": [
{
"mint": "So11111111111111111111111111111111111111112",
"symbol": "SOL",
"amount": 100000,
"value": 10000000
},
...
],
"confidenceScore": 85,
"winRate": 72.5,
"profitLoss30d": 45.2
}
Discover Top Whales
Find the most successful whales to follow.
// Find top performing whales
const topWhales = await fetch(
'https://api.getmegabot.com/v1/whale/top?timeframe=7d&minConfidence=75',
{
headers: { 'X-API-Key': process.env.MEGABOT_API_KEY }
}
).then(r => r.json());
topWhales.forEach(whale => {
console.log(
`${whale.wallet}: ${whale.profitLoss}% (${whale.confidenceScore}/100)`
);
});
Building a Trading Bot
Combine all three APIs to build a complete automated trading system.
Complete Trading Bot Example
A production-ready bot that monitors graduations and executes trades.
import { Connection, PublicKey } from '@solana/web3.js';
import WebSocket from 'ws';
const API_KEY = process.env.MEGABOT_API_KEY;
// 1. Initialize RPC connection
const connection = new Connection(
'https://api.getmegabot.com/rpc',
{ httpHeaders: { 'X-API-Key': API_KEY } }
);
// 2. Connect to graduation feed
const ws = new WebSocket('wss://api.getmegabot.com/v1/analytics/stream');
ws.on('message', async (data) => {
const graduation = JSON.parse(data);
// 3. Filter by quality score
if (graduation.qualityScore >= 75 && graduation.safetyCheck === 'SAFE') {
console.log('High quality token detected!', graduation.symbol);
// 4. Execute swap via Jupiter
try {
const tx = await createSwapTransaction(graduation.mint);
const signature = await connection.sendTransaction(tx);
console.log(`Bought ${graduation.symbol}: ${signature}`);
} catch (error) {
console.error('Swap failed:', error);
}
}
});
// Helper function to create swap transaction
async function createSwapTransaction(mint) {
// Your Jupiter swap logic here
// Return signed transaction
}
Whale Copy Trading Bot
Automatically mirror the trades of successful wallets.
async function setupCopyTrading(whaleWallet, copyPercentage = 10) {
// Track whale wallet with webhook
await fetch('https://api.getmegabot.com/v1/whale/track', {
method: 'POST',
headers: {
'X-API-Key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
wallet: whaleWallet,
notifyOnTrade: true,
webhook: 'https://yourserver.com/whale-trade'
})
});
console.log(`Copying ${copyPercentage}% of ${whaleWallet} trades`);
}
// Your webhook endpoint receives trade notifications
app.post('/whale-trade', async (req, res) => {
const trade = req.body;
// Calculate copy size (10% of whale's trade)
const copyAmount = trade.amount * 0.1;
// Execute the same trade
await executeTrade(trade.token, copyAmount);
res.json({ status: 'copied' });
});
Best Practices
Production-ready patterns for reliable, secure, and efficient API usage.
Error Handling
Always implement comprehensive error handling for API requests.
async function makeAPIRequest(endpoint) {
try {
const response = await fetch(endpoint, {
headers: { 'X-API-Key': API_KEY }
});
if (!response.ok) {
if (response.status === 429) {
throw new Error('Rate limit exceeded');
}
if (response.status === 401) {
throw new Error('Invalid API key');
}
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request failed:', error);
// Implement retry logic or fallback
return null;
}
}
Rate Limit Management
Respect API rate limits with proper throttling.
class RateLimiter {
constructor(requestsPerSecond) {
this.queue = [];
this.interval = 1000 / requestsPerSecond;
this.lastRequest = 0;
}
async execute(fn) {
const now = Date.now();
const timeSinceLastRequest = now - this.lastRequest;
if (timeSinceLastRequest < this.interval) {
await new Promise(r =>
setTimeout(r, this.interval - timeSinceLastRequest)
);
}
this.lastRequest = Date.now();
return await fn();
}
}
// Usage
const limiter = new RateLimiter(10); // 10 req/sec
await limiter.execute(() => makeAPIRequest('/endpoint'));
WebSocket Reconnection
Implement automatic reconnection for WebSocket connections.
function connectWebSocket() {
const ws = new WebSocket('wss://api.getmegabot.com/v1/analytics/stream');
ws.on('close', () => {
console.log('WebSocket closed, reconnecting in 5s...');
setTimeout(connectWebSocket, 5000);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
ws.close();
});
return ws;
}
.env file and add it to .gitignore. Use packages like dotenv for Node.js or python-dotenv for Python.
Troubleshooting
Common issues and their solutions to keep your integration running smoothly.
Invalid API Key
Getting 401 errors? Check these common issues.
- Verify you're using the correct header:
X-API-Key - Check that your API key hasn't expired
- Ensure there are no extra spaces in the key
- Confirm you're using the key from the dashboard
// CORRECT
headers: {
'X-API-Key': process.env.MEGABOT_API_KEY
}
// INCORRECT
headers: {
'Authorization': `Bearer ${apiKey}` // Wrong!
}
Rate Limit Exceeded
Getting 429 errors? You've hit your rate limit.
- Check your current usage in the dashboard
- Implement request throttling (see Best Practices)
- Upgrade to a higher tier if needed
- Wait for the rate limit window to reset
RPC Connection Issues
Having trouble connecting to the RPC endpoint?
- Verify you're using the correct endpoint URL
- Check your network/firewall settings
- Ensure you're passing the API key in headers
- Test with a simple curl request first
WebSocket Not Connecting
Can't establish WebSocket connection?
- Use
wss://protocol, notws:// - Check if your hosting provider allows WebSockets
- Implement reconnection logic (see Best Practices)
- Verify your API key is valid
support@getmegabot.com or check the full API documentation for detailed troubleshooting guides.