qust 0.1.5

A crate for finance quantative reserach
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use crate::{idct::prelude::*, std_prelude::*, trade::prelude::*};
use qust_ds::prelude::*;
use qust_derive::*;

/* #region Price */
#[derive(Clone, Serialize, Deserialize, Default)]
pub struct PriceTick {
    #[serde(
        serialize_with = "serialize_vec_dt",
        deserialize_with = "deserialize_vec_dt"
    )]
    pub t: vdt,
    pub c: v32,
    pub v: v32,
    pub ct: Vec<i32>,
    pub bid1: v32,
    pub ask1: v32,
    pub bid1_v: v32,
    pub ask1_v: v32,
}

impl PriceTick {
    pub fn with_capacity(i: usize) -> Self {
        Self {
            t: Vec::with_capacity(i),
            c: Vec::with_capacity(i),
            v: Vec::with_capacity(i),
            ct: Vec::with_capacity(i),
            bid1: Vec::with_capacity(i),
            ask1: Vec::with_capacity(i),
            bid1_v: Vec::with_capacity(i),
            ask1_v: Vec::with_capacity(i),
        }
    }

    pub fn shrink_to_fit(&mut self) {
        self.t.shrink_to_fit();
        self.c.shrink_to_fit();
        self.v.shrink_to_fit();
        self.ct.shrink_to_fit();
        self.bid1.shrink_to_fit();
        self.ask1.shrink_to_fit();
        self.bid1_v.shrink_to_fit();
        self.ask1_v.shrink_to_fit();
    }

    pub fn cat(&mut self, price: &mut PriceTick) {
        self.t.append(&mut price.t);
        self.c.append(&mut price.c);
        self.v.append(&mut price.v);
        self.ct.append(&mut price.ct);
        self.bid1.append(&mut price.bid1);
        self.ask1.append(&mut price.ask1);
        self.bid1_v.append(&mut price.bid1_v);
        self.ask1_v.append(&mut price.ask1_v);
    }

    pub fn to_price_ori(&self, r: TriBox, ticker: Ticker) -> PriceOri {
        if self.t.is_empty() {
            return PriceOri::with_capacity(0);
        }
        let mut price_ori = r.gen_price_ori(self);
        let mut f = r.update_tick_func(ticker);
        for (&t, &c, &v, &bid1, &ask1, &bid1_v, &ask1_v, &ct) in izip!(
            self.t.iter(),
            self.c.iter(),
            self.v.iter(),
            self.bid1.iter(),
            self.ask1.iter(),
            self.bid1_v.iter(),
            self.ask1_v.iter(),
            self.ct.iter(),
        ) {
            let tick_data = TickData {
                t,
                c,
                v,
                bid1,
                ask1,
                bid1_v,
                ask1_v,
                ct,
            };
            f(&tick_data, &mut price_ori);
        }
        price_ori.shrink_to_fit();
        price_ori
    }

    pub fn to_di(&self, r: TriBox, ticker: Ticker) -> Di {
        self.to_price_ori(r.clone(), ticker)
            .to_pcon(r, ticker)
            .to_di()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct KlineInfo {
    #[serde(serialize_with = "serialize_dt", deserialize_with = "deserialize_dt")]
    pub open_time: dt,
    pub pass_last: u16,
    pub pass_this: u16,
    pub contract: i32,
}

#[derive(Clone, Serialize, Deserialize, Default)]
pub struct PriceOri {
    #[serde(
        serialize_with = "serialize_vec_dt",
        deserialize_with = "deserialize_vec_dt"
    )]
    pub t: vdt,
    pub o: v32,
    pub h: v32,
    pub l: v32,
    pub c: v32,
    pub v: v32,
    pub ki: Vec<KlineInfo>,
    pub immut_info: Vec<vv32>,
}

impl PriceOri {
    pub fn with_capacity(i: usize) -> Self {
        PriceOri {
            t: Vec::with_capacity(i),
            o: Vec::with_capacity(i),
            h: Vec::with_capacity(i),
            l: Vec::with_capacity(i),
            c: Vec::with_capacity(i),
            v: Vec::with_capacity(i),
            ki: Vec::with_capacity(i),
            immut_info: Default::default(),
        }
    }

    pub fn shrink_to_fit(&mut self) {
        self.t.shrink_to_fit();
        self.o.shrink_to_fit();
        self.h.shrink_to_fit();
        self.l.shrink_to_fit();
        self.c.shrink_to_fit();
        self.v.shrink_to_fit();
        self.ki.shrink_to_fit();
    }

