Skip to main content

orca_sdk/
price.rs

1use std::time::Duration;
2
3use super::*;
4use crate::{monitoring::PriceData, types::OrcaResult};
5use base64::{Engine, prelude::BASE64_STANDARD};
6use solana_transaction_status::{
7    EncodedTransaction, UiInstruction, UiMessage, UiParsedInstruction, UiTransactionEncoding,
8};
9
10impl OrcaClient {
11    /// Get token price from a liquidity pool
12    ///
13    /// # Arguments
14    /// base_mint - Base token mint address
15    /// quote_mint - Quote token mint address
16    ///
17    /// # Example
18    /// ```rust
19    /// let price = client.get_token_price_from_pool(
20    ///     "So11111111111111111111111111111111111111112", // SOL
21    ///     "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"  // USDC
22    /// ).await?;
23    /// println!("SOL/USDC price: {}", price);
24    /// ```
25    pub async fn get_token_price_from_pool(
26        &self,
27        base_mint: &str,
28        quote_mint: &str,
29    ) -> OrcaResult<f64> {
30        let pools = self.get_pools_by_token_onchain(base_mint).await?;
31        for pool_address in pools {
32            if let Ok(pool_info) = self.get_pool_state_onchain(&pool_address).await {
33                if (pool_info.token_mint_a == base_mint && pool_info.token_mint_b == quote_mint)
34                    || (pool_info.token_mint_a == quote_mint && pool_info.token_mint_b == base_mint)
35                {
36                    return self
37                        .derive_price_from_pool_state(&pool_info, base_mint)
38                        .await;
39                }
40            }
41        }
42        Err(OrcaError::Error("No pool found for token pair".to_string()))
43    }
44
45    /// Get price history from on-chain transactions
46    ///
47    /// # Arguments
48    /// pool_address - Pool address to get history for
49    /// limit - Maximum number of price points to return
50    ///
51    /// # Example
52    /// ```rust
53    /// let price_history = client.get_price_history_from_chain(
54    ///     "whirlpool_address_here",
55    ///     100
56    /// ).await?;
57    /// for data in price_history {
58    ///     println!("Time: {}, Price: {}", data.timestamp, data.price);
59    /// }
60    /// ```
61    pub async fn get_price_history_from_chain(
62        &self,
63        pool_address: &str,
64        limit: usize,
65    ) -> OrcaResult<Vec<PriceData>> {
66        let client = self
67            .solana
68            .client
69            .as_ref()
70            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
71        let pool_pubkey = Pubkey::from_str(pool_address)
72            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
73        let base_pool_info = self.get_pool_state_onchain(pool_address).await?;
74        let base_liquidity = base_pool_info.liquidity;
75        let signatures = client
76            .get_signatures_for_address(&pool_pubkey)
77            .await
78            .map_err(|e| OrcaError::Error(format!("Failed to get signatures: {}", e)))?;
79        let mut price_history = Vec::new();
80        for sig_info in signatures.iter().take(limit) {
81            let signature = Signature::from_str(&sig_info.signature)
82                .map_err(|e| OrcaError::Error(format!("Invalid signature: {}", e)))?;
83            if let Ok(transaction) = client
84                .get_transaction(&signature, UiTransactionEncoding::Base64)
85                .await
86            {
87                if let Some(block_time) = transaction.block_time {
88                    if let Some(price) = self
89                        .extract_price_from_transaction(&transaction.transaction.transaction)
90                        .await
91                    {
92                        price_history.push(PriceData {
93                            timestamp: block_time as u64,
94                            price,
95                            liquidity: base_liquidity,
96                        });
97                    }
98                }
99            }
100        }
101        Ok(price_history)
102    }
103
104    async fn extract_price_from_transaction(
105        &self,
106        transaction: &EncodedTransaction,
107    ) -> Option<f64> {
108        match transaction {
109            EncodedTransaction::Json(encoded_tx) => {
110                self.extract_price_from_message(&encoded_tx.message).await
111            }
112            _ => None,
113        }
114    }
115
116    async fn extract_price_from_message(&self, message: &UiMessage) -> Option<f64> {
117        match message {
118            UiMessage::Parsed(parsed_msg) => {
119                for instruction in &parsed_msg.instructions {
120                    if let Some(price) = self
121                        .analyze_instruction_for_price(instruction, message)
122                        .await
123                    {
124                        return Some(price);
125                    }
126                }
127            }
128            UiMessage::Raw(raw_msg) => {
129                for compiled_instruction in &raw_msg.instructions {
130                    let instruction = solana_transaction_status::UiInstruction::Compiled(
131                        compiled_instruction.clone(),
132                    );
133                    if let Some(price) = self
134                        .analyze_instruction_for_price(&instruction, message)
135                        .await
136                    {
137                        return Some(price);
138                    }
139                }
140            }
141        }
142        None
143    }
144
145    async fn analyze_instruction_for_price(
146        &self,
147        instruction: &UiInstruction,
148        message: &solana_transaction_status::UiMessage,
149    ) -> Option<f64> {
150        match instruction {
151            UiInstruction::Parsed(parsed) => {
152                if let Some(program_name) = Self::get_instruction_program(parsed) {
153                    if program_name.contains("swap")
154                        || program_name.contains("orca")
155                        || program_name.contains("token")
156                        || program_name.contains("amm")
157                    {
158                        if let Some(amounts) = Self::extract_token_amounts_from_instruction(parsed)
159                        {
160                            if amounts.len() >= 2 && amounts[0] > 0.0 {
161                                return Some(amounts[1] / amounts[0]);
162                            }
163                        }
164                    }
165                }
166            }
167            UiInstruction::Compiled(compiled) => {
168                if let Some(price) = self.analyze_compiled_instruction(compiled, message).await {
169                    return Some(price);
170                }
171            }
172        }
173        None
174    }
175
176    fn get_instruction_program(instruction: &UiParsedInstruction) -> Option<String> {
177        match instruction {
178            UiParsedInstruction::Parsed(parsed) => Some(parsed.program.clone()),
179            UiParsedInstruction::PartiallyDecoded(partial) => Some(partial.program_id.to_string()),
180        }
181    }
182
183    fn extract_token_amounts_from_instruction(
184        instruction: &solana_transaction_status::UiParsedInstruction,
185    ) -> Option<Vec<f64>> {
186        let mut amounts = Vec::new();
187        match instruction {
188            solana_transaction_status::UiParsedInstruction::Parsed(parsed) => {
189                if let parsed_data = &parsed.parsed {
190                    if let serde_json::Value::Object(map) = parsed_data {
191                        for (key, value) in map {
192                            if key.contains("amount")
193                                || key.contains("token")
194                                || key.contains("quantity")
195                                || key.contains("value")
196                                || key.contains("source")
197                                || key.contains("destination")
198                            {
199                                if let Some(amount) = Self::parse_amount_from_value(value) {
200                                    amounts.push(amount);
201                                }
202                            }
203                        }
204                    }
205                }
206            }
207            solana_transaction_status::UiParsedInstruction::PartiallyDecoded(partial) => {
208                // To be realized
209                todo!();
210            }
211        }
212        if amounts.is_empty() {
213            None
214        } else {
215            Some(amounts)
216        }
217    }
218
219    fn parse_amount_from_value(value: &serde_json::Value) -> Option<f64> {
220        match value {
221            serde_json::Value::Number(num) => num.as_f64(),
222            serde_json::Value::String(s) => s.parse::<f64>().ok(),
223            _ => None,
224        }
225    }
226
227    async fn analyze_compiled_instruction(
228        &self,
229        compiled: &solana_transaction_status::UiCompiledInstruction,
230        message: &solana_transaction_status::UiMessage,
231    ) -> Option<f64> {
232        let program_id = match message {
233            solana_transaction_status::UiMessage::Parsed(parsed_msg) => {
234                if let account_keys = &parsed_msg.account_keys {
235                    if let Some(id) = account_keys.get(compiled.program_id_index as usize) {
236                        id.pubkey.clone()
237                    } else {
238                        return None;
239                    }
240                } else {
241                    return None;
242                }
243            }
244            solana_transaction_status::UiMessage::Raw(raw_msg) => {
245                if let Some(account) = raw_msg.account_keys.get(compiled.program_id_index as usize)
246                {
247                    account.clone()
248                } else {
249                    return None;
250                }
251            }
252        };
253        let is_swap_program = program_id == crate::global::ORCA_WHIRLPOOLS_PROGRAM_ID
254            || program_id == crate::global::ORCA_STABLE_SWAP_PROGRAM_ID
255            || program_id == crate::global::ORCA_SWAP_PROGRAM_ID_V1
256            || program_id == crate::global::ORCA_SWAP_PROGRAM_ID_V2;
257        if !is_swap_program {
258            return None;
259        }
260        if let data = &compiled.data {
261            if let Ok(decoded) = BASE64_STANDARD.decode(data) {
262                if decoded.len() >= 17 {
263                    let amount_in_bytes: [u8; 8] = decoded[1..9].try_into().ok()?;
264                    let amount_out_bytes: [u8; 8] = decoded[9..17].try_into().ok()?;
265                    let amount_in = u64::from_le_bytes(amount_in_bytes);
266                    let amount_out = u64::from_le_bytes(amount_out_bytes);
267
268                    if amount_in > 0 && amount_out > 0 {
269                        return Some(amount_out as f64 / amount_in as f64);
270                    }
271                }
272            }
273        }
274
275        None
276    }
277
278    /// Calculate moving average price from on-chain data
279    ///
280    /// # Arguments
281    /// pool_address - Pool address to calculate MA for
282    /// period - Number of periods for moving average
283    ///
284    /// # Example
285    /// ```rust
286    /// let ma_20 = client.calculate_moving_average_from_chain(
287    ///     "whirlpool_address_here",
288    ///     20
289    /// ).await?;
290    /// println!("20-period moving average: {}", ma_20);
291    /// ```
292    pub async fn calculate_moving_average_from_chain(
293        &self,
294        pool_address: &str,
295        period: usize,
296    ) -> OrcaResult<f64> {
297        let prices = self
298            .get_price_history_from_chain(pool_address, period)
299            .await?;
300        if prices.is_empty() {
301            return Err(OrcaError::Error("No price data available".to_string()));
302        }
303        let sum: f64 = prices.iter().map(|p| p.price).sum();
304        let average = sum / prices.len() as f64;
305        Ok(average)
306    }
307
308    pub async fn get_kline_data_production(
309        &self,
310        pool_address: &str,
311        timeframe_minutes: u32,
312        limit: usize,
313    ) -> OrcaResult<Vec<Kline>> {
314        const MAX_RETRIES: u32 = 3;
315        if timeframe_minutes == 0 || timeframe_minutes > 1440 {
316            return Err(OrcaError::Error(
317                "Invalid timeframe: must be between 1 and 1440 minutes".to_string(),
318            ));
319        }
320        if limit > 500 {
321            return Err(OrcaError::Error(
322                "Limit too large: maximum 500 candles".to_string(),
323            ));
324        }
325        let mut retries = 0;
326        loop {
327            match self
328                .try_get_kline_data(pool_address, timeframe_minutes, limit)
329                .await
330            {
331                Ok(kline_data) => {
332                    if kline_data.is_empty() {
333                        log::warn!("No kline data available for pool: {}", pool_address);
334                    }
335                    return Ok(kline_data);
336                }
337                Err(e) if retries < MAX_RETRIES => {
338                    retries += 1;
339                    let backoff_ms = 1000 * 2u64.pow(retries - 1);
340                    tokio::time::sleep(Duration::from_millis(backoff_ms)).await;
341                }
342                Err(e) => {
343                    return Err(e);
344                }
345            }
346        }
347    }
348
349    async fn try_get_kline_data(
350        &self,
351        pool_address: &str,
352        timeframe_minutes: u32,
353        limit: usize,
354    ) -> OrcaResult<Vec<Kline>> {
355        // 获取交易历史作为价格数据源
356        let transactions_needed = limit * 5;
357        let price_history = self
358            .get_price_history_from_chain(pool_address, transactions_needed)
359            .await?;
360        if price_history.is_empty() {
361            return Ok(Vec::new());
362        }
363        let mut sorted_history = price_history;
364        sorted_history.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
365        let timeframe_seconds = (timeframe_minutes * 60) as u64;
366        let mut klines = Vec::with_capacity(limit);
367        let mut current_timeframe_start =
368            sorted_history[0].timestamp / timeframe_seconds * timeframe_seconds;
369        let mut current_kline: Option<Kline> = None;
370        for price_data in sorted_history {
371            let timeframe_start = price_data.timestamp / timeframe_seconds * timeframe_seconds;
372            if timeframe_start != current_timeframe_start {
373                if let Some(kline) = current_kline.take() {
374                    klines.push(kline);
375                    if klines.len() >= limit {
376                        break;
377                    }
378                }
379                current_timeframe_start = timeframe_start;
380                current_kline = Some(Kline {
381                    timestamp: timeframe_start,
382                    open: price_data.price,
383                    high: price_data.price,
384                    low: price_data.price,
385                    close: price_data.price,
386                    volume: 1.0,
387                });
388            } else if let Some(ref mut kline) = current_kline {
389                kline.high = kline.high.max(price_data.price);
390                kline.low = kline.low.min(price_data.price);
391                kline.close = price_data.price;
392                kline.volume += 1.0;
393            }
394        }
395        if let Some(kline) = current_kline {
396            klines.push(kline);
397        }
398        Ok(klines)
399    }
400}
401
402/// K Line data
403#[derive(Debug, Clone)]
404pub struct Kline {
405    pub timestamp: u64,
406    pub open: f64,
407    pub high: f64,
408    pub low: f64,
409    pub close: f64,
410    pub volume: f64,
411}