I am attempting to replicate the RSI indicator value from TradingView using Rust and the Mexc API, but the value displayed is incorrect. Can you help me identify what I am doing wrong?
async fn get_symbol_rsi(client: Client, symbol: &str) -> AppResult<f64> {
let rsi_len = 14;
let candles: Klines = client
.get(format!(
"https://contract.mexc.com/api/v1/contract/kline/{symbol}?interval=Min15"
))
.send()
.await?
.json()
.await?;
let mut closes = candles.data.close.into_iter().rev().take(15);
let mut gain = Vec::new();
let mut loss = Vec::new();
let mut prev_close = closes.next().unwrap();
for close in closes {
let diff = close - prev_close;
if diff > 0.0 {
gain.push(diff);
loss.push(0.0);
} else {
gain.push(0.0);
loss.push(diff.abs());
}
prev_close = close;
}
let avg_up = gain.iter().sum::<f64>() / rsi_len as f64;
let avg_down = loss.iter().sum::<f64>() / rsi_len as f64;
let rs = avg_up / avg_down;
let rsi = 100.0 - (100.0 / (1.0 + rs));
Ok(rsi)
}
thanks for helping.