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
//! Microprice — size-weighted fair value of the top of book.
use crate::microstructure::OrderBook;
use crate::traits::Indicator;
/// Microprice — the size-weighted mid of the top of book.
///
/// The microprice tilts the mid toward the side that is *more likely to be
/// hit*: it weights each touch price by the size resting on the **opposite**
/// side, so a heavy ask (sell pressure) pulls the fair value down toward the
/// bid, and vice versa:
///
/// ```text
/// microprice = (bidPrice₁·askSize₁ + askPrice₁·bidSize₁) / (bidSize₁ + askSize₁)
/// ```
///
/// When both top sizes are zero the weighting is undefined and the plain mid
/// `(bidPrice₁ + askPrice₁) / 2` is returned. An empty book yields `0`.
///
/// `Input = OrderBook`, `Output = f64`. Stateless; ready after the first
/// snapshot.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, Level, Microprice, OrderBook};
///
/// let book = OrderBook::new(
/// vec![Level::new(100.0, 1.0).unwrap()],
/// vec![Level::new(101.0, 3.0).unwrap()],
/// )
/// .unwrap();
/// let mut mp = Microprice::new();
/// // (100·3 + 101·1) / (1 + 3) = 401 / 4 = 100.25 — pulled toward the bid.
/// assert_eq!(mp.update(book), Some(100.25));
/// ```
#[derive(Debug, Clone, Default)]
pub struct Microprice {
has_emitted: bool,
}
impl Microprice {
/// Construct a new microprice indicator.
pub const fn new() -> Self {
Self { has_emitted: false }
}
}
impl Indicator for Microprice {
type Input = OrderBook;
type Output = f64;
fn update(&mut self, book: OrderBook) -> Option<f64> {
self.has_emitted = true;
let (Some(bid), Some(ask)) = (book.best_bid(), book.best_ask()) else {
return Some(0.0);
};
let total = bid.size + ask.size;
if total <= 0.0 {
return Some(f64::midpoint(bid.price, ask.price));
}
Some((bid.price * ask.size + ask.price * bid.size) / total)
}
fn reset(&mut self) {
self.has_emitted = false;
}
fn warmup_period(&self) -> usize {
1
}
fn is_ready(&self) -> bool {
self.has_emitted
}
fn name(&self) -> &'static str {
"Microprice"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::microstructure::Level;
use crate::traits::BatchExt;
fn book(bids: &[(f64, f64)], asks: &[(f64, f64)]) -> OrderBook {
let to_levels = |xs: &[(f64, f64)]| {
xs.iter()
.map(|&(p, s)| Level::new(p, s).unwrap())
.collect::<Vec<_>>()
};
OrderBook::new(to_levels(bids), to_levels(asks)).unwrap()
}
#[test]
fn accessors_and_metadata() {
let mp = Microprice::new();
assert_eq!(mp.name(), "Microprice");
assert_eq!(mp.warmup_period(), 1);
assert!(!mp.is_ready());
}
#[test]
fn weights_toward_thin_side() {
let mut mp = Microprice::new();
// Heavy ask -> microprice pulled toward bid.
assert_eq!(
mp.update(book(&[(100.0, 1.0)], &[(101.0, 3.0)])),
Some(100.25)
);
assert!(mp.is_ready());
}
#[test]
fn balanced_top_equals_mid() {
let mut mp = Microprice::new();
assert_eq!(
mp.update(book(&[(100.0, 2.0)], &[(101.0, 2.0)])),
Some(100.5)
);
}
#[test]
fn zero_size_falls_back_to_mid() {
let mut mp = Microprice::new();
assert_eq!(
mp.update(book(&[(100.0, 0.0)], &[(102.0, 0.0)])),
Some(101.0)
);
}
#[test]
fn empty_book_is_zero() {
let mut mp = Microprice::new();
assert_eq!(
mp.update(OrderBook::new_unchecked(vec![], vec![])),
Some(0.0)
);
}
#[test]
fn batch_equals_streaming() {
let books: Vec<OrderBook> = (0..20)
.map(|i| {
let ask = 1.0 + f64::from(i % 4);
book(&[(100.0, 2.0)], &[(101.0, ask)])
})
.collect();
let mut a = Microprice::new();
let mut b = Microprice::new();
assert_eq!(
a.batch(&books),
books
.iter()
.map(|x| b.update(x.clone()))
.collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut mp = Microprice::new();
mp.update(book(&[(100.0, 1.0)], &[(101.0, 1.0)]));
assert!(mp.is_ready());
mp.reset();
assert!(!mp.is_ready());
}
}