    pub fn cat(&mut self, price: &mut PriceOri) {
        self.t.append(&mut price.t);
        self.o.append(&mut price.o);
        self.h.append(&mut price.h);
        self.l.append(&mut price.l);
        self.c.append(&mut price.c);
        self.v.append(&mut price.v);
        self.ki.append(&mut price.ki);
    }

    pub fn to_pcon(self, inter: TriBox, ticker: Ticker) -> Pcon {
        Pcon {
            price: self,
            inter,
            ticker,
        }
    }
    pub fn to_di(self, ticker: Ticker, inter: TriBox) -> Di {
        self.to_pcon(inter, ticker).to_di()
    }
}

#[derive(Clone)]
pub struct PriceArc {
    pub t: avdt,
    pub o: av32,
    pub h: av32,
    pub l: av32,
    pub c: av32,
    pub v: av32,
    pub ki: Arc<Vec<KlineInfo>>,
    pub immut_info: Vec<Arc<vv32>>,
    pub finished: Option<Vec<KlineState>>,
}

impl PriceArc {
    pub fn to_price_ori(self) -> PriceOri {
        PriceOri {
            t: self.t.to_vec(),
            o: self.o.to_vec(),
            h: self.h.to_vec(),
            l: self.l.to_vec(),
            c: self.c.to_vec(),
            v: self.v.to_vec(),
            ki: self.ki.to_vec(),
            immut_info: self
                .immut_info
                .into_iter()
                .map(|x| x.to_vec())
                .collect_vec(),
        }
    }
}

/* #endregion */

/* #region Pcon */
#[derive(Clone, Serialize, Deserialize)]
pub struct PconType<T, N> {
    pub ticker: Ticker,
    pub inter: T,
    pub price: N,
}
pub type Pcon = PconType<TriBox, PriceOri>;

#[ta_derive]
pub struct PconIdent {
    pub inter: TriBox,
    pub ticker: Ticker,
}

impl PconIdent {
    pub fn new(inter: TriBox, ticker: Ticker) -> Self {
        Self { inter, ticker }
    }
}

impl std::fmt::Display for PconIdent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} - {:?}", self.ticker, self.inter)
    }
}
impl PartialEq for PconIdent {
    fn eq(&self, other: &Self) -> bool {
        self.ticker == other.ticker && format!("{:?}", self.inter) == format!("{:?}", other.inter)
    }
}
impl Eq for PconIdent {}
impl std::hash::Hash for PconIdent {
    fn hash<H>(&self, state: &mut H)
    where
        H: std::hash::Hasher,
    {
        format!("{:?}", self).hash(state)
    }
}

impl PartialEq for Pcon {
    fn eq(&self, other: &Self) -> bool {
        self.ident() == other.ident()
    }
}

impl Pcon {
    pub fn from_price(price: PriceOri, inter: TriBox, ticker: Ticker) -> Self {
        Pcon {
            ticker,
            inter,
            price,
        }
    }

    pub fn ident(&self) -> PconIdent {
        PconIdent::new(self.inter.clone(), self.ticker)
    }

    pub fn to_di(self) -> Di {
        Di {
            pcon: self,
            data_save: DataSave::default(),
            dcon: RwLock::new(vec![Tf(0, 1)]),
            part: RwLock::new(vec![Part::ono]),
        }
    }
}

/* #endregion */

/* #region Di */
#[derive(Serialize, Deserialize, AsRef)]
pub struct DiType<T> {
    pub pcon: T,
    #[serde(skip)]
    pub data_save: DataSave,
    pub dcon: RwLock<Vec<Convert>>,
    pub part: RwLock<Vec<Part>>,
}
pub type Di = DiType<Pcon>;

impl Clone for Di {
    fn clone(&self) -> Self {
        self.pcon.clone().to_di()
    }
}

impl Di {
    pub fn size(&self) -> usize {
        self.pcon.price.t.len()
    }
    pub fn last_dcon(&self) -> Convert {
        let dcon_vec = self.dcon.read().unwrap();
        dcon_vec[dcon_vec.len() - 1].clone()
    }

    pub fn last_part(&self) -> Part {
        let part_vec = self.part.read().unwrap();
        part_vec[part_vec.len() - 1].clone()
    }

