apple_quant_algorithmic/timestamp/
point.rs1use std::{
2 ops::{Add, Sub},
3 time::{SystemTime, UNIX_EPOCH},
4};
5
6use bevy::prelude::Deref;
7use time::Duration;
8
9use crate::timestamp::TradeTimestamp;
10
11#[derive(Deref, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct TickTimestamp(Timestamp);
13
14impl TickTimestamp {
15 pub(crate) fn new(timestamp: Timestamp) -> Self {
16 Self(timestamp)
17 }
18
19 pub(crate) fn now() -> Self {
20 Self(Timestamp::now())
21 }
22
23 pub fn timestamp(&self) -> Timestamp {
24 self.0
25 }
26}
27
28#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
29pub struct ConstTimestamp(pub i128);
30
31#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub struct Timestamp(i128);
33
34impl Timestamp {
35 pub fn new(utc_ns: i128) -> Self {
36 Self(utc_ns)
37 }
38
39 pub fn now() -> Self {
40 let unix_epoch_ns = SystemTime::now()
41 .duration_since(UNIX_EPOCH)
42 .unwrap()
43 .as_nanos();
44
45 let unix_epoch_ns = i128::try_from(unix_epoch_ns).unwrap();
46 Self(unix_epoch_ns)
47 }
48
49 pub fn duration_since(
50 &self,
51 timestamp: &Timestamp,
52 ) -> Duration {
53 let diff_utc_ns = self.0 - timestamp.0;
54 Duration::nanoseconds_i128(diff_utc_ns)
55 }
56
57 pub fn as_utc_nanos(&self) -> i128 {
58 self.0
59 }
60
61 pub fn as_utc_micros(&self) -> i128 {
62 self.0 / 1_000
63 }
64
65 pub fn as_utc_millis(&self) -> i64 {
66 (self.0 / 1_000_000) as i64
67 }
68
69 pub fn as_utc_seconds(&self) -> i64 {
70 (self.0 / 1_000_000_000) as i64
71 }
72}
73
74impl From<TradeTimestamp> for Timestamp {
75 fn from(value: TradeTimestamp) -> Self {
76 *value
77 }
78}
79
80impl From<i128> for Timestamp {
81 fn from(value: i128) -> Self {
82 Self::new(value)
83 }
84}
85
86impl Add<Duration> for Timestamp {
87 type Output = Self;
88
89 fn add(
90 self,
91 rhs: Duration,
92 ) -> Self::Output {
93 Self(self.0 + rhs.whole_nanoseconds())
94 }
95}
96
97impl Add<&Duration> for Timestamp {
98 type Output = Self;
99
100 fn add(
101 self,
102 rhs: &Duration,
103 ) -> Self::Output {
104 Self(self.0 + rhs.whole_nanoseconds())
105 }
106}
107
108impl Sub<Duration> for Timestamp {
109 type Output = Self;
110
111 fn sub(
112 self,
113 rhs: Duration,
114 ) -> Self::Output {
115 Self(self.0 - rhs.whole_nanoseconds())
116 }
117}
118
119impl Sub<&Duration> for Timestamp {
120 type Output = Self;
121
122 fn sub(
123 self,
124 rhs: &Duration,
125 ) -> Self::Output {
126 Self(self.0 - rhs.whole_nanoseconds())
127 }
128}