Overview
The buy_token() method enables you to purchase Solana tokens using SOL through the PumpPortal trading API. This method handles the complete transaction lifecycle, from building the transaction with your private key to submitting it to the Solana blockchain.
Trading Bots
Automated token purchasing strategies
Token Sniping
Early entry on new token launches
DCA Strategies
Dollar-cost averaging automation
Portfolio Rebalancing
Multi-token portfolio management
Method Signature
def buy_token(
self,
private_key: str,
token_mint: str,
amount: float,
slippage_percent: float = 10,
priority_fee: float = 0.005,
pool: str = "auto",
denominated_in_sol: bool = True,
rpc_url: str = "https://api.mainnet-beta.solana.com/"
) -> Dict[str, Union[str, bool]]Parameters
Required Parameters
private_key (str)
Your wallet's private key encoded as a base58 string
private_key = "5J6qw9kM2...base58string..."token_mint (str)
The token contract address (mint address) you want to purchase
token_mint = "CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump"amount (float)
The amount to trade (interpretation depends on denominated_in_sol)
Amount of SOL to spend (e.g., 0.1 = 0.1 SOL)
Amount of tokens to receive (e.g., 1000 = 1000 tokens)
amount = 0.05 # Spend 0.05 SOLOptional Parameters
slippage_percent (float, default=10)
Maximum price slippage tolerance as a percentage
slippage_percent = 15 # Allow up to 15% price slippagepriority_fee (float, default=0.005)
Priority fee paid to Solana validators for faster transaction processing
priority_fee = 0.01 # Pay 0.01 SOL priority feepool (str, default="auto")
Specific exchange/pool to trade on
"auto" - Auto select (recommended)"pump" - pump.fun exchange"raydium" - Raydium DEX"bonk" - Bonk Swappool = "auto" # Let the system choose the best poolReturn Value
Returns a dictionary with transaction details:
Success Response
{
"success": True,
"signature": "5nh7w9kM2pqW...tx_id",
"transactionId": "5nh7w9kM2pqW...tx_id",
"explorer_url": "https://solscan.io/tx/..."
}Error Response
{
"success": False,
"error": "Error description message"
}| Field | Type | Description |
|---|---|---|
success | bool | Whether the transaction was successful |
signature | str | Transaction signature (transaction hash/ID) |
explorer_url | str | Direct link to view transaction on Solscan |
error | str | Error message if transaction failed |
Prerequisites
1. Install Required Dependencies
pip install soldersThe buy_token() method requires the solders library for Solana transaction handling.
2. Authentication Setup
from axiomtradeapi import AxiomTradeClient
# Initialize client with authentication
client = AxiomTradeClient()
# If using environment variables (.env file):
# AXIOM_ACCESS_TOKEN=your_access_token
# AXIOM_REFRESH_TOKEN=your_refresh_token
# Or login manually:
# client.login("username", "password")3. Obtain Your Private Key
Your wallet private key should be in base58 format. You can export it from:
- • Phantom wallet (Settings → Show Private Key)
- • Solflare wallet (Settings → Export Private Key)
- • Other Solana wallets with export functionality
Security
Store private keys in environment variables or secure key management systems.
Basic Usage Examples
Example 1: Simple Token Purchase
Purchase a token by spending a specific amount of SOL.
from axiomtradeapi import AxiomTradeClient
import os
# Initialize client
client = AxiomTradeClient()
# Get private key from environment variable (secure practice)
private_key = os.getenv("SOLANA_PRIVATE_KEY")
# Token mint address (example from pump.fun)
token_mint = "CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump"
# Buy token with 0.1 SOL
result = client.buy_token(
private_key=private_key,
token_mint=token_mint,
amount=0.1, # Spend 0.1 SOL
slippage_percent=10
)
# Check result
if result["success"]:
print(f"✅ Purchase successful!")
print(f"Transaction: {result['signature']}")
print(f"View on Solscan: {result['explorer_url']}")
else:
print(f"❌ Purchase failed: {result['error']}")Example 2: Purchase with Higher Slippage
For volatile meme coins, you may need higher slippage tolerance.
# Buy highly volatile token with 25% slippage
result = client.buy_token(
private_key=private_key,
token_mint="DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",
amount=0.05,
slippage_percent=25, # Higher slippage for volatile tokens
priority_fee=0.01 # Higher priority fee for faster execution
)
if result["success"]:
print(f"✅ Bought volatile token successfully")
print(f"Explorer: {result['explorer_url']}")
else:
print(f"❌ Failed: {result['error']}")Example 3: Purchase Specific Token Amount
Specify the exact number of tokens you want to receive instead of SOL to spend.
# Buy exactly 1,000,000 tokens
result = client.buy_token(
private_key=private_key,
token_mint="8z5VqjqYqF3zK8jM9nL3rT6wU4xY2zA1bC5dE8fG9hJ",
amount=1000000, # Want to receive 1M tokens
denominated_in_sol=False, # Amount is in TOKENS, not SOL
slippage_percent=15
)
if result["success"]:
print(f"✅ Received ~1,000,000 tokens")
print(f"Transaction: {result['signature']}")Advanced Examples
The documentation includes advanced examples for production trading bots, including:
Trading Bot with Retry Logic
Automatic retry with increasing priority fees
Dollar-Cost Averaging (DCA)
Automated recurring purchases
Pre-Transaction Safety Checks
Balance verification and validation
Token Sniper Bot
WebSocket-triggered automated buying
Full advanced examples with complete code are available in the GitHub repository
View Examples on GitHubSecurity Guidelines
🔐 Private Key Security
✅ DO
- • Store keys in environment variables
- • Use secure key management services
- • Encrypt private keys at rest
- • Use hardware wallets for large amounts
- • Regularly rotate keys
❌ DON'T
- • Hard-code keys in source code
- • Commit keys to Git repositories
- • Share keys via email or chat
- • Store keys in plain text files
- • Reuse keys across applications
import os
from dotenv import load_dotenv
# Load from .env file (add .env to .gitignore)
load_dotenv()
private_key = os.getenv("SOLANA_PRIVATE_KEY")
if not private_key:
raise ValueError("SOLANA_PRIVATE_KEY not found in environment variables")
# Use the key
result = client.buy_token(private_key=private_key, ...)💰 Financial Safety
# Always test with minimum amounts first
TEST_AMOUNT = 0.001 # Very small amount for testing
result = client.buy_token(
private_key=private_key,
token_mint=token_mint,
amount=TEST_AMOUNT, # Test with tiny amount
slippage_percent=15
)
if result["success"]:
print("✅ Test successful - safe to proceed with larger amounts")Best Practices
1. Always Handle Errors
result = client.buy_token(...)
if result["success"]:
# Success path
print(f"Transaction: {result['signature']}")
else:
# Error path
print(f"Failed: {result['error']}")
# Log error, send alert, retry, etc.2. Log All Transactions
import logging
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
result = client.buy_token(...)
logger.info(f"[{datetime.now()}] Buy attempt: {token_mint}, Amount: {amount} SOL")
if result["success"]:
logger.info(f"SUCCESS: {result['signature']}")
else:
logger.error(f"FAILED: {result['error']}")3. Use Appropriate Slippage
# Conservative for established tokens
SLIPPAGE_STABLE = 5 # 5% for established tokens
# Moderate for mid-caps
SLIPPAGE_MODERATE = 12 # 12% for moderate volatility
# Aggressive for meme coins
SLIPPAGE_HIGH = 25 # 25% for high volatility
result = client.buy_token(
...,
slippage_percent=SLIPPAGE_HIGH if is_meme_coin else SLIPPAGE_STABLE
)Troubleshooting
Error: "solders library not installed"
Problem: The required solders package is missing.
pip install soldersError: "Insufficient funds"
Problem: Wallet doesn't have enough SOL for the trade + fees.
# Check balance first
balance = client.GetBalance()
print(f"Available: {balance['sol']} SOL")
# Ensure you have: trade amount + priority fee + network fees (~0.000005 SOL)
total_needed = amount + priority_fee + 0.001
if balance['sol'] < total_needed:
print(f"Need {total_needed} SOL, have {balance['sol']} SOL")Error: "Slippage tolerance exceeded"
Problem: Token price moved beyond your slippage tolerance during execution.
# Increase slippage for volatile tokens
result = client.buy_token(
...,
slippage_percent=20, # Increase from default 10%
priority_fee=0.01 # Higher priority for faster execution
)Need More Help?
Our support team can help you troubleshoot trading issues
Related Documentation
Build Automated Trading Bots
Need help building professional trading bots with buy_token()? We offer custom development services.