0% found this document useful (0 votes)
260 views29 pages

Callstatic API para Pumpfun

Uploaded by

Nuno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
260 views29 pages

Callstatic API para Pumpfun

Uploaded by

Nuno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Buy/Sell Transaction Guide

What you'll learn


• How to create buy and sell transaction instructions
• Handle different amount formats (SOL, tokens, percentages)
• Implement proper error handling
• Send and confirm transactions
Introduction
This guide explains how to create and execute buy/sell transactions on Pump.Fun
through the Transaction API. You'll learn how to structure requests, handle
responses, and manage transactions effectively.
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits vary by subscription tier
Transaction Parameters
• Transaction Interface
interface CreateTransaction {
signer: string; // Your wallet public key
transactionType: 'Buy' | 'Sell'; // Transaction type
mint: string; // Token mint address
amount: string; // Amount to trade
slippage: number; // Maximum slippage tolerance
priorityFee: number; // Priority fee in mLamports
}

Basic Usage Examples


1. Buy Transaction
Create a buy transaction for a specific token:
const buyRequest = {
signer: "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
transactionType: "Buy",
mint: "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
amount: "100000000", // 0.1 SOL
slippage: 1.5, // 1.5% slippage
priorityFee: 1000, // 1000 mLamports
};

2. Sell Transaction
Create a sell transaction using percentage:
const sellRequest = {
signer: "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
transactionType: "Sell",
mint: "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
amount: "50%", // Sell 50% of holdings
slippage: 3.5, // 3.5% slippage
priorityFee: 1000, // 1000 mLamports
};

Complete Implementation
• TypeScript
import {
Connection,
VersionedTransaction,
VersionedMessage,
Keypair
} from '@solana/web3.js';
import bs58 from 'bs58';

class PumpFunTradeClient {
private connection: Connection;
private apiKey: string;

constructor(rpcEndpoint: string, apiKey: string) {


this.connection = new Connection(rpcEndpoint, 'confirmed');
this.apiKey = apiKey;
}

async createTradeTransaction(
signer: string,
transactionType: 'Buy' | 'Sell',
mint: string,
amount: string,
slippage: number,
priorityFee: number
) {
const response = await fetch(
'https://api.callstaticrpc.com/pumpfun/v1/transactions/getInstruction',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
signer,
transactionType,
mint,
amount,
slippage,
priorityFee
})
}
);

if (!response.ok) {
throw new Error(`API error: ${response.statusText}`);
}

const result = await response.json();


if (!result.success || !result.data) {
throw new Error('Failed to generate transaction');
}
const message = VersionedMessage.deserialize(
new Uint8Array(result.data)
);

const transaction = new VersionedTransaction(message);


return transaction;
}

async sendTransaction(transaction: VersionedTransaction, privateKey: string) {


const signerKeyPair = Keypair.fromSecretKey(bs58.decode(privateKey));
transaction.sign([signerKeyPair]);

const signature = await this.connection.sendTransaction(transaction);


return signature;
}

}
Error Handling
The API returns standard error messages:
try {
const transaction = await client.createTradeTransaction(/* params */);
} catch (error) {
if (error.message.includes('Authentication')) {
console.error('Invalid API key');
} else if (error.message.includes('Invalid parameters')) {
console.error('Invalid transaction parameters');
} else {
console.error('Unknown error:', error);
}
}

Best Practices
1. Transaction Safety
o Always verify transaction contents before signing
o Use appropriate slippage for market conditions
o Monitor transaction status after sending
2. Error Management
o Implement proper error handling
o Use try-catch blocks consistently
o Handle network errors gracefully
3. Security
o Never expose private keys
o Store API keys securely
o Use environment variables for sensitive data
Next Steps
Now that you understand how to create trade transactions, you can:
1. 🚀 Build a trading interface
2. 📊 Implement automated trading strategies
3. ⚡ Create a trading bot
4. 🔄 Monitor transaction status

Token Creation Guide


What you'll learn
• How to create token metadata on IPFS
• Upload token images and metadata
• Create new tokens on Pump.Fun
• Set up initial liquidity
Introduction
This guide explains the complete token creation process including metadata storage
and token deployment. The process involves two main steps:
1. Creating token metadata on IPFS
2. Deploying the token using the metadata URI
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits vary by subscription tier
Token Creation Process
Step 1: Create Token Metadata
First, upload your token's image and metadata to IPFS:
• TypeScript
• Python
import { promises as fs } from 'fs';

