#[cfg(feature = "csv")]
use std::error::Error;
#[cfg(feature = "csv")]
use std::fmt;
#[cfg(feature = "csv")]
use std::path::Path;
#[cfg(feature = "csv")]
use crate::types::Bar;
#[cfg(feature = "csv")]
#[derive(Debug)]
pub enum CsvError {
Io(std::io::Error),
Csv(csv::Error),
Empty,
MissingColumn(&'static str),
ParseField {
line: usize,
column: &'static str,
value: String,
},
}
#[cfg(feature = "csv")]
impl fmt::Display for CsvError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write!(f, "io error: {e}"),
Self::Csv(e) => write!(f, "csv error: {e}"),
Self::Empty => write!(f, "csv is empty (no header row)"),
Self::MissingColumn(c) => write!(f, "missing required column: {c}"),
Self::ParseField {
line,
column,
value,
} => write!(
f,
"line {line}: cannot parse {column} value {value:?} as a number"
),
}
}
}
#[cfg(feature = "csv")]
impl Error for CsvError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io(e) => Some(e),
Self::Csv(e) => Some(e),
_ => None,
}
}
}
#[cfg(feature = "csv")]
impl From<std::io::Error> for CsvError {
fn from(value: std::io::Error) -> Self {
Self::Io(value)
}
}
#[cfg(feature = "csv")]
impl From<csv::Error> for CsvError {
fn from(value: csv::Error) -> Self {
Self::Csv(value)
}
}
#[must_use]
pub fn decimal_count(value: &str) -> usize {
match value.split_once('.') {
None => 0,
Some((_, frac)) => frac.trim_end_matches('0').len(),
}
}
#[must_use]
pub fn detect_price_scale(rows: &[[String; 4]]) -> f64 {
let mut max_decimals = 0;
for row in rows {
for cell in row {
max_decimals = max_decimals.max(decimal_count(cell));
}
}
if max_decimals == 0 {
0.0
} else {
10f64.powi(max_decimals.min(18) as i32)
}
}
#[cfg(feature = "csv")]
pub(crate) fn column_index(
header: &csv::StringRecord,
name: &'static str,
) -> Result<usize, CsvError> {
header
.iter()
.position(|c| c.trim().eq_ignore_ascii_case(name))
.ok_or(CsvError::MissingColumn(name))
}
#[cfg(feature = "csv")]
pub fn read_tradingview_csv(path: &Path) -> Result<(Vec<Bar>, f64), CsvError> {
let mut reader = csv::ReaderBuilder::new().flexible(true).from_path(path)?;
let header = reader.headers()?.clone();
if header.is_empty() {
return Err(CsvError::Empty);
}
let time_i = column_index(&header, "time")?;
let open_i = column_index(&header, "open")?;
let high_i = column_index(&header, "high")?;
let low_i = column_index(&header, "low")?;
let close_i = column_index(&header, "close")?;
let mut raw: Vec<(usize, String, [String; 4])> = Vec::new();
for record in reader.records() {
let record = record?;
if record.iter().all(|cell| cell.trim().is_empty()) {
continue;
}
let line_no = record
.position()
.map_or(0, |position| position.line() as usize);
let cell = |i: usize| record.get(i).map_or("", str::trim).to_string();
raw.push((
line_no,
cell(time_i),
[cell(open_i), cell(high_i), cell(low_i), cell(close_i)],
));
}
let scales: Vec<[String; 4]> = raw.iter().map(|(_, _, ohlc)| ohlc.clone()).collect();
let price_scale = detect_price_scale(&scales);
let mut bars = Vec::with_capacity(raw.len());
for (line_no, time, ohlc) in raw {
let parse = |value: &str, column: &'static str| {
value.parse::<f64>().map_err(|_| CsvError::ParseField {
line: line_no,
column,
value: value.to_string(),
})
};
bars.push(Bar {
open: parse(&ohlc[0], "open")?,
high: parse(&ohlc[1], "high")?,
low: parse(&ohlc[2], "low")?,
close: parse(&ohlc[3], "close")?,
time,
});
}
Ok((bars, price_scale))
}