https://docs.raydium.io/raydium/traders/trade-api
- User
- Assistant
- User
En utilisant toutes les informations depuis le début. Rédiger script achat automatique, wait 2min , sell all previous token
- Assistant
En utilisant toutes les informations depuis le début. Rédiger script achat automatique, wait 2min , sell all previous token
The Raydium Trade API offers a streamlined method for interacting with Raydium's liquidity pools, enabling users to perform token swaps efficiently with minimal requests and a single signature.
Key Features:
Token Swaps: Facilitates the exchange of tokens by specifying input and output token mint addresses, the amount to swap, and acceptable slippage tolerance.
Transaction Customization: Allows users to choose between versioned ('V0') and legacy ('LEGACY') transactions, and to handle SOL tokens appropriately by wrapping or unwrapping them as needed.
Priority Fees: Supports the inclusion of priority fees to expedite transaction processing, with options to set the fee manually or automatically using Raydium's priority fee API.
Getting Started:
Installation: Install the Raydium SDK v2 using Yarn:
yarn add @raydium-io/raydium-sdk-v2
Import Libraries: Import necessary modules from the Solana Web3.js library, SPL Token library, Axios for HTTP requests, and the Raydium SDK:
import { Transaction, VersionedTransaction, sendAndConfirmTransaction } from '@solana/web3.js';
import { NATIVE_MINT } from '@solana/spl-token';
import axios from 'axios';
import { connection, owner, fetchTokenAccountData } from '../config';
import { API_URLS } from '@raydium-io/raydium-sdk-v2';
Set Up Wallet and Connection: Initialize your wallet and establish a connection to the Solana network:
export const owner: Keypair = Keypair.fromSecretKey(bs58.decode('<your_wallet_secret_key>'));
export const connection = new Connection('<your_rpc_url>');
Obtain a Swap Quote: Request a swap quote by specifying the input and output token mint addresses, the amount to swap, and the slippage tolerance:
const { data: swapResponse } = await axios.get<swapcompute>(
`${API_URLS.SWAP_QUOTE}?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amount}&slippageBps=${slippageBps}`
);
Execute the Swap: Construct and sign the transaction using the obtained swap quote, then send it to the network:
const transaction = VersionedTransaction.deserialize(Buffer.from(swapResponse.transaction, 'base64'));
transaction.sign([owner]);
const signature = await sendAndConfirmTransaction(connection, transaction, [owner]);
For a comprehensive guide and additional details, refer to the official Raydium Trade API documentation.
Additionally, the Raydium SDK provides extensive functionalities for building applications on top of Raydium, including methods for fetching token lists, pool information, and more[1].
For practical implementation examples, you can explore the Raydium SDK v2 demo repository, which offers sample code and usage scenarios[2].
Pour automatiser l'achat d'un token sur Raydium, attendre 2 minutes, puis vendre la totalité de ce token, vous pouvez utiliser le SDK Raydium en TypeScript. Le script suivant illustre ce processus :
import { Connection, Keypair, PublicKey, Transaction, VersionedTransaction, sendAndConfirmTransaction } from '@solana/web3.js';
import { NATIVE_MINT } from '@solana/spl-token';
import axios from 'axios';
import { API_URLS } from '@raydium-io/raydium-sdk-v2';
// Configuration
const RPC_URL = '<votre_rpc_url>';
const WALLET_SECRET_KEY = '<votre_clé_secrète_de_portefeuille>';
const INPUT_MINT = NATIVE_MINT.toBase58(); // SOL
const OUTPUT_MINT = '<adresse_du_token>'; // Adresse du token à acheter
const AMOUNT = 1 * 10 ** 9; // Montant en lamports (1 SOL)
const SLIPPAGE = 0.5; // Tolérance de glissement en pourcentage
const TX_VERSION = 'V0'; // 'V0' ou 'LEGACY'
const WAIT_TIME_MS = 2 * 60 * 1000; // 2 minutes en millisecondes
// Initialisation
const owner = Keypair.fromSecretKey(Uint8Array.from(WALLET_SECRET_KEY.split(',').map(n => parseInt(n))));
const connection = new Connection(RPC_URL);
async function executeSwap(inputMint: string, outputMint: string, amount: number, slippage: number, txVersion: string) {
const isInputSol = inputMint === NATIVE_MINT.toBase58();
const isOutputSol = outputMint === NATIVE_MINT.toBase58();
// Obtenir les comptes de token
const tokenAccounts = await connection.getParsedTokenAccountsByOwner(owner.publicKey, { programId: NATIVE_MINT });
const inputTokenAcc = tokenAccounts.value.find(a => a.account.data.parsed.info.mint === inputMint)?.pubkey;
const outputTokenAcc = tokenAccounts.value.find(a => a.account.data.parsed.info.mint === outputMint)?.pubkey;
if (!inputTokenAcc && !isInputSol) {
console.error('Compte de token d\'entrée introuvable');
return;
}
// Obtenir les frais de priorité
const { data } = await axios.get(`${API_URLS.BASE_HOST}${API_URLS.PRIORITY_FEE}`);
const priorityFee = data.data.default.vh;
// Obtenir le devis de swap
const { data: swapResponse } = await axios.get(`${API_URLS.SWAP_HOST}/compute/swap-base-in`, {
params: {
inputMint,
outputMint,
amount,
slippageBps: slippage * 100,
txVersion,
},
});
// Construire la transaction de swap
const { data: swapTransactions } = await axios.post(`${API_URLS.SWAP_HOST}/transaction/swap-base-in`, {
computeUnitPriceMicroLamports: String(priorityFee),
swapResponse,
txVersion,
wallet: owner.publicKey.toBase58(),
wrapSol: isInputSol,
unwrapSol: isOutputSol,
inputAccount: isInputSol ? undefined : inputTokenAcc?.toBase58(),
outputAccount: isOutputSol ? undefined : outputTokenAcc?.toBase58(),
});
// Exécuter la transaction
const transactionBuffer = Buffer.from(swapTransactions.data.transaction, 'base64');
const transaction = txVersion === 'V0' ? VersionedTransaction.deserialize(transactionBuffer) : Transaction.from(transactionBuffer);
transaction.sign([owner]);
const signature = await sendAndConfirmTransaction(connection, transaction, [owner]);
console.log(`Transaction confirmée avec la signature : ${signature}`);
}
async function main() {
// Achat du token
await executeSwap(INPUT_MINT, OUTPUT_MINT, AMOUNT, SLIPPAGE, TX_VERSION);
// Attente de 2 minutes
console.log('Attente de 2 minutes...');
await new Promise(resolve => setTimeout(resolve, WAIT_TIME_MS));
// Vente du token
await executeSwap(OUTPUT_MINT, INPUT_MINT, AMOUNT, SLIPPAGE, TX_VERSION);
}
main().catch(console.error);
Explication du script :
Configuration :
RPC_URL et WALLET_SECRET_KEY avec votre URL RPC et votre clé secrète de portefeuille respectivement.INPUT_MINT est l'adresse du token que vous utilisez pour l'achat (par exemple, SOL).OUTPUT_MINT est l'adresse du token que vous souhaitez acheter.AMOUNT est le montant à échanger, exprimé en lamports (1 SOL = 1 000 000 000 lamports).SLIPPAGE est la tolérance de glissement en pourcentage.TX_VERSION spécifie la version de la transaction ('V0' ou 'LEGACY').WAIT_TIME_MS est le temps d'attente en millisecondes (2 minutes dans cet exemple).Initialisation :
Fonction executeSwap :
Fonction main :
Remarques :