DEV Community

Jeremy Godfrey
Jeremy Godfrey

Posted on

Building a Real-Time Solana Trading Bot: Transaction Monitoring, Automated Trades, and Dynamic Fee Handling

Introduction
In the fast-paced world of blockchain, automation is key to staying ahead. Recently, I developed a real-time trading bot for the Solana blockchain that not only monitors wallet activity but also executes buy and sell orders automatically based on detected transactions. In this post, I’ll walk through the architecture, key features, and some of the technical challenges I solved along the way.

Key Features
Real-Time Transaction Monitoring:
The bot leverages Solana’s WebSocket API to subscribe to logs for a target wallet, instantly reacting to relevant on-chain activity.
Automated Trade Execution:
Upon detecting buy or sell instructions, the bot can automatically execute corresponding trades using a custom API, with dynamic slippage and priority fee calculations.
Robust Error Handling & Retry Logic:
The script includes intelligent retry mechanisms for failed transactions, ensuring reliability even under adverse network conditions.
Token and SOL Balance Tracking:
The bot fetches and analyzes both SOL and SPL token balances, making decisions based on up-to-date wallet states.

How It Works
WebSocket Subscription:
The bot establishes a persistent WebSocket connection to a Solana RPC endpoint, subscribing to logs mentioning a specific wallet address.
Transaction Queue & Processing:
Incoming transactions are queued and processed sequentially, ensuring no event is missed and that actions are taken in order.
Transaction Analysis:
For each transaction, the bot:
Retrieves full transaction details (with retry logic for reliability)
Compares pre- and post-transaction balances for SOL and tokens
Detects the type of action (buy/sell) based on log messages and token changes
Automated Trading:
When a buy or sell is detected, the bot:
Calculates dynamic slippage and priority fees based on network conditions and trade size
Calls a trading API to construct and sign the transaction
Submits the transaction to the Solana network, with retries for sell actions if needed
Resilience:
The bot automatically reconnects on WebSocket errors or disconnects, and gracefully handles process termination.

Code Highlights

Here’s a brief look at some of the core logic (full code available in my repo):
// Subscribe to wallet logs via WebSocket
function setupWebSocket() {
const ws = new WebSocket(WS_RPC_URL);
ws.on('open', () => {
// Subscribe to logs mentioning the target wallet
ws.send(JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "logsSubscribe",
params: [{ mentions: [TARGET_WALLET] }, { commitment: "confirmed" }]
}));
});
// ... handle messages, errors, and reconnections ...
}

// Analyze and process each transaction
async function processTransaction(signature, logMessages) {
// Fetch transaction details, compare balances, detect action
// If buy/sell detected, call executeTrade()
}

// Execute trades with dynamic fee and slippage
async function executeTrade(hash, action, tokenMint, amount, retryCount = 0) {
// Calculate dynamic slippage and priority fee
// Call trading API, sign and send transaction
// Retry on failure (for sells)
}

Lessons Learned
WebSocket Reliability:
Handling disconnects and errors gracefully is crucial for 24/7 bots.
Dynamic Fee Calculation:
Adapting to network conditions in real time helps ensure transactions are confirmed quickly, even during congestion.
Security:
Always keep your private keys secure and never hard-code them in your scripts. Use environment variables and secure storage.

Conclusion
This project demonstrates how to build a robust, real-time trading bot on Solana, capable of monitoring wallet activity and executing trades automatically. The architecture can be extended for more advanced strategies, analytics, or integration with other DeFi protocols.
Interested in the full code or want to collaborate?
Feel free to reach out and happy to discuss!

Top comments (0)