price_stream.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use futures_util::stream::StreamExt;
  2. use hermes_client::apis::configuration::Configuration;
  3. use hermes_client::streaming::create_price_update_stream;
  4. use std::error::Error;
  5. const BTC_PRICE_FEED_ID: &str = "e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";
  6. const ETH_PRICE_FEED_ID: &str = "ff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace";
  7. #[tokio::main]
  8. async fn main() -> Result<(), Box<dyn Error>> {
  9. let mut config = Configuration::new();
  10. config.base_path = "https://hermes.pyth.network".to_string();
  11. let price_feed_ids = vec![
  12. BTC_PRICE_FEED_ID.to_string(),
  13. ETH_PRICE_FEED_ID.to_string()
  14. ];
  15. println!("Starting SSE price stream for BTC/USD and ETH/USD...");
  16. println!("Press Ctrl+C to exit");
  17. println!("====================");
  18. let mut stream = create_price_update_stream(
  19. &config,
  20. price_feed_ids,
  21. None, // default encoding (base64)
  22. None, // default allow_unordered
  23. None, // default benchmarks_only
  24. None // default ignore_invalid_price_ids
  25. ).await?;
  26. while let Some(result) = stream.next().await {
  27. match result {
  28. Ok(update) => {
  29. let price_feed_id = &update.id;
  30. let symbol = match price_feed_id.as_str() {
  31. BTC_PRICE_FEED_ID => "BTC/USD",
  32. ETH_PRICE_FEED_ID => "ETH/USD",
  33. _ => "Unknown",
  34. };
  35. let price = &update.price;
  36. let price_value = price.price.parse::<f64>().unwrap_or(0.0) * 10f64.powi(price.expo);
  37. let conf_value = price.conf.parse::<f64>().unwrap_or(0.0) * 10f64.powi(price.expo);
  38. println!(
  39. "{}: ${:.2} (conf: ${:.2}, publish_time: {})",
  40. symbol,
  41. price_value,
  42. conf_value,
  43. price.publish_time
  44. );
  45. },
  46. Err(e) => {
  47. eprintln!("Error: {}", e);
  48. }
  49. }
  50. }
  51. Ok(())
  52. }