    pub fn get_kline(&self, p: &KlineType) -> av32 {
        match p {
            KlineType::Open => self.o(),
            KlineType::High => self.h(),
            KlineType::Low => self.l(),
            _ => self.c(),
        }
    }

    pub fn repeat(&self, n: usize) -> Dil {
        Dil {
            dil: vec![self.clone(); n],
        }
    }

    pub fn t(&self) -> avdt {
        self.calc(self.last_dcon()).t
    }
    pub fn o(&self) -> av32 {
        self.calc(self.last_dcon()).o
    }
    pub fn h(&self) -> av32 {
        self.calc(self.last_dcon()).h
    }
    pub fn l(&self) -> av32 {
        self.calc(self.last_dcon()).l
    }
    pub fn c(&self) -> av32 {
        self.calc(self.last_dcon()).c
    }
    pub fn v(&self) -> av32 {
        self.calc(self.last_dcon()).v
    }
    pub fn immut_info(&self) -> Vec<Arc<vv32>> {
        self.calc(self.last_dcon()).immut_info
    }

    pub fn len(&self) -> usize {
        self.pcon.price.t.len()
    }
    pub fn is_empty(&self) -> bool {
        self.pcon.price.t.is_empty()
    }

    pub fn clear(&self) {
        self.data_save.clear();
    }

    pub fn clear2(&self) {
        self.data_save.save_pms2d.write().unwrap().clear();
        self.data_save.save_dcon.write().unwrap().clear();
        self.data_save.save_others.write().unwrap().clear();
    }

    pub fn calc<T: AsRef<N>, N: Calc<R> + ?Sized, R>(&self, x: T) -> R {
        x.as_ref().calc(self)
    }

    pub fn tz_profit(&self) -> f32 {
        let tz = self.pcon.ticker.info().tz;
        10000. * tz / self.pcon.price.c.last().unwrap()
    }
}

impl Debug for Di {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:<15} ---  {:<24} .. {:<24}  ---  {:<10} --- {}",
            self.pcon.ident().to_string(),
            self.pcon.price.ki.first().unwrap().open_time.to_string(),
            self.pcon.price.t.last().unwrap().to_string(),
            self.pcon.price.t.len().to_string(),
            (self.pcon.price.ki.map(|x| x.pass_this as f32).mean() / 120.) as usize,
        )
    }
}

/* #endregion */

/* #region Dil */
#[derive(Serialize, Deserialize, Clone)]
pub struct Dil {
    pub dil: Vec<Di>,
}
impl Dil {
    pub fn clear(&self) {
        self.dil.iter().for_each(|x| x.clear());
    }
    pub fn clear1(&self) {
        self.dil
            .iter()
            .for_each(|x| x.data_save.save_pms2d.write().unwrap().clear());
    }
    pub fn clear2(&mut self) {
        self.dil
            .iter()
            .for_each(|x| x.data_save.save_dcon.write().unwrap().clear());
    }

    pub fn total_kline_nums(&self) -> usize {
        self.dil.iter().map(|x| x.size()).sum::<usize>()
    }
}

impl Debug for Dil {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Dil size {}\n{}",
            self.size(),
            self.dil
                .iter()
                .map(|x| x.debug_string() + "\n")
                .collect_vec()
                .concat(),
        )
    }
}
/* #endregion */

/* #region Price -> PriceArc */
pub trait ToArc {
    type Output;
    fn to_arc(self) -> Self::Output;
}

impl<T> ToArc for Vec<T> {
    type Output = Arc<Vec<T>>;
    fn to_arc(self) -> Self::Output {
        Arc::new(self)
    }
}

impl ToArc for PriceOri {
    type Output = PriceArc;
    fn to_arc(self) -> Self::Output {
        PriceArc {
            t: self.t.to_arc(),
            o: self.o.to_arc(),
            h: self.h.to_arc(),
            l: self.l.to_arc(),
            c: self.c.to_arc(),
            v: self.v.to_arc(),
            ki: self.ki.to_arc(),
            immut_info: self.immut_info.map(|x| x.clone().to_arc()),
            finished: None,
        }
    }
}

impl ToArc for (PriceOri, Option<Vec<KlineState>>) {
    type Output = PriceArc;
    fn to_arc(self) -> Self::Output {
        let mut res = self.0.to_arc();
        res.finished = self.1;
        res
    }
}
/* #endregion */