async function createTokenMetadata(


name: string,
symbol: string,
description: string,
imagePath: string,
socials: {
twitter?: string,
telegram?: string,
website?: string
}
) {
const formData = new FormData();

// Add image file


const imageFile = await fs.openAsBlob(imagePath);
formData.append("file", imageFile);

// Add metadata
formData.append("name", name);
formData.append("symbol", symbol);
formData.append("description", description);
formData.append("showName", "true");

// Add social links if provided


if (socials.twitter) formData.append("twitter", socials.twitter);
if (socials.telegram) formData.append("telegram", socials.telegram);
if (socials.website) formData.append("website", socials.website);

const response = await fetch("https://Pump.Fun/api/ipfs", {


method: "POST",
body: formData,
});

if (!response.ok) {
throw new Error(`Failed to upload metadata: ${response.statusText}`);
}

return await response.json();

Step 2: Deploy Token


After creating the metadata, use the returned URI to deploy your token:
• TypeScript
• Python
import {
Connection,
VersionedTransaction,
VersionedMessage,
Keypair
} from '@solana/web3.js';
import bs58 from 'bs58';

class PumpFunTokenCreator {
private apiKey: string;
private connection: Connection;

constructor(rpcEndpoint: string, apiKey: string) {


this.connection = new Connection(rpcEndpoint, 'confirmed');
this.apiKey = apiKey;
}

async deployToken(
signerKeypair: Keypair,
name: string,
symbol: string,
description: string,
imagePath: string,
socials: {
twitter?: string,
telegram?: string,
website?: string
} = {},
initialLiquidityLamports: string = "0",
slippage: number = 1.5,
priorityFeeMicroLamports: number = 1000
) {
// Create mint keypair
const mintKeypair = Keypair.generate();

// Upload metadata and get URI


const metadataResponse = await createTokenMetadata(
name,
symbol,
description,
imagePath,
socials
);

// Create token with metadata URI


const response = await fetch(

'https://api.callstaticrpc.com/pumpfun/v1/transactions/getCreateInstruction',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
signer: signerKeypair.publicKey.toString(),
tokenMetadata: {
name,
symbol,
uri: metadataResponse.metadataUri
},
mint: mintKeypair.publicKey.toString(),
amount: initialLiquidityLamports,
slippage,
priorityFee: priorityFeeMicroLamports
})
}
);

if (!response.ok) {
throw new Error(`API error: ${response.statusText}`);
}

const result = await response.json();


if (!result.success || !result.data) {
throw new Error('Failed to generate transaction');
}

const message = VersionedMessage.deserialize(


new Uint8Array(result.data)
);

const transaction = new VersionedTransaction(message);

transaction.sign([signerKeypair]);

const signature = await this.connection.sendTransaction(transaction);

return {
signature,
mint: mintKeypair.publicKey.toString(),
metadataUri: metadataResponse.metadataUri
};
}

Complete Usage Example


Here's how to create a token with all metadata and initial liquidity:
• TypeScript
• Python
const creator = new PumpFunTokenCreator(
'YOUR_RPC_ENDPOINT',
'YOUR_API_KEY'
);

// Create token with metadata and initial liquidity


const result = await creator.deployToken(
Keypair.fromSecretKey(bs58.decode('your-wallet-private-key')),
'PPTest',
'TEST',
'This is an example token created via Pump.Fun',
'./example.png',
{
twitter: 'https://x.com/example',
telegram: 'https://t.me/example',
website: 'https://example.com'
},
'1000000000', // 1 SOL initial liquidity
1.5, // 1.5% slippage
1000 // 1000 microlamports priority fee
);

console.log(`Transaction: https://solscan.io/tx/${result.signature}`);
console.log(`Token Mint: ${result.mint}`);
console.log(`Metadata URI: ${result.metadataUri}`);

Best Practices
1. Metadata Preparation
o Use high-quality images
o Provide comprehensive token descriptions
o Include relevant social links
o Verify metadata before deployment
2. Token Deployment
o Store mint address and metadata URI
o Monitor transaction status
o Implement proper error handling
o Consider initial liquidity carefully
3. Security
o Never share private keys
o Store API keys securely
o Validate all input data
o Use environment variables for sensitive data
Next Steps
Now that you understand the complete token creation process, you can:
1. 🚀 Prepare token metadata
2. 📊 Deploy your token
3. 💧 Add initial liquidity
4. 🔄 Monitor token performance

Historical Token Deployments API


What you'll learn
• How to fetch historical token deployment data
• Query deployments by wallet address
• Implement pagination for large datasets
• Analyze deployment patterns and metadata
Introduction
The Historical Token Deployments API enables you to retrieve and analyze past token
deployment data. This API is specifically designed for historical analysis - for
real-time deployment notifications, please refer to our WebSocket Streams API.
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits and data access vary by subscription tier
Authentication
All requests require a Bearer token in UUID format:
Authorization: Bearer your-api-key-here

Base URL
https://api.callstaticrpc.com/pumpfun/v1

Data Structure
The API returns detailed information about token deployments:
• Response Structure
{
"success": true,
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"deployer": "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
"deploy_timestamp": 1679616000000,
"mint": "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
"name": "Sample Token",
"symbol": "SMPL",
"decimals": 9,
"initial_supply": 1000000000000,
"total_supply": 1000000000000,
"description": "A sample token deployment",
"mint_authority": "AaA9aA3aA6aA2aA8aA4aA7aAa1aA5aA9aA3aA6aA2a",
"freeze_authority": "AaA7aA1aA4aA8aA2aA6aA9aAa3aA7aA1aA4aA8aA5a",
"twitter": "@sample_token",
"telegram": "t.me/sample_token",
"website": "https://sample-token.com",
"uri": "https://arweave.net/sample-token-metadata",
"image_uri": "https://arweave.net/sample-token-image",
"is_complete": true,
"complete_timestamp": 1679616100000
}
],
"has_more": false,
"total": 1
}

• TypeScript
• JavaScript
• Python
import axios from 'axios';

interface TokenDeployment {
id: string;
deployer: string;
deploy_timestamp: number;
mint: string;
name: string;
symbol: string;
decimals: number;
initial_supply: number;
total_supply: number;
description: string;
mint_authority: string;
freeze_authority: string;
twitter?: string;
telegram?: string;
website?: string;
uri: string;
image_uri: string;
is_complete: boolean;
complete_timestamp?: number;
}

