use crate::tcp::{helper::price, Tdx};
use crate::bytes_helper::u16_from_le_bytes;
#[derive(Debug, Clone)]
pub struct MinuteTime<'d> {
pub send: Box<[u8]>,
pub market: u16,
pub code: &'d str,
pub response: Vec<u8>,
pub data: Vec<MinuteTimeData>,
}
impl<'d> MinuteTime<'d> {
pub fn new(market: u16, code: &'d str) -> Self {
assert_eq!(code.len(), 6, "股票代码必须是6位");
let mut send = [0u8; Self::LEN];
send[0..12].copy_from_slice(Self::SEND);
send[12..14].copy_from_slice(&market.to_le_bytes());
send[14..20].copy_from_slice(code.as_bytes());
Self {
send: send.into(),
market,
code,
response: Vec::new(),
data: Vec::new(),
}
}
}
impl<'a> Tdx for MinuteTime<'a> {
type Item = [MinuteTimeData];
const SEND: &'static [u8] = &[
0x0c, 0x1b, 0x08, 0x00, 0x01, 0x01, 0x0e, 0x00, 0x0e, 0x00, 0x1d,
0x05, ];
const TAG: &'static str = "分时数据";
const LEN: usize = 12 + 2 + 6 + 4;
fn send(&mut self) -> &[u8] {
&self.send
}
fn parse(&mut self, v: Vec<u8>) {
let mut pos = 0;
let num_points = u16_from_le_bytes(&v, pos);
pos += 4;
self.data = Vec::with_capacity(num_points as usize);
let mut last_price = 0i32;
for _ in 0..num_points {
let price_raw = price(&v, &mut pos);
let _reversed1 = price(&v, &mut pos);
let vol = price(&v, &mut pos);
last_price += price_raw;
let price = last_price as f64 / 100.0;
self.data.push(MinuteTimeData { price, vol });
}
self.response = v;
}
fn result(&self) -> &Self::Item {
&self.data
}
}
#[derive(Debug, Default, Clone, serde::Serialize)]
pub struct MinuteTimeData {
pub price: f64,
pub vol: i32,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_minute_time_new() {
let minute = MinuteTime::new(0, "000001");
assert_eq!(minute.market, 0);
assert_eq!(minute.code, "000001");
assert_eq!(minute.send.len(), 24);
}
#[test]
fn test_minute_time_new_shanghai() {
let minute = MinuteTime::new(1, "600000");
assert_eq!(minute.market, 1);
assert_eq!(minute.code, "600000");
}
#[test]
fn test_minute_time_send_bytes() {
let minute = MinuteTime::new(0, "000001");
assert_eq!(&minute.send[0..12], &[0x0c, 0x1b, 0x08, 0x00, 0x01, 0x01, 0x0e, 0x00, 0x0e, 0x00, 0x1d, 0x05]);
assert_eq!(&minute.send[12..14], &[0x00, 0x00]);
assert_eq!(&minute.send[14..20], b"000001");
assert_eq!(&minute.send[20..24], &[0x00, 0x00, 0x00, 0x00]);
}
#[test]
#[should_panic(expected = "股票代码必须是6位")]
fn test_minute_time_invalid_code() {
MinuteTime::new(0, "00001");
}
#[test]
fn test_connection() {
if std::env::var("RUSTDX_SKIP_INTEGRATION_TESTS").is_ok() {
println!("⚠️ 跳过集成测试 (RUSTDX_SKIP_INTEGRATION_TESTS 已设置)");
return;
}
println!("⚠️ 集成测试需要手动验证(需要实际TCP连接)");
}
}