use {
anyhow::Result,
log::{error, info},
solana_sdk::{
signature::Signer,
signer::keypair::Keypair,
},
std::{fs, sync::Arc, time::Duration},
solana_rust_bot_lib::TradeManager,
tokio::{time::sleep, signal::ctrl_c},
};
#[tokio::main]
async fn main() -> Result<()> {
// Initialize the logger
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.format_timestamp_millis()
.init();
info!("🚀 Initializing trading system");
// Load keypair
let keypair_bytes = fs::read("keypair.bin")?;
let keypair = Keypair::from_bytes(&keypair_bytes)?;
info!("👛 Loaded wallet: {}", keypair.pubkey());
// Create trade manager
let trade_manager = Arc::new(TradeManager::new(keypair));
info!("✨ Trade manager initialized");
// Set up graceful shutdown
let manager_clone = trade_manager.clone();
tokio::spawn(async move {
match ctrl_c().await {
Ok(()) => {
info!("🛑 Shutdown signal received");
// Logic for saving state if needed could go here
std::process::exit(0);
}
Err(e) => error!("Failed to handle shutdown signal: {}", e),
}
});
// Main trading loop with error recovery
loop {
match trade_manager.clone().start().await {
Ok(()) => info!("Trading cycle completed successfully"),
Err(e) => {
error!("❌ Error in trading cycle: {}", e);
sleep(Duration::from_secs(5)).await; // Wait before repeating if an error occurs
}
}
// Print trading stats
match trade_manager.get_trade_stats().await {
Ok(stats) => {
info!("📊 Trading Stats:\n{}", serde_json::to_string_pretty(&stats)?);
}
Err(e) => {
error!("Failed to get trading stats: {}", e);
}
}
sleep(Duration::from_secs(60)).await; // 1 minute delay between cycles
}
} main.rs and /// next is lib.rs use std::{
sync::Arc,
time::{Duration, Instant},
tokio::time::sleep,
serde_json::{json, Value},
anyhow::{anyhow, Result},
log::{error, info, warn},
dashmap::DashMap,
solana_client::rpc_client::RpcClient,
solana_sdk::{
signature::Keypair,
signer::Signer,
commitment_config::CommitmentConfig,
},
tokio_tungstenite::{
connect_async,
WebSocketStream,
MaybeTlsStream,
},
tokio::net::TcpStream,
futures_util::stream::StreamExt,
serde::Deserialize,
};
// Constants
pub const JUPITER_V6_API: &str = "https://quote-api.jup.ag/v6";
pub const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
pub const WS_URL: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com";
pub const SOL_MINT: &str = "So11111111111111111111111111111111111111112";
pub const PRIORITY_FEE: u64 = 15000; // Set appropriate fees
pub const TRADE_AMOUNT_SOL: f64 = 0.005; // Testing with 0.005 SOL
pub const MIN_LIQUIDITY_USD: f64 = 1000.0;
pub const MAX_LIQUIDITY_USD: f64 = 20000.0;
pub const SLIPPAGE_BPS: u32 = 1000; // 10%
pub const POLL_INTERVAL: Duration = Duration::from_secs(1);
pub const MAX_NEW_TOKEN_AGE: u64 = 30; // Tokens created in the last 30 seconds are eligible
type WebSocketConnection = WebSocketStream<MaybeTlsStream>;
#[derive(Debug, Clone)]
struct ActiveTrade {
token_mint: String,
entry_price: f64,
amount: u64,
last_price: f64,
take_profit: f64,
stop_loss: f64,
volume_24h: f64,
liquidity: f64,
}
#[derive(Debug)]
struct TokenData {
mint_authority_revoked: bool,
liquidity_locked: bool,
creation_time: Instant,
}
#[derive(Deserialize)]
struct HeliusEvent {
token_address: String,
// Add other important fields based on the expected WebSocket response
}
pub struct TradeManager {
rpc_client: Arc,
keypair: Arc,
active_trades: Arc<DashMap<String, ActiveTrade>>,
ws_connection: Arc<tokio::sync::Mutex<Option>>,
http_client: Arcreqwest::Client,
}
impl TradeManager {
pub fn new(keypair: Keypair) -> Self {
let rpc_client = RpcClient::new_with_commitment(
HELIUS_RPC.to_string(),
CommitmentConfig::confirmed(),
);
info!("Successfully connected to Helius RPC");
Self {
rpc_client: Arc::new(rpc_client),
keypair: Arc::new(keypair),
active_trades: Arc::new(DashMap::new()),
ws_connection: Arc::new(tokio::sync::Mutex::new(None)),
http_client: Arc::new(reqwest::Client::new()),
}
}
async fn setup_websocket(&self) -> Result<()> {
let mut ws_guard = self.ws_connection.lock().await;
if ws_guard.is_none() {
let (ws_stream, _) = connect_async(WS_URL).await?;
*ws_guard = Some(ws_stream);
info!("✅ WebSocket connected to {}", WS_URL);
}
Ok(())
}
pub async fn start(self: Arc<Self>) -> Result<()> {
info!("🚀 Starting trading system");
self.setup_websocket().await?;
let manager_clone = self.clone(); // Clone the Arc<TradeManager>
tokio::spawn(async move {
if let Err(e) = manager_clone.handle_events().await {
error!("Event handling error: {}", e);
}
});
Ok(())
}
async fn handle_events(&self) -> Result<()> {
let mut ws_guard = self.ws_connection.lock().await;
let ws_stream = ws_guard.as_mut().unwrap();
let mut incoming = ws_stream.fuse();
while let Some(message) = incoming.next().await {
match message {
Ok(tokio_tungstenite::tungstenite::Message::Text(text)) => {
let event: HeliusEvent = serde_json::from_str(&text)?;
// Check if the token meets criteria for buying
if self.should_buy_token(&event.token_address).await? {
info!("🆕 New token detected: {}", event.token_address);
if let Err(e) = self.execute_buy(&event.token_address).await {
error!("Failed to execute buy for {}: {}", event.token_address, e);
}
}
}
Ok(_) => {} // Handle other message types if necessary
Err(e) => {
error!("WebSocket error: {}", e);
break; // Exit on critical error
}
}
}
Ok(())
}
async fn should_buy_token(&self, token_mint: &str) -> Result<bool> {
let token_data = self.get_token_info(token_mint).await?;
let current_time = Instant::now();
let token_age = current_time
.duration_since(token_data.creation_time)
.as_secs();
if token_data.mint_authority_revoked &&
token_data.liquidity_locked &&
token_age <= MAX_NEW_TOKEN_AGE {
return Ok(true);
}
Ok(false)
}
pub async fn execute_buy(&self, token_mint: &str) -> Result<String> {
info!("🚀 Initiating buy for {}", token_mint);
let mut attempts = 0;
const MAX_ATTEMPTS: u32 = 3;
while attempts < MAX_ATTEMPTS {
let (volume, liquidity) = self.get_token_metrics(token_mint).await?;
if !self.validate_trading_requirements(volume, liquidity)? {
return Err(anyhow!("Token doesn't meet trading requirements"));
}
let amount_lamports = (TRADE_AMOUNT_SOL * 1e9) as u64;
let quote = self.get_quote(SOL_MINT, token_mint, amount_lamports).await;
match quote {
Ok(quote) => {
let swap_data = self.get_swap_data("e).await?;
let signature = self.send_priority_tx(&swap_data).await?;
self.verify_transaction(&signature).await?;
let price = self.fetch_token_price(token_mint).await?;
self.record_trade(token_mint, price, amount_lamports, volume, liquidity).await;
info!("✅ Buy executed | Signature: {}", signature);
return Ok(signature);
}
Err(e) => {
attempts += 1;
warn!("Failed to buy {}: Attempt {}/{} -- {}", token_mint, attempts, MAX_ATTEMPTS, e);
let backoff_time = 2u64.pow(attempts as u32);
sleep(Duration::from_secs(backoff_time)).await; // Exponential backoff
}
}
}
Err(anyhow!("Failed to execute buy for {} after {} attempts", token_mint, MAX_ATTEMPTS))
}
pub async fn execute_sell(&self, token_mint: &str) -> Result<String> {
let trade = match self.active_trades.get(token_mint) {
Some(t) => t,
None => return Err(anyhow!("No active trade found for {}", token_mint)),
};
info!("🔄 Executing sell for {} | Amount: {}", token_mint, trade.amount);
let mut attempts = 0;
const MAX_ATTEMPTS: u32 = 3;
while attempts < MAX_ATTEMPTS {
let quote = self.get_quote(token_mint, SOL_MINT, trade.amount).await;
match quote {
Ok(quote) => {
let swap_data = self.get_swap_data("e).await?;
let signature = self.send_priority_tx(&swap_data).await?;
self.verify_transaction(&signature).await?;
info!("✅ Sell executed | Signature: {}", signature);
self.active_trades.remove(token_mint);
return Ok(signature);
}
Err(e) => {
attempts += 1;
warn!("Failed to sell {}: Attempt {}/{} -- {}", token_mint, attempts, MAX_ATTEMPTS, e);
let backoff_time = 2u64.pow(attempts as u32);
sleep(Duration::from_secs(backoff_time)).await; // Exponential backoff
}
}
}
Err(anyhow!("Failed to execute sell for {} after {} attempts", token_mint, MAX_ATTEMPTS))
}
async fn get_token_metrics(&self, token_mint: &str) -> Result<(f64, f64)> {
let request = json!({
"jsonrpc": "2.0",
"id": "metrics",
"method": "getTokenData",
"params": [token_mint]
});
let response = self.http_client
.post(HELIUS_RPC)
.json(&request)
.send()
.await?
.json::<Value>()
.await?;
let volume = response["result"]["volume24h"]
.as_f64()
.ok_or_else(|| anyhow!("Invalid volume data"))?;
let liquidity = response["result"]["liquidity"]
.as_f64()
.ok_or_else(|| anyhow!("Invalid liquidity data"))?;
Ok((volume, liquidity))
}
fn validate_trading_requirements(&self, volume: f64, liquidity: f64) -> Result<bool> {
if liquidity < MIN_LIQUIDITY_USD || liquidity > MAX_LIQUIDITY_USD {
warn!("Liquidity outside range: ${}", liquidity);
return Ok(false);
}
if volume < MIN_LIQUIDITY_USD * 0.1 {
warn!("Insufficient 24h volume: ${}", volume);
return Ok(false);
}
Ok(true)
}
async fn get_quote(&self, input_mint: &str, output_mint: &str, amount: u64) -> Result<Value> {
let url = format!(
"{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps={}&onlyDirectRoutes=true",
JUPITER_V6_API, input_mint, output_mint, amount, SLIPPAGE_BPS
);
info!("Fetching quote from Jupiter API");
let response = self.http_client
.get(&url)
.send()
.await?
.json::<Value>()
.await?;
if response.get("error").is_some() {
return Err(anyhow!("Jupiter error: {}", response["error"]));
}
Ok(response)
}
async fn get_swap_data(&self, quote: &Value) -> Result<String> {
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": self.keypair.pubkey().to_string(),
"computeUnitPriceMicroLamports": PRIORITY_FEE,
"asLegacyTransaction": false
});
let response = self.http_client
.post(format!("{}/swap", JUPITER_V6_API))
.json(&swap_request)
.send()
.await?
.json::<Value>()
.await?;
response["swapTransaction"]
.as_str()
.ok_or_else(|| anyhow!("Invalid swap response"))
.map(String::from)
}
async fn send_priority_tx(&self, swap_data: &str) -> Result<String> {
let request = json!({
"jsonrpc": "2.0",
"id": "helius-priority",
"method": "sendTransaction",
"params": [
swap_data,
{
"encoding": "base64",
"maxRetries": 0,
"skipPreflight": true,
"priorityFee": PRIORITY_FEE
}
]
});
let response = self.http_client
.post(HELIUS_RPC)
.json(&request)
.send()
.await?
.json::<Value>()
.await?;
response["result"]
.as_str()
.ok_or_else(|| anyhow!("Invalid transaction response"))
.map(String::from)
}
async fn verify_transaction(&self, signature: &str) -> Result<()> {
info!("Verifying transaction: {}", signature);
for _ in 0..10 {
match self.rpc_client.get_signature_status(&signature.parse()?)? {
Some(Ok(_)) => return Ok(()),
Some(Err(e)) => return Err(anyhow!("Transaction failed: {}", e)),
None => sleep(Duration::from_millis(500)).await,
}
}
Err(anyhow!("Transaction verification timeout"))
}
async fn fetch_token_price(&self, token_mint: &str) -> Result<f64> {
let request = json!({
"jsonrpc": "2.0",
"id": "price-check",
"method": "getTokenPrice",
"params": [token_mint]
});
let response = self.http_client
.post(HELIUS_RPC)
.json(&request)
.send()
.await?
.json::<Value>()
.await?;
response["result"]["price"]
.as_f64()
.ok_or_else(|| anyhow!("Invalid price response"))
}
async fn record_trade(&self, token_mint: &str, price: f64, amount: u64, volume: f64, liquidity: f64) {
let trade = ActiveTrade {
token_mint: token_mint.to_string(),
entry_price: price,
amount,
last_price: price,
take_profit: price * 1.20, // 20% profit target
stop_loss: price * 0.95,
volume_24h: volume,
liquidity,
};
self.active_trades.insert(token_mint.to_string(), trade);
info!("Recorded trade for {}", token_mint);
}
async fn get_token_info(&self, token_mint: &str) -> Result<TokenData> {
let request = json!({
"jsonrpc": "2.0",
"id": "get-token-info",
"method": "getTokenData",
"params": [token_mint]
});
let response = self.http_client
.post(HELIUS_RPC)
.json(&request)
.send()
.await?
.json::<Value>()
.await?;
let mint_authority_revoked = response["result"]["is_mint_authority_revoked"]
.as_bool()
.ok_or_else(|| anyhow!("Invalid data for mint authority revocation status"))?;
let liquidity_locked = response["result"]["is_liquidity_locked"]
.as_bool()
.ok_or_else(|| anyhow!("Invalid data for liquidity locked status"))?;
let creation_time = Instant::now(); // Replace with actual creation timestamp retrieval
Ok(TokenData { mint_authority_revoked, liquidity_locked, creation_time })
}
}