buy_token()

Purchase Solana tokens with SOL through automated trading execution

CRITICAL WARNING

This method executes REAL blockchain transactions with REAL money. Always test with small amounts first and verify all parameters carefully before executing trades.

Automated
One-call execution
Flexible
SOL or token amount
Smart Routing
Auto pool selection
Secure
On-chain execution

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

python
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

Format:Base58 encoded string (NOT hex, NOT array format)
Security:⚠️ NEVER commit private keys to version control or share them
python
private_key = "5J6qw9kM2...base58string..."

token_mint (str)

The token contract address (mint address) you want to purchase

Format:Base58 encoded Solana public key (32 bytes)
How to find:Token addresses are found on Solscan, DEX Screener, or from WebSocket events
python
token_mint = "CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump"

amount (float)

The amount to trade (interpretation depends on denominated_in_sol)

If denominated_in_sol=True

Amount of SOL to spend (e.g., 0.1 = 0.1 SOL)

If denominated_in_sol=False

Amount of tokens to receive (e.g., 1000 = 1000 tokens)

python
amount = 0.05  # Spend 0.05 SOL

Optional Parameters

slippage_percent (float, default=10)

Maximum price slippage tolerance as a percentage

Range:Typically 1-50%
Lower (1-5%):Transaction may fail on volatile tokens
Higher (15-50%):More likely to execute but with price impact
python
slippage_percent = 15  # Allow up to 15% price slippage

priority_fee (float, default=0.005)

Priority fee paid to Solana validators for faster transaction processing

Unit:SOL (0.005 = 0.005 SOL = 5,000 lamports)
Normal times:0.001-0.005 SOL
High congestion:0.01-0.05 SOL
Time-sensitive:0.1+ SOL
python
priority_fee = 0.01  # Pay 0.01 SOL priority fee

pool (str, default="auto")

Specific exchange/pool to trade on

"auto" - Auto select (recommended)
"pump" - pump.fun exchange
"raydium" - Raydium DEX
"bonk" - Bonk Swap
python
pool = "auto"  # Let the system choose the best pool

Return Value

Returns a dictionary with transaction details:

Success Response

python
{
    "success": True,
    "signature": "5nh7w9kM2pqW...tx_id",
    "transactionId": "5nh7w9kM2pqW...tx_id",
    "explorer_url": "https://solscan.io/tx/..."
}

Error Response

python
{
    "success": False,
    "error": "Error description message"
}
FieldTypeDescription
successboolWhether the transaction was successful
signaturestrTransaction signature (transaction hash/ID)
explorer_urlstrDirect link to view transaction on Solscan
errorstrError message if transaction failed

Prerequisites

1. Install Required Dependencies

bash
pip install solders

The buy_token() method requires the solders library for Solana transaction handling.

2. Authentication Setup

python
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.

python
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.

python
# 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.

python
# 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 GitHub

Security 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
python
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

python
# 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

python
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

python
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

python
# 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.

bash
pip install solders

Error: "Insufficient funds"

Problem: Wallet doesn't have enough SOL for the trade + fees.

python
# 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.

python
# 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.

Open Source

Contribute to AxiomTradeAPI

View on GitHub

Community

Join 1000+ developers

Join Discord

Custom Development

Professional bot building

Get Started