Compiling solana_rust_bot v0.1.0 (C:\solana_rust_bot)
error: async fn is not yet supported for Python functions.
Additional crates such as `pyo3-asyncio` can be used to integrate async Rust and Python. For more information, see https://github.com/PyO3/pyo3/issues/1632
--> src\lib.rs:303:5
|
303 | async fn execute_swap(
| ^^^^^
error: cannot find macro json in this scope
--> src\lib.rs:319:28
|
319 | let swap_request = json!({
| ^^^^
|
help: consider importing this macro
|
1 + use serde_json::json;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:255:25
|
255 | .json::()
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:334:21
|
334 | .json::()
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:396:21
|
396 | .json::()
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:407:21
|
407 | .json::()
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:418:21
|
418 | .json::()
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:433:21
|
433 | .json::()
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0412]: cannot find type Value in this scope
--> src\lib.rs:478:43
|
478 | fn convert_value_to_py(py: Python, value: Value) -> PyResult {
| ^^^^^ not found in this scope
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0433]: failed to resolve: use of undeclared type Value
--> src\lib.rs:480:9
|
480 | Value::Null => Ok(py.None()),
| ^^^^^ use of undeclared type Value
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0433]: failed to resolve: use of undeclared type Value
--> src\lib.rs:481:9
|
481 | Value::Bool(b) => Ok(b.into_py(py)),
| ^^^^^ use of undeclared type Value
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0433]: failed to resolve: use of undeclared type Value
--> src\lib.rs:482:9
|
482 | Value::Number(n) => Ok(n.as_f64().unwrap_or(0.0).into_py(py)),
| ^^^^^ use of undeclared type Value
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0433]: failed to resolve: use of undeclared type Value
--> src\lib.rs:483:9
|
483 | Value::String(s) => Ok(s.into_py(py)),
| ^^^^^ use of undeclared type Value
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0433]: failed to resolve: use of undeclared type Value
--> src\lib.rs:484:9
|
484 | Value::Array(arr) => {
| ^^^^^ use of undeclared type Value
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
error[E0433]: failed to resolve: use of undeclared type Value
--> src\lib.rs:491:9
|
491 | Value::Object(map) => {
| ^^^^^ use of undeclared type Value
|
help: consider importing this enum
|
1 + use serde_json::Value;
|
warning: unused import: Signer
--> src\lib.rs:12:26
|
12 | signature::{Keypair, Signer},
| ^^^^^^
|
= note: #[warn(unused_imports)] on by default
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
--> src\lib.rs:24:1
|
24 | impl Fromreqwest::Error for PyErr {
| ^^^^^--------------------^^^^^-----
| | | |
| | | pyo3::PyErr is not defined in the current crate
| | reqwest::Error is not defined in the current crate
| impl doesn't use only types from inside the current crate
|
= note: define and implement a trait or new type instead
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
--> src\lib.rs:30:1
|
30 | impl Fromanyhow::Error for PyErr {
| ^^^^^-------------------^^^^^-----
| | | |
| | | pyo3::PyErr is not defined in the current crate
| | anyhow::Error is not defined in the current crate
| impl doesn't use only types from inside the current crate
|
= note: define and implement a trait or new type instead
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
--> src\lib.rs:36:1
|
36 | impl Fromstd::time::SystemTimeError for PyErr {
| ^^^^^--------------------------------^^^^^-----
| | | |
| | | pyo3::PyErr is not defined in the current crate
| | SystemTimeError is not defined in the current crate
| impl doesn't use only types from inside the current crate
|
= note: define and implement a trait or new type instead
error[E0061]: this method takes 4 arguments but 3 arguments were supplied
--> src\lib.rs:317:26
|
317 | let quote = self.get_quote(input_mint, output_mint, amount).await?;
| ^^^^^^^^^ ---------- ----------- ------ argument #3 of type std::string::String is missing
| | |
| | expected String, found &str
| expected Python<'_>, found &str
|
note: method defined here
--> src\lib.rs:243:8
|
243 | fn get_quote<'p>(&self, py: Python<'p>, input_mint: String, output_mint: String, amount: u64) -> PyResult<...
| ^^^^^^^^^ -------------- ------------------ ------------------- -----------
help: try using a conversion method
|
317 | let quote = self.get_quote(input_mint, output_mint.to_string(), amount).await?;
| ++++++++++++
help: provide the argument
|
317 | let quote = self.get_quote(/* pyo3::Python<'_> /, / std::string::String /, / std::string::String */, amount).await?;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error[E0277]: Result<&pyo3::PyAny, pyo3::PyErr> is not a future
--> src\lib.rs:317:69
|
317 | let quote = self.get_quote(input_mint, output_mint, amount).await?;
| -^^^^^
| ||
| |Result<&pyo3::PyAny, pyo3::PyErr> is not a future
| help: remove the .await
|
= help: the trait std::future::Future is not implemented for Result<&pyo3::PyAny, pyo3::PyErr>, which is required by Result<&pyo3::PyAny, pyo3::PyErr>: IntoFuture
= note: Result<&pyo3::PyAny, pyo3::PyErr> must be a future or must implement IntoFuture to be awaited
= note: required for Result<&pyo3::PyAny, pyo3::PyErr> to implement IntoFuture
error[E0560]: struct MarketData has no field named volume_24h_volume
--> src\lib.rs:358:13
|
358 | volume_24h_volume: volume_24h, // Corrected field name
| ^^^^^^^^^^^^^^^^^ MarketData does not have this field
|
= note: available fields are: volume_24h
error[E0277]: *mut pyo3::Python<'static> cannot be sent between threads safely
--> src\lib.rs:265:28
|
265 | future_into_py(py, async move {
| -------------- ^---------
| | |
| _________|________within this {async block@src\lib.rs:265:28: 265:38}
| | |
| | required by a bound introduced by this call
266 | | let params = trader.trading_params.read().await;
267 | | let settings = trader.settings.read().await;
... |
299 | | Ok(signature.into_py(py))
300 | | })
| |^ *mut pyo3::Python<'static> cannot be sent between threads safely
|
= help: within {async block@src\lib.rs:265:28: 265:38}, the trait Send is not implemented for *mut pyo3::Python<'static>, which is required by {async block@src\lib.rs:265:28: 265:38}: Send
note: required because it appears within the type PhantomData<*mut pyo3::Python<'static>>
--> /rustc/f6e511eec7342f59a25f7c0534f1dbea00d01b14\library\core\src\marker.rs:741:12
note: required because it appears within the type impl_::not_send::NotSend
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-0.19.2\src\impl\not_send.rs:7:19
|
7 | pub(crate) struct NotSend(PhantomData<*mut Python<'static>>);
| ^^^^^^^
= note: required because it appears within the type (&pyo3::gil::GILGuard, impl_::not_send::NotSend)
note: required because it appears within the type PhantomData<(&pyo3::gil::GILGuard, impl_::not_send::NotSend)>
--> /rustc/f6e511eec7342f59a25f7c0534f1dbea00d01b14\library\core\src\marker.rs:741:12
note: required because it appears within the type pyo3::Python<'_>
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-0.19.2\src\marker.rs:378:12
|
378 | pub struct Python<'py>(PhantomData<(&'py GILGuard, NotSend)>);
| ^^^^^^
note: required because it's used within this async block
--> src\lib.rs:265:28
|
265 | future_into_py(py, async move {
| ^^^^^^^^^^
note: required by a bound in pyo3_asyncio::tokio::future_into_py
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-asyncio-0.19.0\src\tokio.rs:360:39
|
358 | pub fn future_into_py<F, T>(py: Python, fut: F) -> PyResult<&PyAny>
| -------------- required by a bound in this function
359 | where
360 | F: Future<Output = PyResult> + Send + 'static,
| ^^^^ required by this bound in future_into_py
error[E0277]: *mut pyo3::Python<'static> cannot be shared between threads safely
--> src\lib.rs:265:28
|
265 | future_into_py(py, async move {
| --------------^
| | |
| | required by a bound introduced by this call
266 | | let params = trader.trading_params.read().await;
267 | | let settings = trader.settings.read().await;
... |
299 | | Ok(signature.into_py(py))
300 | | })
| |__^ *mut pyo3::Python<'static> cannot be shared between threads safely
|
= help: within pyo3::gil::GILGuard, the trait Sync is not implemented for *mut pyo3::Python<'static>, which is required by {async block@src\lib.rs:265:28: 265:38}: Send
note: required because it appears within the type PhantomData<*mut pyo3::Python<'static>>
--> /rustc/f6e511eec7342f59a25f7c0534f1dbea00d01b14\library\core\src\marker.rs:741:12
note: required because it appears within the type impl_::not_send::NotSend
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-0.19.2\src\impl\not_send.rs:7:19
|
7 | pub(crate) struct NotSend(PhantomData<*mut Python<'static>>);
| ^^^^^^^
note: required because it appears within the type GILPool
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-0.19.2\src\gil.rs:361:12
|
361 | pub struct GILPool {
| ^^^^^^^
note: required because it appears within the type ManuallyDrop<GILPool>
--> /rustc/f6e511eec7342f59a25f7c0534f1dbea00d01b14\library\core\src\mem\manually_drop.rs:51:12
note: required because it appears within the type pyo3::gil::GILGuard
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-0.19.2\src\gil.rs:161:19
|
161 | pub(crate) struct GILGuard {
| ^^^^^^^^
= note: required for &pyo3::gil::GILGuard to implement Send
= note: required because it appears within the type (&pyo3::gil::GILGuard, impl_::not_send::NotSend)
note: required because it appears within the type PhantomData<(&pyo3::gil::GILGuard, impl_::not_send::NotSend)>
--> /rustc/f6e511eec7342f59a25f7c0534f1dbea00d01b14\library\core\src\marker.rs:741:12
note: required because it appears within the type pyo3::Python<'_>
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-0.19.2\src\marker.rs:378:12
|
378 | pub struct Python<'py>(PhantomData<(&'py GILGuard, NotSend)>);
| ^^^^^^
note: required because it's used within this async block
--> src\lib.rs:265:28
|
265 | future_into_py(py, async move {
| ^^^^^^^^^^
note: required by a bound in pyo3_asyncio::tokio::future_into_py
--> C:\Users\Orsen.cargo\registry\src\index.crates.io-6f17d22bba15001f\pyo3-asyncio-0.19.0\src\tokio.rs:360:39
|
358 | pub fn future_into_py<F, T>(py: Python, fut: F) -> PyResult<&PyAny>
| -------------- required by a bound in this function
359 | where
360 | F: Future<Output = PyResult> + Send + 'static,
| ^^^^ required by this bound in
warning: unused variable: py
--> src\lib.rs:218:12
|
218 | fn new(py: Python, config_path: String, keypair_bytes: Vec) -> PyResult {
| ^^ help: if this is intentional, prefix it with an underscore: _py
|
= note: #[warn(unused_variables)] on by default
Some errors have detailed explanations: E0061, E0117, E0277, E0412, E0433, E0560.
For more information about an error, try rustc --explain E0061.
warning: solana_rust_bot (lib) generated 2 warnings
error: could not compile solana_rust_bot (lib) due to 23 previous errors; 2 warnings emitted
2024-11-17T06:09:00.980890Z INFO build_wheels: maturin::build_context: close time.busy=672ms time.idle=1.30µs
💥 maturin failed
Caused by: Failed to build a native library through cargo
Caused by: Cargo build finished with "exit code: 101": "cargo" "rustc" "--jobs" "13" "--features" "pyo3/extension-module" "--message-format" "json-render-diagnostics" "--manifest-path" "C:\\solana_rust_bot\\Cargo.toml" "--release" "--lib"
(pytorch_cuda) C:\solana_rust_bot> fix entire file please use anyhow::{anyhow, Result};
use pyo3::{prelude::*, exceptions::PyRuntimeError};
use pyo3_asyncio::tokio::future_into_py;
use pyo3::types::{PyDict, PyList}; // Required for converting to Python types
use tokio::runtime::Runtime;
use tokio::sync::RwLock;
use serde::{Serialize, Deserialize};
use dashmap::DashMap;
use reqwest::Client;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{
signature::{Keypair, Signer},
transaction::Transaction,
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use std::{
sync::{Arc, Once},
time::{Duration, SystemTime, UNIX_EPOCH},
fs::File,
io::Read,
};
// Error conversion functions
impl Fromreqwest::Error for PyErr {
fn from(err: reqwest::Error) -> Self {
PyRuntimeError::new_err(err.to_string())
}
}
impl Fromanyhow::Error for PyErr {
fn from(err: anyhow::Error) -> Self {
PyRuntimeError::new_err(err.to_string())
}
}
impl Fromstd::time::SystemTimeError for PyErr {
fn from(err: std::time::SystemTimeError) -> Self {
PyRuntimeError::new_err(err.to_string())
}
}
// Constants
pub const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
pub const SOL_MINT: &str = "So1111111111111111111111111111111111111112";
// Runtime management
static RUNTIME_INIT: Once = Once::new();
static mut RUNTIME: Option = None;
// Configuration structures
#[derive(Serialize, Deserialize, Debug)]
pub struct NetworkConfig {
pub api_key: String,
pub rpc_url: String,
pub ws_url: String,
pub backup_rpc: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SnipingConfig {
pub buy_amount: f64,
pub max_slippage: f64,
pub priority_fee: u64,
pub min_liquidity: f64,
pub min_market_cap: f64,
pub min_volume: f64,
pub buyer_seller_ratio: f64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ScalpingConfig {
pub position_size: f64,
pub take_profit: f64,
pub stop_loss: f64,
pub max_position_size: f64,
pub scaling_threshold: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PerformanceConfig {
pub max_concurrent_trades: usize,
pub price_impact_threshold: f64,
pub volatility_threshold: f64,
pub update_interval_ms: usize,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PoolConfig {
pub token: String,
pub raydium_pool: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
pub network: NetworkConfig,
pub sniping: SnipingConfig,
pub scalping: ScalpingConfig,
pub performance: PerformanceConfig,
pub pools: Vec,
}
// Trading Parameters
#[derive(Debug, Clone)]
pub struct TradingParameters {
pub slippage_tolerance: f64,
pub min_profit_threshold: f64,
pub max_position_size: f64,
pub scaling_factor: f64,
pub priority_fee_multiplier: u64,
pub retry_attempts: u32,
pub cooldown_period: Duration,
pub volume_requirement: f64,
pub liquidity_requirement: f64,
}
impl Default for TradingParameters {
fn default() -> Self {
Self {
slippage_tolerance: 1.0,
min_profit_threshold: 0.5,
max_position_size: 5.0,
scaling_factor: 1.5,
priority_fee_multiplier: 2,
retry_attempts: 3,
cooldown_period: Duration::from_secs(1),
volume_requirement: 10000.0,
liquidity_requirement: 5000.0,
}
}
}
// Trade and Market Data Structures
#[pyclass]
#[derive(Clone, Debug)]
pub struct ScalperSettings {
#[pyo3(get, set)]
pub min_price_change: f64,
#[pyo3(get, set)]
pub max_position_size: f64,
#[pyo3(get, set)]
pub take_profit: f64,
#[pyo3(get, set)]
pub stop_loss: f64,
#[pyo3(get, set)]
pub max_slippage: f64,
#[pyo3(get, set)]
pub min_volume: f64,
#[pyo3(get, set)]
pub priority_fee: u64,
}
#[pymethods]
impl ScalperSettings {
#[new]
fn new() -> Self {
Self {
min_price_change: 0.5,
max_position_size: 0.1,
take_profit: 1.0,
stop_loss: -0.5,
max_slippage: 0.5,
min_volume: 1000.0,
priority_fee: 15000,
}
}
}
#[pyclass]
#[derive(Clone, Debug)]
pub struct Trade {
#[pyo3(get)]
pub token: String,
#[pyo3(get)]
pub entry_price: f64,
#[pyo3(get)]
pub current_price: f64,
#[pyo3(get)]
pub size: f64,
#[pyo3(get)]
pub profit_loss: f64,
#[pyo3(get)]
pub timestamp: i64,
#[pyo3(get)]
pub status: String,
}
#[pyclass]
#[derive(Clone, Debug, Default)]
pub struct MarketData {
#[pyo3(get)]
pub price: f64,
#[pyo3(get)]
pub volume_24h: f64,
#[pyo3(get)]
pub liquidity: f64,
#[pyo3(get)]
pub price_change_24h: f64,
#[pyo3(get)]
pub timestamp: i64,
}
// Main Trading Struct
#[pyclass]
pub struct SolanaTrader {
settings: Arc<RwLock>,
http_client: Arc,
rpc_client: Arc,
active_trades: Arc<DashMap<String, Trade>>,
market_data: Arc<DashMap<String, MarketData>>,
keypair: Arc,
trading_params: Arc<RwLock>,
runtime: &'static Runtime,
}
#[pymethods]
impl SolanaTrader {
#[new]
fn new(py: Python, config_path: String, keypair_bytes: Vec) -> PyResult {
let runtime = get_runtime()?;
let keypair = Keypair::from_bytes(&keypair_bytes).map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;
let config = load_config(&config_path).map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;
let http_client = Client::builder()
.timeout(Duration::from_secs(5))
.pool_max_idle_per_host(1) // Set pool_max_idle_per_host to 1
.build()
.map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;
let settings = Arc::new(RwLock::new(ScalperSettings::new()));
Ok(Self {
settings,
http_client: Arc::new(http_client),
rpc_client: Arc::new(RpcClient::new(config.network.rpc_url)),
active_trades: Arc::new(DashMap::new()),
market_data: Arc::new(DashMap::new()),
keypair: Arc::new(keypair),
trading_params: Arc::new(RwLock::new(TradingParameters::default())),
runtime,
})
}
fn get_quote<'p>(&self, py: Python<'p>, input_mint: String, output_mint: String, amount: u64) -> PyResult<&'p PyAny> {
let trader = self.clone();
future_into_py(py, async move {
let url = format!(
"{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50&onlyDirectRoutes=true&wrapUnwrapSOL=true",
JUPITER_API, input_mint, output_mint, amount
);
let response = trader.http_client.get(&url)
.send()
.await
.map_err(|e| convert_reqwest_err(e))?
.json::<Value>()
.await
.map_err(|e| convert_serde_err(e))?;
Ok(convert_value_to_py(py, response)?)
})
}
fn execute_trade<'p>(&self, py: Python<'p>, token: String, is_buy: bool) -> PyResult<&'p PyAny> {
let trader = self.clone();
future_into_py(py, async move {
let params = trader.trading_params.read().await;
let settings = trader.settings.read().await;
if !trader.validate_trade_params(&token, is_buy, params.max_position_size).await? {
return Err(PyRuntimeError::new_err("Trade validation failed"));
}
let amount = if is_buy {
settings.max_position_size
} else {
trader.active_trades.get(&token)
.map(|t| t.size)
.unwrap_or(settings.max_position_size)
};
let lamports = (amount * 1e9) as u64;
let signature = trader.execute_swap(&token, is_buy, lamports, &settings).await?;
if is_buy {
let market_data = trader.fetch_market_data_internal(&token).await?;
trader.active_trades.insert(token.clone(), Trade {
token: token.clone(),
entry_price: market_data.price,
current_price: market_data.price,
size: amount,
profit_loss: 0.0,
timestamp: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64,
status: "ACTIVE".to_string(),
});
} else {
trader.active_trades.remove(&token);
}
Ok(signature.into_py(py))
})
}
async fn execute_swap(
&self,
token: &str,
is_buy: bool,
amount: u64,
settings: &ScalperSettings,
) -> Result<String> {
let (input_mint, output_mint) = if is_buy {
(SOL_MINT, token)
} else {
(token, SOL_MINT)
};
// Get the quote
let quote = self.get_quote(input_mint, output_mint, amount).await?;
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": self.keypair.pubkey().to_string(),
"wrapUnwrapSOL": true,
"computeUnitPriceMicroLamports": settings.priority_fee,
"priorityFeeLamports": settings.priority_fee,
"asLegacyTransaction": false, // Corrected key
"maxAccounts": 64
});
let swap_response = self.http_client
.post(format!("{}/swap", JUPITER_API))
.json(&swap_request)
.send()
.await?
.json::<Value>()
.await?;
let transaction_data = swap_response["swapTransaction"]
.as_str()
.ok_or_else(|| anyhow!("Invalid swap transaction format"))?;
// Decode and send the transaction
let transaction = decode_transaction(transaction_data)?;
let signature = self.rpc_client.send_transaction(&transaction).await?;
Ok(signature.to_string())
}
async fn fetch_market_data_internal(&self, token: &str) -> Result<MarketData> {
let (price, volume_24h, liquidity) = tokio::try_join!(
self.fetch_price(token),
self.fetch_volume(token),
self.fetch_liquidity(token)
)?;
let price_change_24h = self.calculate_price_change(token).await?;
Ok(MarketData {
price,
volume_24h_volume: volume_24h, // Corrected field name
liquidity,
price_change_24h,
timestamp: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64,
})
}
async fn validate_trade_params(&self, token: &str, is_buy: bool, amount: f64) -> Result<bool> {
let params = self.trading_params.read().await;
if amount > params.max_position_size {
return Ok(false);
}
let market_data = self.fetch_market_data_internal(token).await?;
if market_data.volume_24h < params.volume_requirement ||
market_data.liquidity < params.liquidity_requirement {
return Ok(false);
}
if !is_buy {
if let Some(trade) = self.active_trades.get(token) {
let current_profit = (market_data.price - trade.entry_price) / trade.entry_price * 100.0;
if current_profit < params.min_profit_threshold {
return Ok(false);
}
}
}
Ok(true)
}
async fn fetch_price(&self, token: &str) -> Result<f64> {
let response = self.http_client
.get(format!("{}/price?token={}", JUPITER_API, token))
.send()
.await?
.json::<Value>()
.await?;
response["price"].as_f64().ok_or_else(|| anyhow!("Failed to parse price"))
}
async fn fetch_volume(&self, token: &str) -> Result<f64> {
let response = self.http_client
.get(format!("{}/volume?token={}", JUPITER_API, token))
.send()
.await?
.json::<Value>()
.await?;
response["volume"].as_f64().ok_or_else(|| anyhow!("Failed to parse volume"))
}
async fn fetch_liquidity(&self, token: &str) -> Result<f64> {
let response = self.http_client
.get(format!("{}/liquidity?token={}", JUPITER_API, token))
.send()
.await?
.json::<Value>()
.await?;
response["liquidity"].as_f64().ok_or_else(|| anyhow!("Failed to parse liquidity"))
}
async fn calculate_price_change(&self, token: &str) -> Result<f64> {
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let day_ago = now - 24 * 3600;
// Fetch price history over 24 hours
let historical_response = self.http_client
.get(format!("{}/price/history?token={}&startTime={}&endTime={}", JUPITER_API, token, day_ago, now))
.send()
.await?
.json::<Value>()
.await?;
let prices = historical_response["prices"]
.as_array()
.ok_or_else(|| anyhow!("Invalid price history format"))?;
if prices.is_empty() {
return Ok(0.0);
}
let start_price = prices.first().and_then(|p| p["price"].as_f64()).unwrap_or(0.0);
let end_price = prices.last().and_then(|p| p["price"].as_f64()).unwrap_or(0.0);
if start_price == 0.0 {
return Ok(0.0);
}
Ok((end_price - start_price) / start_price * 100.0)
}
}
// Helper functions
fn decode_transaction(data: &str) -> Result {
let decoded = BASE64.decode(data)?;
bincode::deserialize(&decoded).map_err(|e| anyhow!("Failed to deserialize transaction: {}", e))
}
fn load_config(file_path: &str) -> Result {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let config: Config = serde_json::from_str(&contents)?;
Ok(config)
}
fn get_runtime() -> PyResult<&'static Runtime> {
unsafe {
RUNTIME_INIT.call_once(|| {
RUNTIME = Some(Runtime::new().expect("Failed to create Tokio runtime"));
});
RUNTIME.as_ref().ok_or_else(|| PyErr::new::<PyRuntimeError, _>("Runtime not initialized"))
}
}
fn convert_value_to_py(py: Python, value: Value) -> PyResult {
match value {
Value::Null => Ok(py.None()),
Value::Bool(b) => Ok(b.into_py(py)),
Value::Number(n) => Ok(n.as_f64().unwrap_or(0.0).into_py(py)),
Value::String(s) => Ok(s.into_py(py)),
Value::Array(arr) => {
let list = PyList::empty(py);
for item in arr {
list.append(convert_value_to_py(py, item)?)?;
}
Ok(list.into())
}
Value::Object(map) => {
let dict = PyDict::new(py);
for (k, v) in map {
dict.set_item(k, convert_value_to_py(py, v)?)?;
}
Ok(dict.into())
}
}
}
fn convert_reqwest_err(e: reqwest::Error) -> PyErr {
PyRuntimeError::new_err(e.to_string())
}
fn convert_serde_err(e: serde_json::Error) -> PyErr {
PyRuntimeError::new_err(e.to_string())
}
#[pymodule]
fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::()?;
m.add_class::()?;
m.add_class::()?;
m.add_class::()?;
Ok(())
}