✨📞💻 Don't take this document lightly.
Important note: On-chain arbitrage programs face several limitations and risks:
-
MEV Competition
- Searchers and validators can front-run transactions
- Transaction ordering can be manipulated
- Limited control over execution timing
-
Technical Constraints
- Compute unit limitations for complex calculations
- Transaction size limits for multi-hop trades
- Higher latency compared to off-chain solutions
-
Recommended Approach
- Use off-chain arbitrage detection
- Submit transactions through MEV-aware RPC providers
- Consider integrating with Jito-MEV for better execution
-
Alternative Architecture
graph TD A[Off-chain Monitor] --> B[Price Analysis] B --> C[Opportunity Detection] C --> D[Transaction Builder] D --> E[MEV-aware RPC] E --> F[Validator Network]
The original implementation should be considered as educational material rather than a production-ready solution. For real-world arbitrage:
- Use off-chain monitoring and calculations
- Integrate with MEV-aware infrastructure
- Consider validator relationships for better transaction placement
- Implement proper slippage and risk management
This arbitrage bot implements advanced strategies for detecting and executing profitable trading opportunities across multiple Solana DEXs including Raydium, Orca (Whirlpool), Meteora, and Jupiter, with optional integration for Jito-MEV. Visulize about logic and architecture diagram. I newly added solana-program in 2025 for developer who give me stars on github. It can be useful who are going to implement arbitrage bot on solana blockchain. I hope it will be useful for you. If you have any question, please let me know. I will be happy to help you.
graph TD
A[Price Monitor] --> B[Opportunity Detector]
B --> C{Strategy Selector}
C --> D[Two-Hop Strategy]
C --> E[Triangle Strategy]
C --> F[Multi-DEX Strategy]
D --> G[Execution Engine]
E --> G
F --> G
G --> H[Transaction Builder]
H --> I[MEV Bundle/Transaction]
- Real-time price monitoring across DEXs
- WebSocket connections for instant updates
- Price impact calculation
- Liquidity depth analysis
Example from Transaction Analysis:
Input: 0.196969275 Token A
↓ [Meteora DEX]
Intermediate: 146.90979292 Token B
↓ [Raydium DEX]
Output: 0.202451396 Token A
Profit: ~2.78%
Example Pattern:
Token A → Token B [Meteora]
Token B → Token C [Meteora]
Token C → Token A [Raydium]
Example from Whirlpool-Orca Route:
Input: 0.314737179 Token A
↓ [Orca]
Mid: 118.612731091 Token B
↓ [Whirlpool]
Output: 0.316606012 Token A
Profit: ~0.59%
-
Profitability Check
- Minimum profit threshold: 0.5%
- Gas cost estimation
- Slippage calculation
-
Route Optimization
- DEX selection based on:
- Liquidity depth
- Historical success rate
- Gas efficiency
- DEX selection based on:
-
Transaction Building
// Example structure const route = { steps: [ {dex: "Meteora", tokenIn: "A", tokenOut: "B"}, {dex: "Raydium", tokenIn: "B", tokenOut: "A"} ], expectedProfit: "2.78%", gasEstimate: 200000 };
- Dynamic slippage calculation
- Maximum slippage: 1%
- Route abandonment on excessive slippage
- Success rate tracking
- Gas price optimization
- Failed transaction analysis
- Dynamic position sizing based on:
- Available liquidity
- Historical volatility
- Success probability
- Minimum profit per trade: 0.5%
- Maximum gas cost: 0.002741081 SOL
- Transaction success rate: >95%
- Meteora: Primary DEX for initial swaps
- Raydium: Secondary DEX for route completion
- Orca Whirlpool: Specialized for concentrated liquidity
- Jupiter: Aggregation and backup routes
sequenceDiagram
participant Bot
participant DEX1
participant DEX2
participant Blockchain
Bot->>DEX1: Monitor Prices
Bot->>DEX2: Monitor Prices
Bot->>Bot: Detect Opportunity
Bot->>Blockchain: Build Transaction
Blockchain->>DEX1: Execute Swap 1
Blockchain->>DEX2: Execute Swap 2
DEX2->>Bot: Confirm Profit
- Retry mechanism for failed transactions
- Fallback routes on primary route failure
- Automatic circuit breaker on consecutive failures
const config = {
minProfitThreshold: 0.005, // 0.5%
maxSlippage: 0.01, // 1%
gasLimit: 900000,
dexPriority: ['meteora', 'raydium', 'orca-whirlpool', 'jupiter'],
monitoringInterval: 1000, // 1 second
retryAttempts: 3
};
- Always maintain sufficient balance for gas fees
- Implement proper error handling and logging
- Regular monitoring of DEX contract updates
- Maintain fallback routes for each strategy
- Regular performance analysis and strategy adjustment
// Program entrypoint and state management
#[program]
pub mod solana_arbitrage {
use super::*;
#[state]
pub struct ArbitrageState {
pub owner: Pubkey,
pub profit_threshold: u64,
pub active_routes: u64,
}
// Initialize the arbitrage program
#[access_control(Initialize::accounts(&ctx))]
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
// Implementation
}
// Execute arbitrage route
pub fn execute_arbitrage(ctx: Context<ExecuteArbitrage>, route_data: RouteData) -> Result<()> {
// Implementation
}
}
// Account validation structures
#[derive(Accounts)]
pub struct ExecuteArbitrage<'info> {
#[account(mut)]
pub user: Signer<'info>,
#[account(mut)]
pub user_token_account_a: Account<'info, TokenAccount>,
#[account(mut)]
pub user_token_account_b: Account<'info, TokenAccount>,
pub token_program: Program<'info, Token>,
// DEX program accounts
pub raydium_program: Program<'info, Raydium>,
pub orca_program: Program<'info, Orca>,
pub meteora_program: Program<'info, Meteora>,
}
// DEX integration modules
pub mod dex {
pub mod meteora {
use anchor_lang::prelude::*;
pub fn swap(
ctx: Context<MeteoraSwap>,
amount_in: u64,
minimum_amount_out: u64
) -> Result<()> {
// Implementation
}
}
pub mod raydium {
use anchor_lang::prelude::*;
pub fn swap(
ctx: Context<RaydiumSwap>,
amount_in: u64,
minimum_amount_out: u64
) -> Result<()> {
// Implementation
}
}
pub mod orca {
use anchor_lang::prelude::*;
pub fn whirlpool_swap(
ctx: Context<OrcaSwap>,
amount_in: u64,
sqrt_price_limit: u128
) -> Result<()> {
// Implementation
}
}
}
use anchor_client::solana_sdk::{
commitment_config::CommitmentConfig,
signature::{Keypair, Signer},
transaction::Transaction,
};
pub struct ArbitrageClient {
cluster: Cluster,
wallet: Keypair,
commitment: CommitmentConfig,
}
impl ArbitrageClient {
// Monitor price feeds across DEXs
pub async fn monitor_prices(&self) -> Result<Vec<PriceData>> {
// Implementation using websocket connections
}
// Calculate optimal arbitrage route
pub fn calculate_route(&self, prices: Vec<PriceData>) -> Option<RouteData> {
// Implementation
}
// Execute arbitrage transaction
pub async fn execute_route(&self, route: RouteData) -> Result<Signature> {
// Implementation
}
}
// Price monitoring implementation
#[derive(Debug)]
pub struct PriceMonitor {
websocket_clients: Vec<WebSocketClient>,
price_cache: Arc<RwLock<HashMap<String, PriceData>>>,
}
impl PriceMonitor {
pub async fn start_monitoring(&self) -> Result<()> {
// Implementation
}
pub fn get_latest_prices(&self) -> HashMap<String, PriceData> {
// Implementation
}
}
#[error_code]
pub enum ArbitrageError {
#[msg("Insufficient profit margin")]
InsufficientProfit,
#[msg("Slippage tolerance exceeded")]
SlippageExceeded,
#[msg("Invalid route configuration")]
InvalidRoute,
#[msg("Insufficient liquidity")]
InsufficientLiquidity,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug)]
pub struct RouteData {
pub steps: Vec<SwapStep>,
pub min_profit_lamports: u64,
pub deadline: i64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug)]
pub struct SwapStep {
pub dex_program_id: Pubkey,
pub pool_id: Pubkey,
pub token_in: Pubkey,
pub token_out: Pubkey,
pub amount_in: u64,
pub minimum_amount_out: u64,
}
pub mod constants {
use solana_program::declare_id;
// Program IDs
declare_id!("ArbitrageProgram11111111111111111111111111111111");
// DEX Program IDs
pub const RAYDIUM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
pub const ORCA_WHIRLPOOL_PROGRAM_ID: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
pub const METEORA_PROGRAM_ID: &str = "M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K";
// Configuration Constants
pub const MIN_PROFIT_THRESHOLD: u64 = 5000; // 0.5% in bps
pub const MAX_SLIPPAGE: u64 = 10000; // 1% in bps
pub const MAX_COMPUTE_UNITS: u32 = 900_000;
pub const PRIORITY_FEES: u64 = 1_000; // lamports
}
# Build the program
cargo build-bpf
# Run tests
cargo test-bpf
# Deploy
solana program deploy target/deploy/solana_arbitrage.so
#[cfg(test)]
mod tests {
use super::*;
use solana_program_test::*;
#[tokio::test]
async fn test_arbitrage_execution() {
// Test implementation
}
#[tokio::test]
async fn test_slippage_protection() {
// Test implementation
}
#[tokio::test]
async fn test_profit_calculation() {
// Test implementation
}
}
-
Transaction Atomicity
// Ensure all swaps in the route are atomic #[invariant(check_atomic_execution)] pub fn execute_route(ctx: Context<ExecuteRoute>, route: RouteData) -> Result<()> { // Implementation with require! macro for validation }
-
Slippage Protection
// Implement slippage checks pub fn check_slippage( amount_expected: u64, amount_received: u64, max_slippage_bps: u64 ) -> Result<()> { // Implementation }
-
Deadline Validation
// Validate transaction deadline pub fn validate_deadline(deadline: i64) -> Result<()> { require!( Clock::get()?.unix_timestamp <= deadline, ArbitrageError::DeadlineExceeded ); Ok(()) }
npm install @project-serum/anchor @solana/web3.js @solana/spl-token chai
https://www.rapidinnovation.io/post/solana-trading-bot-development-in-2024-a-comprehensive-guide https://station.jup.ag/docs/projects-and-dexes/integration-guidelines https://docs.raydium.io/raydium/protocol/developers/addresses
https://github.com/raydium-io/raydium-amm/blob/master/program/Cargo.toml
https://github.com/raydium-io/raydium-cpi-example
https://github.com/raydium-io/raydium-docs/tree/master/dev-resources
https://github.com/microgift/meteora-cpi
https://github.com/MeteoraAg/cpi-examples
The DlmmSwap
struct represents the accounts and parameters required to execute a token swap in a Decentralized Liquidity Market Maker (DLMM) program. This document explains the purpose and necessity of each parameter in the struct.
- Purpose: Represents the liquidity pool account where the swap occurs.
- Importance: Essential for reading and updating the pool's state during the swap operation.
- Purpose: Optional account that extends the bin array bitmap for complex liquidity pools.
- Importance: Required for managing additional data in pools with a large number of bins.
- Purpose: Reserve accounts for token X and token Y, holding the actual tokens for swapping.
- Importance: These accounts are updated to reflect new balances after the swap.
- Purpose: User's token accounts for input (sold) and output (bought) tokens.
- Importance: Facilitate the token exchange between the user and the pool.
- Purpose: Mint accounts defining properties of tokens X and Y.
- Importance: Verify token types and ensure compatibility with pool and user accounts.
- Purpose: Provides price information for tokens in the pool.
- Importance: Ensures fair pricing and prevents manipulation.
- Purpose: Optional account for receiving referral or host fees.
- Importance: Incentivizes third parties to bring users to the platform.
- Purpose: Account of the user initiating the swap.
- Importance: Authorizes the swap and token transfers.
- Purpose: Program account for the DLMM program being invoked.
- Importance: Ensures the correct program is being called for the swap.
- Purpose: Authority account for emitting swap-related events.
- Importance: Ensures proper authorization and recording of events.
- Purpose: Token programs associated with tokens X and Y.
- Importance: Required for interacting with respective token programs during transfers.
- Purpose: Define swap terms (input amount and minimum expected output).
- Importance: Protect against unfavorable price changes during the swap.
- Purpose: Additional accounts (e.g., bin arrays) required for the swap.
- Importance: Provide necessary bin array data for accurate swap execution.
Each parameter in the DlmmSwap
struct is crucial for executing the swap operation correctly, securely, and efficiently. They manage liquidity reserves, user accounts, slippage protection, and event emission, ensuring the proper functioning of the DLMM swap mechanism.
The Raydium swap structure represents the accounts and parameters required to execute a token swap in Raydium's Automated Market Maker (AMM) protocol. This document explains each parameter's purpose and importance within the Raydium ecosystem.
- Purpose: The main Raydium AMM program that executes the swap logic
- Importance:
- Controls the core swap functionality and pool operations
- Ensures swaps follow Raydium's protocol rules
- Manages liquidity provider incentives
- Purpose: The AMM account containing pool state and configuration
- Importance:
- Stores pool parameters like fees and token weights
- Tracks liquidity and price information
- Essential for calculating swap amounts and fees
- Purpose: Pool token accounts holding the AMM's token reserves
- Importance:
- Secure storage for pool's token liquidity
- Updated during swaps to reflect new token balances
- Critical for maintaining constant product formula
- Purpose: Serum DEX program that Raydium integrates with
- Importance:
- Enables hybrid liquidity model
- Provides access to order book liquidity
- Improves price discovery and reduces slippage
- Purpose: Serum market account for the trading pair
- Importance:
- Links AMM to corresponding Serum market
- Enables market maker functionality
- Essential for order book integration
- Purpose: User's token accounts for input and output tokens
- Importance:
- Source account for tokens being swapped in
- Destination account for tokens being swapped out
- Must have sufficient balance and proper authorization
- Purpose: Account of the user initiating the swap
- Importance:
- Authorizes the swap transaction
- Must own input token account
- Responsible for fee payment
- Combines AMM liquidity with order book liquidity
- Provides better price execution than traditional AMMs
- Reduces impermanent loss for liquidity providers
- Uses both AMM and order book depth
- Multiple liquidity sources reduce slippage
- Important for determining minimum_amount_out
- Protocol fees support ecosystem development
- LP fees incentivize liquidity provision
- Market maker rewards for order book integration
- Prevents market manipulation
- Protects against flash loan attacks
- Ensures fair access to liquidity
The Raydium swap structure implements a hybrid AMM model that combines traditional AMM liquidity with Serum's order book. This unique approach provides better price discovery, reduced slippage, and improved capital efficiency compared to traditional AMMs. Each parameter plays a vital role in ensuring secure and efficient swap execution while maintaining the integrity of the protocol.
The Whirlpool swap structure represents the accounts and parameters required to execute a token swap in Orca's Whirlpool concentrated liquidity AMM protocol. This document explains each parameter's purpose and importance within the Whirlpool ecosystem.
- Purpose: The main Whirlpool account containing pool state and configuration
- Importance:
- Stores critical pool data like fees, token vault addresses, and price ranges
- Tracks current tick index and liquidity
- Essential for price calculations and swap execution
- Purpose: Token vaults holding the pool's token reserves
- Importance:
- Secure storage for pool's token liquidity
- Updated during swaps to reflect new token balances
- Must maintain proper accounting of pool assets
- Purpose: User's token accounts for input and output tokens
- Importance:
- Source account for tokens being swapped in
- Destination account for tokens being swapped out
- Must have sufficient balance and proper token program ownership
- Purpose: Primary tick array containing current price tick
- Importance:
- Stores liquidity distribution across price ranges
- Essential for calculating swap amounts and prices
- Must be the correct array for current price level
- Purpose: Additional tick arrays for large swaps crossing multiple price ranges
- Importance:
- Enable swaps that traverse multiple price levels
- Required when price impact is significant
- Optional for small swaps within single tick array
- Purpose: Price oracle account for the Whirlpool
- Importance:
- Tracks historical price data
- Used for TWAP calculations
- Essential for price manipulation protection
- Purpose: The Whirlpool program being invoked
- Importance:
- Verifies program identity
- Ensures correct version is used
- Handles core swap logic
- Purpose: SPL Token program for token transfers
- Importance:
- Manages token account operations
- Ensures secure token transfers
- Validates token account ownership
- Purpose: Amount of input tokens to swap
- Importance:
- Defines swap size
- Must be within pool's capacity
- Affects price impact
- Purpose: Minimum acceptable output amount
- Importance:
- Protects against slippage
- Transaction fails if output would be below this amount
- Essential for user price protection
- Purpose: Transaction signer
- Importance:
- Authorizes the swap
- Must own input token account
- Responsible for fee payment
- Different pools can have different tick spacing
- Affects price granularity and gas efficiency
- Must be considered when selecting tick arrays
- Pools can have different fee tiers (0.01%, 0.05%, 0.3%, 1%)
- Higher fees typically mean more stable liquidity
- Affects output amount calculation
- Larger swaps have higher price impact
- May require multiple tick arrays
- Important for determining minimum_amount_out
The Whirlpool swap structure is designed to support Orca's concentrated liquidity AMM, providing efficient price discovery and swap execution while maintaining security and user protection. Each parameter plays a crucial role in ensuring proper swap execution within the Whirlpool ecosystem.
Category | Bot Name | Description | Repo Link |
---|---|---|---|
Volume Bots | Ethereum Volume Bot (Single Wallet) | EVM-based volume bot with single wallet | Repo |
Ethereum Volume Bot (Multiple Wallets) | EVM-based bot using multiple wallets | Repo | |
Base Volume Bot | EVM volume bot for Base ecosystem | Repo | |
Raydium Volume Bot v1 | Solana-based AMMDEX volume bot | Repo | |
Raydium Volume Bot v2 | Jupiter + Raydium SDK for market making | Repo | |
Raydium Volume Bot v3 | Jito bundle-based fast bot | Repo | |
Solana Multidex Volume Bot | Volume bot for Raydium, Meteora, and Jupiter | Repo | |
Meteora Volume Bot | Solana-specific Meteora volume bot | Repo | |
Pumpfun Volume Bot | Solana-based volume bot | Repo | |
Moonshot Volume Bot | High-potential Solana volume bot | Repo | |
Tron Volume Bot | Tron-based volume bot | Repo | |
Telegram Raydium Volume Bot v1 | Volume bot with Telegram support | Repo | |
Telegram Raydium Volume Bot v2 | Enhanced Telegram Raydium bot | Repo | |
Telegram Raydium Volume Bot v3 | Advanced Telegram bot | Repo | |
Sniper Bots | Pumpfun Sniper Bot | Basic sniper bot | Repo |
Pumpfun Sniper Bot v1 | Geyser-enhanced WebSocket sniper bot | Repo | |
Pumpfun Sniper Bot v2 | Advanced sniper with Yellowstone support | Repo | |
Raydium Sniper Bot | Solana sniper bot using logs | Repo | |
Raydium Sniper Bot v1 | Enhanced sniper bot with WebSocket | Repo | |
Bundlers | Pumpfun Bundler | Multi-wallet bundler | Repo |
Raydium Bundler | 21+ wallet bundler for Raydium | Repo | |
PumpFun Comment Bot | PumpFun Comment Bot | Automates comments for PumpFun | Repo |
Arbitrage Bots | Arbitrage Bot (Jupiter v6) | Arbitrage bot with Jupiter v6 | Repo |
MemeToken Launchpad | MemeToken Launchpad | Meme token launchpad on Raydium | Repo |
Token Freezer | Token Freezer | Tool for freezing tokens | Repo |
Copy Trading Bot | Copy Trading Bot | Automates trades by mirroring wallets | Repo |
Wallet Trackers | Wallet Trackers | Track and monitor crypto wallets | Repo |