interface PaginatedResponse {
success: boolean;
data: TokenDeployment[];
has_more: boolean;
total: number;
}

class TokenHistoricalClient {
private readonly baseUrl = 'https://api.callstaticrpc.com/pumpfun/v1';

constructor(private readonly apiKey: string) {}

async getWalletDeployments(params: {
wallet: string;
limit?: number;
offset?: number;
}): Promise<PaginatedResponse> {
const response = await axios.get(`${this.baseUrl}/historical/deployments`,
{
headers: {
Authorization: `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
params: {
wallet: params.wallet,
limit: params.limit,
offset: params.offset
}
});

return response.data;
}

async getAllDeployments(wallet: string): Promise<TokenDeployment[]> {


let allDeployments: TokenDeployment[] = [];
let offset = 0;
const limit = 100;

while (true) {
const response = await this.getWalletDeployments({
wallet,
limit,
offset
});

allDeployments = [...allDeployments, ...response.data];

if (!response.has_more) break;
offset += limit;
}

return allDeployments;
}

[Analysis scenarios section with properly indented code...]


• TypeScript
async function analyzeDeploymentTimeline(wallet: string) {
const client = new TokenHistoricalClient('your-api-key');
const deployments = await client.getAllDeployments(wallet);

// Group deployments by month


const monthlyDeployments = deployments.reduce((acc, dep) => {
const month = new Date(dep.deploy_timestamp).toISOString().slice(0, 7);
acc[month] = (acc[month] || 0) + 1;
return acc;
}, {});

return {
totalDeployments: deployments.length,
deploymentsByMonth: monthlyDeployments,
firstDeployment: new Date(Math.min(...deployments.map(d =>
d.deploy_timestamp))),
lastDeployment: new Date(Math.max(...deployments.map(d =>
d.deploy_timestamp))),
completionRate: deployments.filter(d => d.is_complete).length /
deployments.length
};
}

• TypeScript
async function analyzeSocialPresence(wallet: string) {
const client = new TokenHistoricalClient('your-api-key');
const deployments = await client.getAllDeployments(wallet);

return {
totalTokens: deployments.length,
withTwitter: deployments.filter(d => d.twitter).length,
withTelegram: deployments.filter(d => d.telegram).length,
withWebsite: deployments.filter(d => d.website).length,
withAllSocial: deployments.filter(d =>
d.twitter && d.telegram && d.website
).length,
socialUrls: deployments.map(d => ({
name: d.name,
twitter: d.twitter,
telegram: d.telegram,
website: d.website
}))
};
}

Error Handling
The API returns standard HTTP status codes:
Status Code Description
200 Successful response
400 Bad request
401 Unauthorized - Invalid or missing bearer token
500 Internal server error
Best Practices
1. Implement Pagination
o Use the limit and offset parameters for large datasets
o Default to reasonable page sizes (e.g., 100 records)
o Handle the has_more flag to determine if more data is available
2. Error Handling
try {
const deployments = await client.getWalletDeployments({
wallet: "AaA2...",
});
} catch (error) {
if (error.response?.status === 401) {
console.error("Invalid API key");
} else if (error.response?.status === 400) {
console.error("Invalid parameters");
}
}

Next Steps
Now that you understand how to analyze historical token deployment data, you can:
1. 📊 Build deployment analytics dashboards
2. 🔍 Track wallet deployment patterns
3. 📈 Create token metadata analysis tools
4. Monitor social media presence

Market Data Guide


What you'll learn
• How to fetch token market data
• Track price and market cap information
• Monitor bonding curve progress
• Implement real-time price tracking
Introduction
This guide explains how to retrieve and monitor token market data from Pump.Fun
using the Market Data API. You can track prices, market caps, and bonding progress
for any token.
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits vary by subscription tier
Market Data Structure
• Market Data Interface
interface TokenMarketData {
price_usd: string; // Current USD price
price_sol: string; // Current SOL price
current_market_cap: string; // Current market capitalization
bonding_market_cap: string; // Total bonding curve market cap
bonding_progress: number; // Progress as decimal (0-1)
}

interface MarketDataResponse {
success: boolean;
data: TokenMarketData;
}

Implementation Example
• TypeScript
• Python
class PumpFunMarketDataClient {
private apiKey: string;

constructor(apiKey: string) {
this.apiKey = apiKey;
}

async getTokenMarketData(tokenMint: string): Promise<TokenMarketData> {


const response = await fetch(
`https://api.callstaticrpc.com/pumpfun/v1/token/marketData?token=$
{tokenMint}`,
{
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
}
);

if (!response.ok) {
throw new Error(`API error: ${response.statusText}`);
}

const result = await response.json();


if (!result.success || !result.data) {
throw new Error('Failed to fetch market data');
}

return result.data;
}

// Real-time price monitoring


async monitorTokenPrice(
tokenMint: string,
callback: (data: TokenMarketData) => void,
interval: number = 60000, // Default 1 minute
errorCallback?: (error: Error) => void
): Promise<() => void> {
let isRunning = true;

const monitor = async () => {


while (isRunning) {
try {
const data = await this.getTokenMarketData(tokenMint);
callback(data);
await new Promise(resolve => setTimeout(resolve, interval));
} catch (error) {
if (errorCallback) {
errorCallback(error as Error);
}
await new Promise(resolve => setTimeout(resolve, interval));
}
}
};

monitor();
return () => { isRunning = false; };
}

// Price change monitoring


async monitorPriceChanges(
tokenMint: string,
threshold: number, // Percentage change threshold
callback: (change: number, data: TokenMarketData) => void,
interval: number = 60000
): Promise<() => void> {
let lastPrice: number | null = null;

return this.monitorTokenPrice(
tokenMint,
(data) => {
const currentPrice = parseFloat(data.price_usd);
if (lastPrice !== null) {
const changePercent = ((currentPrice - lastPrice) / lastPrice)
* 100;
if (Math.abs(changePercent) >= threshold) {
callback(changePercent, data);
}
}
lastPrice = currentPrice;
},
interval
);
}
}

Usage Examples
Basic Market Data Fetch
• TypeScript
• Python
const client = new PumpFunMarketDataClient('YOUR_API_KEY');

try {
const data = await client.getTokenMarketData('TOKEN_MINT_ADDRESS');

console.log('Token Market Data:');


console.log(`Price (USD): $${data.price_usd}`);
console.log(`Price (SOL): ${data.price_sol} SOL`);
console.log(`Market Cap: $${data.current_market_cap}`);
console.log(`Bonding Progress: ${data.bonding_progress * 100}%`);
} catch (error) {
console.error('Error fetching market data:', error);
}

Real-Time Price Monitoring


• TypeScript
• Python
const client = new PumpFunMarketDataClient('YOUR_API_KEY');

// Monitor price with 5% change threshold


const stopMonitoring = await client.monitorPriceChanges(
'TOKEN_MINT_ADDRESS',
5.0, // 5% threshold
(changePercent, data) => {
console.log(`Price changed by ${changePercent.toFixed(2)}%`);
console.log(`New price: $${data.price_usd}`);
},
30000 // Check every 30 seconds
);

// Stop monitoring after 1 hour


setTimeout(stopMonitoring, 3600000);

Bonding Progress Monitoring


• TypeScript
• Python
const client = new PumpFunMarketDataClient('YOUR_API_KEY');

const stopMonitoring = await client.monitorTokenPrice(


'TOKEN_MINT_ADDRESS',
(data) => {
if (data.bonding_progress >= 95) { // 95% complete
console.log('Bonding curve near completion!');
console.log(`Progress: ${(data.bonding_progress).toFixed(2)}%`);
console.log(`Current Market Cap: $${data.current_market_cap}`);
}
},
60000 // Check every minute
);

Best Practices
1. Rate Limiting
o Respect API rate limits
o Use appropriate monitoring intervals
o Implement exponential backoff for errors
2. Data Processing
o Handle string-to-number conversions carefully
o Validate data before processing
o Store historical data if needed
3. Error Handling
o Implement proper error callbacks
o Handle network issues gracefully
o Log errors appropriately
Common Use Cases
1. Price Alerts
o Monitor significant price changes
o Track price thresholds
o Set up notification systems
2. Market Analysis
o Track market cap changes
o Monitor bonding curve progress
o Analyze price trends
3. Trading Automation
o Trigger trades based on price movements
o Monitor liquidity levels
o Track market conditions
Next Steps
Now that you understand market data monitoring, you can:
1. 📊 Set up price alerts
2. 📈 Track market trends
3. 🤖 Build trading bots
4. 📉 Monitor multiple tokens

Token Metadata API


What you'll learn
• How to fetch metadata for any token
• Understanding token deployment status and bonding curve completion
• Tracking Raydium deployment status
• Accessing token social and authority details
Introduction
The Token Metadata API enables you to retrieve comprehensive metadata about token
deployments, including bonding curve completion status and Raydium deployment
information. This API is designed for tracking token launches and accessing
associated deployment details.
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits and data access vary by subscription tier
Authentication
All requests require a Bearer token in UUID format:
Authorization: Bearer your-api-key-here

Base URL
https://api.callstaticrpc.com/pumpfun/v1

Data Structure
The API returns detailed metadata about token deployments:
• Response Structure
{
"success": true,
"data": {
"id": "dep_123456789",
"deployer": "AaA9aA3aA6aA2aA8aA4aA7aAa1aA5aA9aA3aA6aA2a",
"deploy_timestamp": 1679529600000,
"mint": "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
"name": "Sample Token",
"symbol": "SMPL",
"decimals": 9,
"initial_supply": 1000000000000,
"total_supply": 1000000000000, // Always 1 billion (1,000,000,000) tokens
"description": "A sample token for demonstration purposes",
"mint_authority": "AaA9aA3aA6aA2aA8aA4aA7aAa1aA5aA9aA3aA6aA2a",
"freeze_authority": "AaA7aA1aA4aA8aA2aA6aA9aAa3aA7aA1aA4aA8aA5a",
"twitter": "@sampletoken",
"telegram": "https://t.me/sampletoken",
"website": "https://sampletoken.com",
"uri": "https://arweave.net/abc123",
"image_uri": "https://arweave.net/xyz789",
"is_complete": true, // Indicates bonding curve filled and Raydium
deployment
"complete_timestamp": 1679529605000 // When Raydium deployment completed
}
}

• TypeScript
• Python
import axios from 'axios';

interface TokenMetadata {
id: string;
deployer: string;
deploy_timestamp: number;
mint: string;
name: string;
symbol: string;
decimals: number;
initial_supply: number; // Always 1 billion
total_supply: number; // Always 1 billion
description: string;
mint_authority: string;
freeze_authority: string;
twitter?: string;
telegram?: string;
website?: string;
uri: string;
image_uri: string;
is_complete: boolean; // Bonding curve and Raydium status
complete_timestamp?: number;
}

interface MetadataResponse {
success: boolean;
data: TokenMetadata;
}

class TokenMetadataClient {
private readonly baseUrl = 'https://api.callstaticrpc.com/pumpfun/v1';

constructor(private readonly apiKey: string) {}

async getTokenMetadata(mint: string): Promise<MetadataResponse> {


const response = await axios.get(`${this.baseUrl}/token/metadata`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
params: { token:mint }
});

return response.data;
}

Error Handling
The API returns standard HTTP status codes:
Status Code Description
200 Successful response
400 Bad request
401 Unauthorized - Invalid or missing bearer token
500 Internal server error

oken Volume API


What you'll learn
• How to fetch volume data for any token
• Analyzing buy/sell ratios and volume trends
• Calculate volume deltas and momentum
• Convert lamports to SOL for better readability
Introduction
The Token Volume API enables you to retrieve and analyze trading volume data for
any token. You can track buy/sell patterns, analyze volume trends across multiple
timeframes, and monitor trading activity. All volume values are denominated in SOL
and formatted in lamports (1 SOL = 1,000,000,000 lamports).
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits and data access vary by subscription tier
Authentication
All requests require a Bearer token in UUID format:
Authorization: Bearer your-api-key-here

Base URL
https://api.callstaticrpc.com/pumpfun/v1

Data Structure
The API returns volume data with multiple time windows:
• Response Structure
{
"success": true,
"data": {
"token": "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
"name": "Sample Token",
"symbol": "STKN",
// Short-term volumes
"buy_volume_1m": "1000000000", // 1 SOL in buys last minute
"buy_volume_5m": "5000000000",
"buy_volume_15m": "15000000000",
"buy_volume_30m": "30000000000",
// Medium-term volumes
"buy_volume_1h": "60000000000",
"buy_volume_4h": "240000000000",
// Long-term volumes
"buy_volume_24h": "1440000000000",
"buy_volume_1w": "10080000000000",
// Sell volumes follow same pattern
"sell_volume_1m": "900000000",
"sell_volume_5m": "4500000000",
"sell_volume_15m": "13500000000",
"sell_volume_30m": "27000000000",
"sell_volume_1h": "54000000000",
"sell_volume_4h": "216000000000",
"sell_volume_24h": "1296000000000",
"sell_volume_1w": "9072000000000",
// Last trade timestamps
"last_buy_timestamp": 1679529600000,
"last_sell_timestamp": 1679529600000
}
}

Implementation
Here's how to implement volume analysis in your application:
• TypeScript
• Python
import axios from 'axios';

interface TokenVolume {
token: string;
name: string;
symbol: string;
buy_volume_1m: string;
buy_volume_5m: string;
buy_volume_15m: string;
buy_volume_30m: string;
buy_volume_1h: string;
buy_volume_4h: string;
buy_volume_24h: string;
buy_volume_1w: string;
sell_volume_1m: string;
sell_volume_5m: string;
sell_volume_15m: string;
sell_volume_30m: string;
sell_volume_1h: string;
sell_volume_4h: string;
sell_volume_24h: string;
sell_volume_1w: string;
last_buy_timestamp: number;
last_sell_timestamp: number;
}

class VolumeAnalyzer {
private readonly LAMPORTS_PER_SOL = 1_000_000_000;

// Convert lamports string to SOL number


private lamportsToSol(lamports: string): number {
return parseInt(lamports) / this.LAMPORTS_PER_SOL;
}

// Calculate buy/sell ratio for a timeframe


calculateBuySellRatio(volume: TokenVolume, timeframe: string): number {
const buyKey = `buy_volume_${timeframe}` as keyof TokenVolume;
const sellKey = `sell_volume_${timeframe}` as keyof TokenVolume;
const buyVolume = this.lamportsToSol(volume[buyKey] as string);
const sellVolume = this.lamportsToSol(volume[sellKey] as string);

return sellVolume === 0 ? buyVolume : buyVolume / sellVolume;


}

// Calculate volume deltas between timeframes


calculateVolumeTrend(volume: TokenVolume): {
shortTerm: number; // 5m vs 1h
mediumTerm: number; // 1h vs 4h
longTerm: number; // 4h vs 24h
} {
return {
shortTerm: this.lamportsToSol(volume.buy_volume_5m) / 12 -
this.lamportsToSol(volume.buy_volume_1h) / 12,
mediumTerm: this.lamportsToSol(volume.buy_volume_1h) / 4 -
this.lamportsToSol(volume.buy_volume_4h) / 4,
longTerm: this.lamportsToSol(volume.buy_volume_4h) / 6 -
this.lamportsToSol(volume.buy_volume_24h) / 6
};
}

// Analyze overall volume momentum


analyzeVolumeMomentum(volume: TokenVolume): {
momentum: 'increasing' | 'decreasing' | 'stable';
strength: number;
} {
const trends = this.calculateVolumeTrend(volume);
const avgTrend = (trends.shortTerm + trends.mediumTerm + trends.longTerm) /
3;

return {
momentum: avgTrend > 0.1 ? 'increasing' :
avgTrend < -0.1 ? 'decreasing' : 'stable',
strength: Math.abs(avgTrend)
};
}

// Get time since last trade


getTimeSinceLastTrade(volume: TokenVolume): {
lastBuy: number;
lastSell: number;
} {
const now = Date.now();
return {
lastBuy: now - volume.last_buy_timestamp,
lastSell: now - volume.last_sell_timestamp
};
}

Analysis Techniques
1. Volume Ratios
Compare buy and sell volumes to identify trading patterns:
• Buy/Sell ratio > 1: More buying pressure
• Buy/Sell ratio < 1: More selling pressure
• Track ratios across timeframes to spot trends
2. Volume Deltas
Calculate volume changes between timeframes:
• Short-term: 5m vs 1h (normalized)
• Medium-term: 1h vs 4h (normalized)
• Long-term: 4h vs 24h (normalized)
3. Volume Momentum
Analyze volume trends to determine market momentum:
• Increasing: Higher recent volume
• Decreasing: Lower recent volume
• Stable: Consistent volume
4. Trade Timing
Monitor time since last trades:
• Recent trades indicate active trading
• Long gaps may indicate low liquidity
• Compare buy vs sell timing patterns
Error Handling
The API returns standard HTTP status codes:
Status Code Description
200 Successful response
400 Bad request
401 Unauthorized - Invalid or missing bearer token
500 Internal server error

Historical Wallet Trades API


What you'll learn
• How to fetch historical trading data for specific wallets
• Query trade history with pagination
• Analyze trading patterns and metrics
• Track wallet trading activity over time
Introduction
The Historical Wallet Trades API enables you to retrieve and analyze past trading
activity for any wallet address. This API is specifically designed for historical
analysis of trading patterns, price movements, and trading behavior at the wallet
level.
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits and data access vary by subscription tier
Authentication
All requests require a Bearer token in UUID format:
Authorization: Bearer your-api-key-here

Base URL
https://api.callstaticrpc.com/pumpfun/v1

Data Structure
The API returns detailed information about wallet trades:
• Response Structure
{
"success": true,
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"hash": "CcC5cC2cC8cC1cC7cC3cC9cC4cC6cC2cC8cC5cC1cC7cC4c",
"timestamp": 1679616000000,
"sol_amount": 1000000000,
"token_amount": 50000000000,
"token": "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
"price": 0.02,
"dex": 1,
"buyer": "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
"virtual_sol_reserves": 100000000000,
"virtual_token_reserves": 5000000000000,
"real_sol_reserves": 98000000000,
"real_token_reserves": 5100000000000,
"is_buy": true
}
],
"has_more": false,
"total": 1
}

• TypeScript
• Python
import axios from 'axios';

interface Trade {
id: string;
hash: string;
timestamp: number;
sol_amount: number;
token_amount: number;
token: string;
price: number;
dex: 1 | 2; // 1 for PumpFun, 2 for Raydium
buyer: string;
virtual_sol_reserves: number;
virtual_token_reserves: number;
real_sol_reserves: number;
real_token_reserves: number;
is_buy: boolean;
}

interface PaginatedResponse {
success: boolean;
data: Trade[];
has_more: boolean;
total: number;
}

class WalletTradesClient {
private readonly baseUrl = 'https://api.callstaticrpc.com/pumpfun/v1';

constructor(private readonly apiKey: string) {}

async getWalletTrades(params: {
wallet: string;
limit?: number;
offset?: number;
}): Promise<PaginatedResponse> {
const response = await
axios.get(`${this.baseUrl}/historical/trades/byWallet`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
params
});
return response.data;
}

async getAllWalletTrades(wallet: string): Promise<Trade[]> {


let allTrades: Trade[] = [];
let offset = 0;
const limit = 100;

while (true) {
const response = await this.getWalletTrades({
wallet,
limit,
offset
});

allTrades = [...allTrades, ...response.data];

if (!response.has_more) break;
offset += limit;
}

return allTrades;
}

Analysis Examples
Here are some common analysis scenarios using the wallet trades data:
• TypeScript
async function analyzeWalletActivity(wallet: string) {
const client = new WalletTradesClient('your-api-key');
const trades = await client.getAllWalletTrades(wallet);

return {
totalTrades: trades.length,
totalVolume: trades.reduce((sum, trade) => sum + trade.sol_amount, 0),
tokenInteractions: new Set(trades.map(t => t.token)).size,
tradingFrequency: {
buys: trades.filter(t => t.is_buy).length,
sells: trades.filter(t => !t.is_buy).length
},
dexUsage: {
pumpfun: trades.filter(t => t.dex === 1).length,
raydium: trades.filter(t => t.dex === 2).length
}
};
}

async function analyzeTokenPreferences(wallet: string) {


const client = new WalletTradesClient('your-api-key');
const trades = await client.getAllWalletTrades(wallet);

const tokenStats = trades.reduce((acc, trade) => {


if (!acc[trade.token]) {
acc[trade.token] = {
totalVolume: 0,
tradeCount: 0,
avgPrice: 0
};
}

acc[trade.token].totalVolume += trade.sol_amount;
acc[trade.token].tradeCount++;
acc[trade.token].avgPrice =
(acc[trade.token].avgPrice * (acc[trade.token].tradeCount - 1) +
trade.price)
/ acc[trade.token].tradeCount;

return acc;
}, {});

return tokenStats;

Error Handling
The API returns standard HTTP status codes:
Status Code Description
200 Successful response
400 Bad request
401 Unauthorized - Invalid or missing bearer token
500 Internal server error
Best Practices
1. Implement Pagination
o Use the limit and offset parameters for large datasets
o Default to reasonable page sizes (e.g., 100 records)
o Handle the has_more flag to determine if more data is available
2. Error Handling
try {
const trades = await client.getWalletTrades({
wallet: "AaA2...",
});
} catch (error) {
if (error.response?.status === 401) {
console.error("Invalid API key");
} else if (error.response?.status === 400) {
console.error("Invalid parameters");
}
}

3. Rate Limiting
o Implement exponential backoff for retry logic
o Monitor your API usage through the dashboard
o Consider caching frequently accessed data
Next Steps
Now that you understand how to analyze wallet trading data, you can:
1. 📊 Build wallet activity dashboards
2. 🔍 Track trading patterns and preferences
3. 📈 Monitor trading frequency and volume
4. Analyze token interactions

Historical Token Trades API


What you'll learn
• How to fetch historical trading data for specific tokens
• Query trade history with pagination
• Analyze trading patterns and metrics
• Track liquidity changes over time
Introduction
The Historical Token Trades API enables you to retrieve and analyze past trading
activity for any token. This API is specifically designed for historical analysis
of trading patterns, price movements, and liquidity changes.
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits and data access vary by subscription tier
Authentication
All requests require a Bearer token in UUID format:
Authorization: Bearer your-api-key-here

Base URL
https://api.callstaticrpc.com/pumpfun/v1

Data Structure
The API returns detailed information about token trades:
• Response Structure
{
"success": true,
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"hash": "CcC5cC2cC8cC1cC7cC3cC9cC4cC6cC2cC8cC5cC1cC7cC4c",
"timestamp": 1679616000000,
"sol_amount": 1000000000,
"token_amount": 50000000000,
"token": "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB",
"price": 0.02,
"dex": 1,
"buyer": "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
"virtual_sol_reserves": 100000000000,
"virtual_token_reserves": 5000000000000,
"real_sol_reserves": 98000000000,
"real_token_reserves": 5100000000000,
"is_buy": true
}
],
"has_more": false,
"total": 1
}

• TypeScript
• Python
import axios from 'axios';

interface Trade {
id: string;
hash: string;
timestamp: number;
sol_amount: number;
token_amount: number;
token: string;
price: number;
dex: 1 | 2; // 1 for PumpFun, 2 for Raydium
buyer: string;
virtual_sol_reserves: number;
virtual_token_reserves: number;
real_sol_reserves: number;
real_token_reserves: number;
is_buy: boolean;
}

interface PaginatedResponse {
success: boolean;
data: Trade[];
has_more: boolean;
total: number;
}

class TokenTradesClient {
private readonly baseUrl = 'https://api.callstaticrpc.com/pumpfun/v1';

constructor(private readonly apiKey: string) {}

async getTokenTrades(params: {
token: string;
limit?: number;
offset?: number;
}): Promise<PaginatedResponse> {
const response = await
axios.get(`${this.baseUrl}/historical/trades/byToken`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
params
});

return response.data;
}

async getAllTokenTrades(token: string): Promise<Trade[]> {


let allTrades: Trade[] = [];
let offset = 0;
const limit = 100;

while (true) {
const response = await this.getTokenTrades({
token,
limit,
offset
});

allTrades = [...allTrades, ...response.data];

if (!response.has_more) break;
offset += limit;
}

return allTrades;
}

}
Analysis Examples
Here are some common analysis scenarios using the historical trades data:
• TypeScript
async function analyzePriceMovement(token: string) {
const client = new TokenTradesClient('your-api-key');
const trades = await client.getAllTokenTrades(token);

return {
totalTrades: trades.length,
volumeInSol: trades.reduce((sum, trade) => sum + trade.sol_amount, 0),
averagePrice: trades.reduce((sum, trade) => sum + trade.price, 0) /
trades.length,
priceRange: {
min: Math.min(...trades.map(t => t.price)),
max: Math.max(...trades.map(t => t.price))
},
buyCount: trades.filter(t => t.is_buy).length,
sellCount: trades.filter(t => !t.is_buy).length
};
}

async function analyzeLiquidityChanges(token: string) {


const client = new TokenTradesClient('your-api-key');
const trades = await client.getAllTokenTrades(token);

return trades.map(trade => ({


timestamp: new Date(trade.timestamp),
virtualLiquidity: {
sol: trade.virtual_sol_reserves,
token: trade.virtual_token_reserves
},
realLiquidity: {
sol: trade.real_sol_reserves,
token: trade.real_token_reserves
},
divergence: {
sol: trade.virtual_sol_reserves - trade.real_sol_reserves,
token: trade.virtual_token_reserves - trade.real_token_reserves
}
}));

Error Handling
The API returns standard HTTP status codes:
Status Code Description
200 Successful response
400 Bad request
401 Unauthorized - Invalid or missing bearer token
500 Internal server error
Best Practices
1. Implement Pagination
o Use the limit and offset parameters for large datasets
o Default to reasonable page sizes (e.g., 100 records)
o Handle the has_more flag to determine if more data is available
2. Error Handling
try {
const trades = await client.getTokenTrades({
token: "BbB3...",
});
} catch (error) {
if (error.response?.status === 401) {
console.error("Invalid API key");
} else if (error.response?.status === 400) {
console.error("Invalid parameters");
}
}

3. Rate Limiting
o Implement exponential backoff for retry logic
o Monitor your API usage through the dashboard
o Consider caching frequently accessed data
Next Steps
Now that you understand how to analyze historical token trading data, you can:
1. 📊 Build trading analytics dashboards
2. 🔍 Track price movements and volatility
3. 📈 Monitor liquidity changes
4. Analyze trading patterns

Real-Time Token Event Filtering Guide


What you'll learn
• How to filter token events in real-time
• Implement basic and advanced filtering strategies
• Combine multiple filters effectively
Introduction
This guide explains all available filtering options for token events. You can use
these filters across any subscription type (Deployment, Trade, or Completed
events).
Access Requirements
• Valid API key (visit https://app.callstatic.com for tier information)
• Rate limits and data access vary by subscription tier
Available Filters
• Filter Interface
interface EventFilters {
// Basic Filters - Currently Active
mint?: string; // Filter by token's mint address
deployer?: string; // Filter by deployer's wallet address
name?: string; // Filter by token name
symbol?: string; // Filter by token symbol

// Advanced Filters - Coming Soon


count?: number; // [UPCOMING] Filter for similar tokens launched in
short timeframe
narrative?: string; // [UPCOMING] Filter by token narrative/theme
tweet?: string; // [UPCOMING] Filter by tweet URL

Basic Filter Usage


1. Mint Address Filter
Track specific tokens by their mint address:
const subscribeMessage = {
type: "Subscribe",
payload: {
sub_type: "Deployment",
filter: {
mint: "BbB3bB7bB2bB9bB4bB8bB1bBb5bB2bB6bB3bB9bB4bB"
}
}
};

2. Deployer Filter
Monitor deployments from specific wallets:
const subscribeMessage = {
type: "Subscribe",
payload: {
sub_type: "Deployment",
filter: {
deployer: "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
},
},
};

3. Name Filter
Track tokens by name pattern:
const subscribeMessage = {
type: "Subscribe",
payload: {
sub_type: "Deployment",
filter: {
name: "AI", // Will match tokens containing "AI"
},
},
};

4. Symbol Filter
Monitor specific token symbols:
const subscribeMessage = {
type: "Subscribe",
payload: {
sub_type: "Deployment",
filter: {
symbol: "BTC", // Will match tokens with "BTC" in symbol
},
},
};

Combining Filters
You can combine multiple active filters for more precise monitoring:
const subscribeMessage = {
type: "Subscribe",
payload: {
sub_type: "Deployment",
filter: {
name: "Bitcoin",
symbol: "BTC",
deployer: "AaA2aA5aA8aA4aA7aA1aA9aAa3aA6aA2aA8aA5aA1a",
},
},
};

Complete Example Implementation


• TypeScript
import WebSocket from 'ws';
class TokenMonitor {
private ws: WebSocket;

constructor(apiKey: string) {
this.ws = new WebSocket('wss://api.callstaticrpc.com/pumpfun/v1/streams', {
headers: { Authorization: `Bearer ${apiKey}` }
});

this.setupEventHandlers();
}

private setupEventHandlers() {
this.ws.on('open', () => {
console.log('Connected! Monitoring tokens...');

const subscribeMessage = {
type: "Subscribe",
payload: {
sub_type: "Deployment",
filter: {
name: "Bitcoin",
symbol: "BTC"
}
}
};

this.ws.send(JSON.stringify(subscribeMessage));
});

this.ws.on('message', (data: string) => {


try {
const message = JSON.parse(data);
if (message.data) {
console.log('\n🔔 Token Deployment Detected!');
console.log(`Name: ${message.data.name}`);
console.log(`Symbol: ${message.data.symbol}`);
console.log(`Deployer: ${message.data.deployer}`);
console.log(`Mint: ${message.data.mint}`);

if (message.data.twitter) {
console.log(`Twitter: ${message.data.twitter}`);
}
if (message.data.telegram) {
console.log(`Telegram: ${message.data.telegram}`);
}
if (message.data.website) {
console.log(`Website: ${message.data.website}`);
}
}
} catch (error) {
console.error('Error processing message:', error);
}
});

this.ws.on('error', (error) => {


console.error('WebSocket error:', error);
});
this.ws.on('close', () => {
console.log('Connection closed. Attempting to reconnect...');
setTimeout(() => this.setupEventHandlers(), 5000);
});
}

Error Handling
The WebSocket API returns standard error messages:
try {
ws.send(JSON.stringify(subscribeMessage));
} catch (error) {
if (error.message.includes('Authentication')) {
console.error('Invalid API key');
} else if (error.message.includes('Invalid filter')) {
console.error('Invalid filter parameters');
} else {
console.error('Unknown error:', error);
}
}

Best Practices
1. Filter Precision
o Use specific filters to reduce noise
o Combine filters for better accuracy
o Regularly review and update filters
2. Connection Management
o Implement reconnection logic
o Handle connection errors gracefully
o Monitor connection health
3. Data Processing
o Validate incoming messages
o Handle missing fields gracefully
o Log relevant information
Upcoming Features
Future Enhancements
The following filters are coming soon:
1. Count Filter
o Track similar token launches in short timeframes
o Useful for detecting trending token patterns
2. Narrative Filter
o Filter tokens by theme or category
o Match token metadata against specific narratives
3. Tweet Filter
o Monitor tokens related to specific tweets
o Filter by tweet URL instead of content
Next Steps
Now that you understand token event filtering, you can:
1. 🔍 Set up basic token monitoring
2. 📊 Track specific deployer activity
3. 🎯 Monitor tokens by name or symbol
4. ⚡ Implement real-time alerts

You might also like