Raydium Liquidity Trading

This guide explains how to execute buy and sell operations on Raydium liquidity pools, utilizing Solana and Kaze AI's toolkit to ensure efficient and secure token trading with slippage control.

Overview

The RaydiumManager class provides two core functionalities for liquidity trading:

  • Buying Tokens on Raydium: Swap SOL for a selected token with slippage control.

  • Selling Tokens on Raydium: Sell tokens for SOL, supporting slippage tolerance and customizable percentages of token balance.


Code Explanation

1. Buy Operation with Raydium

The buy_with_raydium method allows you to buy tokens using SOL, with slippage control and automatic WSOL (Wrapped SOL) handling:

  • Fetches pool keys for the selected pair address.

  • Calculates the amount of token to buy based on the provided input amount and slippage tolerance.

  • Ensures the presence of a token account for the buyer, creating one if necessary.

  • Executes the swap with dynamically calculated values for the amount out.

Copy

client = Client(agent.rpc_url)
pool_keys = fetch_pool_keys(pair_address)
amount_in = int(sol_in * SOL_DECIMAL)
base_reserve, quote_reserve, token_decimal = get_token_reserves(pool_keys)
amount_out = sol_for_tokens(sol_in, base_reserve, quote_reserve)
slippage_adjustment = 1 - (slippage / 100)
minimum_amount_out = int(amount_out * slippage_adjustment * 10**token_decimal)

2. Sell Operation with Raydium

The sell_with_raydium method enables selling tokens for SOL with customizable percentage of token balance and slippage control:

  • Retrieves token balance and checks if it's sufficient for selling.

  • Calculates the amount of SOL to receive based on the reserves and slippage.

  • Ensures the proper setup of WSOL accounts for token conversion during the swap.

Copy

token_balance = get_token_balance(str(mint))
token_balance = token_balance * (percentage / 100)
base_reserve, quote_reserve, token_decimal = get_token_reserves(pool_keys)
amount_out = tokens_for_sol(token_balance, base_reserve, quote_reserve)
slippage_adjustment = 1 - (slippage / 100)
amount_out_with_slippage = amount_out * slippage_adjustment
minimum_amount_out = int(amount_out_with_slippage * SOL_DECIMAL)

3. Token and WSOL Account Setup

Both buy and sell operations require setting up an associated token account if one doesn’t exist. Additionally, WSOL (Wrapped SOL) accounts are created for the swap, and closed afterward to save on costs.

Copy

wsol_token_account = Pubkey.create_with_seed(payer_keypair.pubkey(), seed, TOKEN_PROGRAM_ID)
create_wsol_account_instr = create_account_with_seed(...)
init_wsol_account_instr = initialize_account(...)

4. Swap Execution

The core swap logic involves creating swap instructions and compiling them into a transaction. Both buying and selling methods follow similar patterns in this section. After compiling the instructions, a transaction is submitted to the blockchain for confirmation.

Copy

swap_instructions = make_swap_instruction(amount_in, minimum_amount_out, token_account_in, token_account_out, pool_keys, payer_keypair)
compiled_message = MessageV0.try_compile(...)

Key Features

  1. Buy and Sell Operations

    • Execute token swaps using SOL or other tokens.

    • Adjustable slippage tolerance to protect against price fluctuations.

  2. WSOL (Wrapped SOL) Handling

    • Automatically wrap and unwrap SOL for token swaps.

    • Reduce transaction fees by closing unnecessary accounts post-swap.

  3. Transaction Confirmation

    • Ensure the transaction is successfully executed with confirmation checks.

    • Monitor for any errors and retry the transaction if needed.

  4. Account and Token Management

    • Dynamically create associated token accounts and handle liquidity pools.

    • Ensure proper token account balance before initiating the trade.


How to Use

  • Setup:

    • Initialize the SolanaAgentKit with your wallet and RPC connection.

    • Pass the appropriate parameters (pair address, slippage, amount) when calling the trade functions.

  • Example Buy Operation:

    Copy

    pair_address = "Raydium_Pool_Address"
    signature = await RaydiumManager.buy_with_raydium(agent, pair_address, sol_in=0.05, slippage=3)
    print(f"Transaction Signature: {signature}")
  • Example Sell Operation:

    Copy

    pair_address = "Raydium_Pool_Address"
    success = await RaydiumManager.sell_with_raydium(agent, pair_address, percentage=50, slippage=2)
    print(f"Transaction success: {success}")

Error Handling

  • Insufficient Funds:

    • Ensure enough tokens or SOL is available before initiating the transaction.

  • Slippage Exceedance:

    • Adjust slippage parameters if the market is volatile to prevent failed transactions.

  • Account Management Failures:

    • Handle errors related to token account creation and ensure all necessary accounts are set up properly.

Last updated