use crate::tcp::{Tdx, helper::DateTime};
#[derive(Debug, Clone)]
pub struct Kline<'d> {
pub send: Box<[u8]>,
pub market: u16,
pub code: &'d str,
pub category: u16,
pub start: u16,
pub count: u16,
pub response: Vec<u8>,
pub data: Vec<KlineData<'d>>,
}
#[rustfmt::skip]
impl<'d> Default for Kline<'d> {
fn default() -> Self {
Self { market: 0, code: "000001", category: 9, start: 0, count: 3,
send: { let mut v = [0; Self::LEN]; v.copy_from_slice(Self::SEND); v.into() },
response: Vec::new(),
data: vec![KlineData::default(); 3], }
}
}
impl<'d> Kline<'d> {
#[rustfmt::skip]
pub fn new(market: u16, code: &'d str, category: u16, start: u16, count: u16) -> Self {
Self { market, code, category, start, count,
send: {
let mut arr = [0; Self::LEN];
arr.copy_from_slice(Self::SEND);
arr[12..14].copy_from_slice(&market.to_le_bytes());
arr[14..20].copy_from_slice(code.as_bytes());
arr[20..22].copy_from_slice(&category.to_le_bytes());
arr[24..26].copy_from_slice(&start.to_le_bytes());
arr[26..28].copy_from_slice(&count.to_le_bytes());
arr.into()
},
response: Vec::new(),
data: vec![KlineData::default(); count as usize] }
}
pub fn market(&mut self, market: u16) -> &mut Self {
self.market = market;
self.send[12..14].copy_from_slice(&market.to_le_bytes());
self
}
pub fn code(&mut self, code: &'d str) -> &mut Self {
self.code = code;
self.send[14..20].copy_from_slice(code.as_bytes());
self
}
pub fn category(&mut self, category: u16) -> &mut Self {
self.category = category;
self.send[20..22].copy_from_slice(&category.to_le_bytes());
self
}
pub fn start(&mut self, start: u16) -> &mut Self {
self.start = start;
self.send[24..26].copy_from_slice(&start.to_le_bytes());
self
}
pub fn count(&mut self, count: u16) -> &mut Self {
self.data.resize_with(count as usize, Default::default);
self.count = count;
self.send[26..28].copy_from_slice(&count.to_le_bytes());
self
}
}
impl<'a> Tdx for Kline<'a> {
type Item = [KlineData<'a>];
const SEND: &'static [u8] = &[
0x0c, 0x01, 0x08, 0x64, 0x01, 0x01, 0x1c, 0x00, 0x1c, 0x00, 0x2d, 0x05, 0x00, 0x00, 0x30,
0x30, 0x30, 0x30, 0x30, 0x31, 0x09, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
const TAG: &'static str = "日线";
fn send(&mut self) -> &[u8] {
&self.send
}
fn parse(&mut self, v: Vec<u8>) {
let _ = self.try_parse(v);
}
#[rustfmt::skip]
fn try_parse(&mut self, v: Vec<u8>) -> std::io::Result<()> {
use crate::tcp::helper::vol_amount;
self.data.clear();
self.response = v;
let v = &self.response;
let declared = declared_count(v, Self::TAG)?;
let expected = declared.min(self.count as usize);
let (mut pos, mut base) = (2usize, 0i64);
let mut data = Vec::with_capacity(expected);
while data.len() < expected {
let Some(bar) = bar_head(v, &mut pos, self.category) else {
break;
};
let [open, close, high, low] = bar.prices;
base += open;
data.push(KlineData { dt: bar.dt, code: self.code,
open: base as f64 / 1000.,
close: real_price(close, base),
high: real_price(high, base),
low: real_price(low, base),
vol: vol_amount(bar.vol as i32),
amount: vol_amount(bar.amount as i32) });
base += close;
}
if data.len() < expected {
return Err(incomplete(Self::TAG, declared, self.count, data.len()));
}
data.sort_by_key(|b| b.dt);
self.data = data;
Ok(())
}
fn result(&self) -> &Self::Item {
&self.data
}
}
#[derive(Debug, Default, Clone, serde::Serialize)]
pub struct KlineData<'d> {
pub dt: DateTime,
pub code: &'d str,
pub open: f64,
pub close: f64,
pub high: f64,
pub low: f64,
pub vol: f64,
pub amount: f64,
}
#[inline]
fn real_price(p: i64, base: i64) -> f64 {
(p + base) as f64 / 1000.
}
pub(super) struct BarHead {
pub dt: DateTime,
pub prices: [i64; 4],
pub vol: u32,
pub amount: u32,
}
pub(super) fn declared_count(v: &[u8], tag: &str) -> std::io::Result<usize> {
match v {
[lo, hi, ..] => Ok(u16::from_le_bytes([*lo, *hi]) as usize),
_ => Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("{tag}响应体过短:{} 字节,缺少记录数", v.len()),
)),
}
}
pub(super) fn incomplete(
tag: &str,
declared: usize,
requested: u16,
parsed: usize,
) -> std::io::Error {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("{tag}响应不完整:声明 {declared} 根,请求 {requested} 根,实际解析 {parsed} 根"),
)
}
pub(super) fn read_u32(v: &[u8], pos: &mut usize) -> Option<u32> {
let bytes = v.get(*pos..pos.checked_add(4)?)?;
*pos += 4;
Some(u32::from_le_bytes(bytes.try_into().ok()?))
}
pub(super) fn bar_head(v: &[u8], pos: &mut usize, category: u16) -> Option<BarHead> {
use crate::tcp::helper::{datetime, price_checked};
let dt = datetime(v.get(*pos..pos.checked_add(4)?)?, category);
*pos += 4;
let mut prices = [0i64; 4];
for p in &mut prices {
*p = i64::from(price_checked(v, pos)?);
}
let vol = read_u32(v, pos)?;
let amount = read_u32(v, pos)?;
Some(BarHead {
dt,
prices,
vol,
amount,
})
}
#[test]
fn day_new_modify() {
let day = Kline::new(0, "000001", 9, 0, 3);
let mut day2 = Kline::new(1, "000000", 0, 1, 1);
day2.market(0).code("000001").category(9).start(0).count(3);
compare!(Kline::default(), day, day2);
}
#[test]
fn connection() -> std::io::Result<()> {
crate::tcp::tests::connection(Kline::default())
}
#[test]
fn parse() {
let mut day = Kline::default();
let arr = vec![
0x03, 0x00, 0xeb, 0x64, 0x34, 0x01, 0xb4, 0x9a, 0x02, 0xe4, 0x06, 0x9c, 0x03, 0xc2, 0x07,
0xe8, 0x6f, 0xa8, 0x49, 0x59, 0xf7, 0x12, 0x4f, 0xec, 0x64, 0x34, 0x01, 0xd0, 0x01, 0xfa,
0x03, 0x90, 0x01, 0xc4, 0x04, 0x00, 0x81, 0x9a, 0x49, 0xb7, 0xb1, 0x03, 0x4f, 0xef, 0x64,
0x34, 0x01, 0xcc, 0x02, 0xa8, 0x05, 0x96, 0x07, 0xd6, 0x02, 0xd8, 0x3d, 0x8b, 0x49, 0x4b,
0xf0, 0xeb, 0x4e,
];
let res = [
KlineData {
dt: DateTime {
year: 2021,
month: 9,
day: 23,
hour: 15,
minute: 0,
},
code: "000001",
open: 18.1,
close: 17.68,
high: 18.32,
low: 17.65,
vol: 1379837.0,
amount: 2465683712.0,
},
KlineData {
dt: DateTime {
year: 2021,
month: 9,
day: 24,
hour: 15,
minute: 0,
},
code: "000001",
open: 17.6,
close: 17.35,
high: 17.68,
low: 17.34,
vol: 1265696.0,
amount: 2209462016.0,
},
KlineData {
dt: DateTime {
year: 2021,
month: 9,
day: 27,
hour: 15,
minute: 0,
},
code: "000001",
open: 17.21,
close: 17.57,
high: 17.68,
low: 17.06,
vol: 1140667.0,
amount: 1979196800.0,
},
];
day.parse(arr);
compare!(res, day.data.as_slice());
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::ErrorKind;
const BAR: [u8; 21] = [
0xeb, 0x64, 0x34, 0x01, 0xb4, 0x9a, 0x02, 0xe4, 0x06, 0x9c, 0x03, 0xc2, 0x07, 0xe8, 0x6f,
0xa8, 0x49, 0x59, 0xf7, 0x12, 0x4f,
];
fn body(count: u16, bars: &[&[u8]]) -> Vec<u8> {
let mut v = count.to_le_bytes().to_vec();
bars.iter().for_each(|b| v.extend_from_slice(b));
v
}
#[test]
fn declared_without_body_is_invalid() {
let mut day = Kline::new(0, "000001", 9, 0, 5);
let err = day.try_parse(vec![0x20, 0x03]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidData);
let msg = err.to_string();
assert!(msg.contains("800") && msg.contains("实际解析 0"), "{msg}");
assert!(day.data.is_empty());
assert_eq!(day.response, [0x20, 0x03]);
day.parse(vec![0x20, 0x03]);
assert!(day.data.is_empty());
assert_eq!(day.response, [0x20, 0x03]);
}
#[test]
fn declared_zero_is_ok_and_empty() {
let mut day = Kline::new(0, "000001", 9, 0, 5);
day.try_parse(vec![0x00, 0x00]).unwrap();
assert!(day.data.is_empty());
assert_eq!(day.response, [0x00, 0x00]);
}
#[test]
fn too_short_body_is_invalid() {
for v in [vec![], vec![0x01]] {
let mut day = Kline::new(0, "000001", 9, 0, 5);
assert_eq!(
day.try_parse(v.clone()).unwrap_err().kind(),
ErrorKind::InvalidData
);
assert!(day.data.is_empty());
assert_eq!(day.response, v);
}
}
#[test]
fn truncated_record_is_invalid() {
let full = body(2, &[&BAR, &BAR]);
for len in 2..full.len() {
let mut day = Kline::new(0, "000001", 9, 0, 2);
let err = day.try_parse(full[..len].to_vec()).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidData, "len={len}");
assert!(day.data.is_empty(), "len={len}");
assert_eq!(day.response.len(), len);
day.parse(full[..len].to_vec());
assert!(day.data.is_empty(), "len={len}");
}
}
#[test]
fn overlong_varint_does_not_panic() {
for filler in [0x80u8, 0xff] {
let mut v = body(1, &[&BAR[..4]]);
v.extend_from_slice(&[filler; 64]);
let mut day = Kline::new(0, "000001", 9, 0, 1);
assert_eq!(
day.try_parse(v.clone()).unwrap_err().kind(),
ErrorKind::InvalidData
);
day.parse(v);
assert!(day.data.is_empty());
}
}
#[test]
fn single_valid_record() {
let mut day = Kline::new(0, "000001", 9, 0, 1);
day.try_parse(body(1, &[&BAR])).unwrap();
assert_eq!(day.data.len(), 1);
let bar = &day.data[0];
assert_eq!(
bar.dt,
DateTime {
year: 2021,
month: 9,
day: 23,
hour: 15,
minute: 0
}
);
assert_eq!(bar.code, "000001");
assert_eq!(
(bar.open, bar.close, bar.high, bar.low),
(18.1, 17.68, 18.32, 17.65)
);
assert_eq!((bar.vol, bar.amount), (1379837.0, 2465683712.0));
}
#[test]
fn fewer_or_more_than_requested() {
let mut day = Kline::new(0, "000001", 9, 0, 5);
day.try_parse(body(1, &[&BAR])).unwrap();
assert_eq!(day.data.len(), 1);
day.try_parse(body(2, &[&BAR, &BAR])).unwrap();
assert_eq!(day.data.len(), 2);
let mut day = Kline::new(0, "000001", 9, 0, 1);
day.try_parse(body(2, &[&BAR, &BAR])).unwrap();
assert_eq!(day.data.len(), 1);
}
}