Created
June 10, 2023 08:44
-
-
Save diffstorm/e9ce7ecc17945105ad1f6b968dff35fb to your computer and use it in GitHub Desktop.
Rust code example which prints 1D relative strength index value of Bitcoin on Binance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This program uses the binance crate in Rust to interact with the Binance API. It fetches the 1-day klines (candlestick data) for the BTCUSDT pair and calculates the RSI (Relative Strength Index) using the compute_rsi function. Finally, it prints the calculated RSI for BTCUSDT on Binance. | |
Note that you'll need to add the binance crate to your Cargo.toml file to use the Binance API in Rust: | |
[dependencies] | |
binance = "0.16.0" | |
Make sure to replace "your_api_key" and "your_secret_key" with your actual Binance API key and secret key. | |
*/ | |
use binance::api::*; | |
use binance::market::*; | |
fn compute_rsi(data: &[f64], time_window: usize) -> f64 { | |
let mut gain: f64 = 0.0; | |
let mut loss: f64 = 0.0; | |
for i in 1..data.len() { | |
let diff = data[i] - data[i - 1]; | |
if diff > 0.0 { | |
gain += diff; | |
} else { | |
loss += diff.abs(); | |
} | |
} | |
let avg_gain = gain / time_window as f64; | |
let avg_loss = loss / time_window as f64; | |
let rs = avg_gain / avg_loss; | |
let rsi = 100.0 - (100.0 / (1.0 + rs)); | |
rsi | |
} | |
fn main() { | |
let api_key = "your_api_key"; | |
let secret_key = "your_secret_key"; | |
let client = Binance::new(api_key, secret_key); | |
let symbol = "BTCUSDT"; | |
let time_window = 14; | |
match client.get_klines(symbol, "1d", 100) { | |
Ok(klines) => { | |
let closes: Vec<f64> = klines | |
.iter() | |
.map(|kline| kline.close.parse().unwrap()) | |
.collect(); | |
let rsi = compute_rsi(&closes, time_window); | |
println!("RSI for {} on Binance: {:.2}", symbol, rsi); | |
} | |
Err(e) => println!("Error fetching klines: {}", e), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment