sdb_core/storage/
filetype.rs

1use crate::dtf::file_format::read_magic_value;
2use std::io::BufReader;
3use std::fs::File;
4use csv::{DeserializeRecordsIntoIter, ReaderBuilder};
5use std::path::Path;
6use crate::dtf::{
7    update::Update,
8    file_format::{append, encode},
9};
10
11/// File types for storing financial data, currently there's only RawDtf
12#[derive(Serialize)]
13pub enum FileType {
14    /// Dense Tick Format bytes
15    RawDtf,
16}
17
18impl Default for FileType {
19    fn default() -> Self {
20        FileType::RawDtf
21    }
22}
23
24impl FileType {
25    /// Get file type from file
26    pub fn from_fname(fname: &str) -> FileType {
27
28        let file = File::open(fname).expect("OPENING FILE");
29        let mut rdr = BufReader::new(file);
30
31        if read_magic_value(&mut rdr).unwrap() {
32            return FileType::RawDtf;
33        }
34
35        unreachable!()
36    }
37}
38
39/// ```csv
40/// id,exchange,symbol,date,price,amount,sell
41/// 109797481,be,dashbtc,1498694478000,0.07154,0.40495999,false
42/// ```
43#[derive(Deserialize)]
44struct KaikoCsvEntry {
45    pub id: String,
46    pub exchange: String,
47    pub symbol: String,
48    pub date: u64,
49    pub price: f32,
50    pub amount: f32,
51    pub sell: Option<bool>,
52}
53
54impl Into<Update> for KaikoCsvEntry {
55    fn into(self) -> Update {
56        Update {
57            ts: self.date,
58            seq: self.id.parse().unwrap_or(0),
59            is_trade: true,
60            is_bid: !self.sell.unwrap_or(false),
61            price: self.price,
62            size: self.amount,
63        }
64    }
65}
66
67pub(crate) fn parse_kaiko_csv_to_dtf_inner(symbol: &str, filename: &str, csv_str: &str) -> Option<String> {
68    let csv_reader = ReaderBuilder::new()
69        .has_headers(true)
70        .from_reader(csv_str.as_bytes());
71
72    // Parse the full CSV into a vector of `KaikoCsvEntry`s and make into `Update`s
73    let iter: DeserializeRecordsIntoIter<_, KaikoCsvEntry> = csv_reader.into_deserialize();
74    let size_hint = iter.size_hint().0;
75    let mut updates: Vec<Update> = Vec::with_capacity(size_hint);
76
77    for kaiko_entry_res in iter {
78        match kaiko_entry_res {
79            Ok(kaiko_entry) => updates.push(kaiko_entry.into()),
80            Err(err) => { return Some(format!("{:?}", err)); }
81        }
82    }
83
84    // Write or append the updates into the target DTF file
85    let fpath = Path::new(&filename);
86    let res = if fpath.exists() {
87        append(filename, &updates)
88    } else {
89        encode(filename, symbol, &updates)
90    };
91
92    match res {
93        Ok(_) => None,
94        Err(err) => Some(format!("Error writing DTF to output file: {:?}", err)),
95    }
96}