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
/* Copyright 2023 Architect Financial Technologies LLC. This is free
 * software released under the GNU Affero Public License version 3. */

//! types that are sent on the wire between various parts of the system

use core::fmt;
use std::{ops::Deref, str::FromStr};

use crate::{hcstr::Str, hcstrid, packed_value, symbology::Symbolic};
use anyhow::{bail, Result};
use arrayvec::ArrayString;
use netidx::{
    pack::Pack,
    protocol::value::{FromValue, Value},
    utils::pack,
};
use netidx_derive::Pack;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use schemars::{gen::SchemaGenerator, schema::Schema, JsonSchema};
use serde::{Deserialize, Serialize};

pub mod alerts;
pub mod b2c2;
pub mod binance;
pub mod binance_futures;
pub mod book;
pub mod coinbase;
pub mod creds;
pub mod dropcopy;
pub mod dvchain;
pub mod limits;
pub mod oms_query;
pub mod orderflow;
pub mod otc_cpty;
pub mod rfq;
pub mod secrets;
pub mod symbology;
pub mod tms;

/// A trading direction
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Pack,
    Serialize,
    Deserialize,
    JsonSchema,
)]
#[repr(i8)]
pub enum Dir {
    Buy = 1,
    Sell = -1,
}

packed_value!(Dir);

impl FromStr for Dir {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "Buy" => Ok(Self::Buy),
            "Sell" => Ok(Self::Sell),
            s => bail!("{} is not a valid direction", s),
        }
    }
}

impl Dir {
    /// flip the direction Buy -> Sell, Sell -> Buy
    pub fn flip(self) -> Self {
        match self {
            Self::Buy => Self::Sell,
            Self::Sell => Self::Buy,
        }
    }

    pub fn to_str_uppercase(self) -> &'static str {
        match self {
            Self::Buy => "BUY",
            Self::Sell => "SELL",
        }
    }

    pub fn from_str_uppercase(s: &str) -> Result<Self> {
        match s {
            "BUY" => Ok(Self::Buy),
            "SELL" => Ok(Self::Sell),
            _ => bail!("invalid format: {}", s),
        }
    }

    pub fn to_str_lowercase(self) -> &'static str {
        match self {
            Self::Buy => "buy",
            Self::Sell => "sell",
        }
    }

    pub fn from_str_lowercase(s: &str) -> Result<Self> {
        match s {
            "buy" => Ok(Self::Buy),
            "sell" => Ok(Self::Sell),
            _ => bail!("invalid format: {}", s),
        }
    }
}

/// A dirpair is a structure for holding things that depend on trading
/// direction.
///
/// For example one might hold one's position in a particular coin in
/// a `DirPair<Decimal>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Pack, Serialize, Deserialize, JsonSchema)]
pub struct DirPair<T: 'static> {
    pub buy: T,
    pub sell: T,
}

impl<T: Into<Value> + Pack + 'static> Into<Value> for DirPair<T> {
    fn into(self) -> Value {
        Value::Bytes(pack(&self).unwrap().freeze())
    }
}

impl<T: FromValue + Pack + 'static> FromValue for DirPair<T> {
    fn from_value(v: Value) -> Result<Self> {
        match v {
            Value::Bytes(mut b) => Ok(Pack::decode(&mut b)?),
            _ => bail!("invalid value, expected a bytes {:?}", v),
        }
    }
}

impl<T: Default + 'static> Default for DirPair<T> {
    fn default() -> Self {
        Self { buy: T::default(), sell: T::default() }
    }
}

impl<T: 'static> DirPair<T> {
    /// get a shared reference to the field specified by dir
    pub fn get(&self, dir: Dir) -> &T {
        match dir {
            Dir::Buy => &self.buy,
            Dir::Sell => &self.sell,
        }
    }

    /// get a mutable reference to field side specified by dir
    pub fn get_mut(&mut self, dir: Dir) -> &mut T {
        match dir {
            Dir::Buy => &mut self.buy,
            Dir::Sell => &mut self.sell,
        }
    }
}

impl DirPair<Decimal> {
    /// true if both sides are 0
    pub fn is_empty(&self) -> bool {
        self.buy == dec!(0) && self.sell == dec!(0)
    }

    /// net the buy and the sell side (buy - sell)
    pub fn net(&self) -> Decimal {
        self.buy - self.sell
    }
}

hcstrid!(Desk);
packed_value!(Desk);

hcstrid!(Trader);
packed_value!(Trader);

hcstrid!(Account);
packed_value!(Account);

/// A fixed sized string that will truncate any string you put in it that is too big
#[derive(
    Debug,
    Clone,
    Copy,
    Hash,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Pack,
    Serialize,
    Deserialize,
    JsonSchema,
)]
#[pack(unwrapped)]
#[serde(transparent)]
pub struct FixedStr<const C: usize>(#[schemars(with = "String")] ArrayString<C>);

#[macro_export]
macro_rules! format_fixed {
    ($sz:expr, $f:expr, $($arg:expr),*) => {{
	use std::fmt::Write;
	let mut s = FixedStr::<$sz>::new();
	write!(s, $f, $($arg),*).unwrap();
	s
    }};
}

impl<const C: usize> fmt::Write for FixedStr<C> {
    fn write_str(&mut self, mut s: &str) -> fmt::Result {
        let mut i = 1;
        loop {
            if s.len() <= C - self.len() {
                break self.0.write_str(s);
            } else if s.is_char_boundary(C - self.len() - i) {
                s = s.split_at(C - self.len() - i).0
            } else if i > 0 {
                i -= 1;
            } else {
                break Ok(());
            }
        }
    }

    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
        self.0.write_fmt(args)
    }
}

impl<const C: usize> AsRef<str> for FixedStr<C> {
    fn as_ref(&self) -> &str {
        &**self
    }
}

impl<const C: usize> Deref for FixedStr<C> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl<'a, const C: usize> TryFrom<&'a str> for FixedStr<C> {
    type Error = arrayvec::CapacityError<&'a str>;

    fn try_from(s: &'a str) -> std::result::Result<Self, Self::Error> {
        Ok(Self(ArrayString::from(s)?))
    }
}

impl<const C: usize> FromStr for FixedStr<C> {
    type Err = arrayvec::CapacityError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match ArrayString::from(s) {
            Ok(s) => Ok(Self(s)),
            Err(_) => Err(arrayvec::CapacityError::new(())),
        }
    }
}

impl<const C: usize> FixedStr<C> {
    pub fn new() -> Self {
        Self(ArrayString::new())
    }

    /// return a new FixedStr from s, if is is too long truncate it at the end
    pub fn from_lossy_end(mut s: &str) -> Self {
        let mut i = 1;
        loop {
            if s.len() <= C {
                break Self(ArrayString::from(s).unwrap());
            } else if s.is_char_boundary(C - i) {
                s = s.split_at(C - i).0
            } else if i > 0 {
                i -= 1;
            } else {
                break Self(ArrayString::new());
            }
        }
    }

    /// return a new FixedStr from s, if s is too long truncate it at the beginning
    pub fn from_lossy_start(mut s: &str) -> Self {
        let mut i = 0;
        loop {
            if s.len() <= C {
                break Self(ArrayString::from(s).unwrap());
            } else if s.is_char_boundary(s.len() - C - i) {
                s = s.split_at(s.len() - C - i).1;
            } else if i > 0 {
                i -= 1;
            } else {
                break Self(ArrayString::new());
            }
        }
    }
}