longtrader-worker 0.2.1

Local strategy host running portable strategies against pluggable backends (exchange daemon / terminal API / mock)
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
//! Statistical Arbitrage — pairs trading with z-score mean reversion.
//!
//! Identifies a pair of cointegrated assets and trades the spread
//! between them. The spread is standardised into a z-score. When the
//! z-score exceeds a threshold, the spread is opened (long the
//! underperformer, short the outperformer). When it reverts, the
//! spread is closed for a profit.
//!
//! ```text
//!   spread = price_A − hedge_ratio · price_B
//!   z = (spread − mean(spread)) / stdev(spread)
//!   if  z >  threshold → short spread (sell A / buy B)
//!   if  z < −threshold → long spread (buy A / sell B)
//!   if  |z| < exit_threshold → close
//! ```
//!
//! Reference: <https://hummingbot.org/strategies/statistical-arbitrage/>

use std::{collections::VecDeque, sync::Arc};

use async_trait::async_trait;
use color_eyre::Result;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::Deserialize;

use crate::{
    indicators::decimal_sqrt,
    ports::{MarketDataSource, TradingGateway},
    strategies::{CommonParams, Strategy, limit_order, params_from_table},
};

/// Configuration for the statistical arbitrage strategy.
#[derive(Debug, Clone, Deserialize)]
pub struct StatArbConfig {
    #[serde(flatten)]
    pub common: CommonParams,
    /// Symbol for asset A (the lead).
    pub symbol_a: String,
    /// Symbol for asset B (the lag).
    pub symbol_b: String,
    /// Hedge ratio (units of B per unit of A).
    #[serde(default = "default_hedge_ratio")]
    pub hedge_ratio: Decimal,
    /// Rolling window for the spread mean/stdev.
    #[serde(default = "default_window")]
    pub window: usize,
    /// Z-score entry threshold.
    #[serde(default = "default_entry")]
    pub entry_threshold: Decimal,
    /// Z-score exit threshold.
    #[serde(default = "default_exit")]
    pub exit_threshold: Decimal,
    /// Position size in units of A.
    #[serde(default = "default_qty")]
    pub qty: Decimal,
}

fn default_hedge_ratio() -> Decimal {
    dec!(1)
}
fn default_window() -> usize {
    50
}
fn default_entry() -> Decimal {
    dec!(2)
}
fn default_exit() -> Decimal {
    dec!(0.5)
}
fn default_qty() -> Decimal {
    dec!(1)
}

impl StatArbConfig {
    /// Parses config from the `[strategy.params]` table.
    ///
    /// # Errors
    /// Propagates deserialization errors.
    pub fn from_params(table: &toml::Table) -> Result<Self> {
        params_from_table(table)
    }
}

/// Spread tracker with rolling statistics.
#[derive(Debug, Clone)]
pub struct SpreadTracker {
    window: usize,
    buf: VecDeque<Decimal>,
}

impl SpreadTracker {
    #[must_use]
    pub fn new(window: usize) -> Self {
        Self { window, buf: VecDeque::with_capacity(window) }
    }

    pub fn push(&mut self, spread: Decimal) {
        self.buf.push_back(spread);
        if self.buf.len() > self.window {
            self.buf.pop_front();
        }
    }

    #[must_use]
    pub fn mean(&self) -> Option<Decimal> {
        if self.buf.is_empty() {
            return None;
        }
        let count = Decimal::from(self.buf.len());
        self.buf.iter().try_fold(Decimal::ZERO, |acc, &x| acc.checked_add(x))?.checked_div(count)
    }

    #[must_use]
    pub fn stdev(&self) -> Option<Decimal> {
        let n = self.buf.len();
        if n < 2 {
            return None;
        }
        let mean = self.mean()?;
        let count = Decimal::from(n);
        let sq = self.buf.iter().try_fold(Decimal::ZERO, |acc, &x| {
            let d = x.checked_sub(mean)?;
            acc.checked_add(d.checked_mul(d)?)
        })?;
        Some(decimal_sqrt(sq.checked_div(count)?))
    }

    #[must_use]
    pub fn z_score(&self, spread: Decimal) -> Option<Decimal> {
        let mean = self.mean()?;
        let stdev = self.stdev()?;
        if stdev.is_zero() {
            return None;
        }
        Some((spread - mean) / stdev)
    }
}

/// Stat arb signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatArbSignal {
    /// Long spread: buy A, sell B.
    LongSpread,
    /// Short spread: sell A, buy B.
    ShortSpread,
    /// Close position.
    Close,
    /// No signal.
    NoTrade,
}

/// Classify the spread z-score into a trading signal.
#[must_use]
pub fn classify_stat_arb(
    z: Option<Decimal>,
    entry_threshold: Decimal,
    exit_threshold: Decimal,
    has_position: bool,
) -> StatArbSignal {
    let z = match z {
        None => return StatArbSignal::NoTrade,
        Some(v) => v,
    };
    if has_position {
        if z.abs() < exit_threshold { StatArbSignal::Close } else { StatArbSignal::NoTrade }
    } else if z > entry_threshold {
        StatArbSignal::ShortSpread
    } else if z < -entry_threshold {
        StatArbSignal::LongSpread
    } else {
        StatArbSignal::NoTrade
    }
}

/// Statistical arbitrage strategy.
pub struct StatArb {
    config: StatArbConfig,
    gateway: Arc<dyn TradingGateway>,
    market: Arc<dyn MarketDataSource>,
    tracker: tokio::sync::Mutex<SpreadTracker>,
    has_position: tokio::sync::Mutex<i8>, // −1 short, 0 flat, +1 long
}

impl StatArb {
    pub fn new(
        config: StatArbConfig,
        gateway: Arc<dyn TradingGateway>,
        market: Arc<dyn MarketDataSource>,
    ) -> Self {
        let window = config.window;
        Self {
            config,
            gateway,
            market,
            tracker: tokio::sync::Mutex::new(SpreadTracker::new(window)),
            has_position: tokio::sync::Mutex::new(0),
        }
    }

    async fn fetch_price(&self, symbol: &str) -> Result<Decimal> {
        let ticker = self
            .market
            .fetch_ticker(crate::proto::market::FetchTickerRequest {
                exchange_id: buffa::MessageField::some(self.config.common.proto_exchange_id()),
                symbol: symbol.to_string(),
                ..Default::default()
            })
            .await?;
        if let Some(last) = ticker.last.as_option() {
            let p = longtrader_contract::ext::common_to_decimal(last)?;
            if p > Decimal::ZERO {
                return Ok(p);
            }
        }
        color_eyre::eyre::bail!("no price for {symbol}")
    }

    pub async fn tick(&self) -> Result<()> {
        let price_a = self.fetch_price(&self.config.symbol_a).await?;
        let price_b = self.fetch_price(&self.config.symbol_b).await?;
        let spread = price_a - self.config.hedge_ratio * price_b;
        let mut tracker = self.tracker.lock().await;
        tracker.push(spread);
        let z = tracker.z_score(spread);
        drop(tracker);

        let has_pos = *self.has_position.lock().await;
        let has_pos_bool = has_pos != 0;
        let signal = classify_stat_arb(
            z,
            self.config.entry_threshold,
            self.config.exit_threshold,
            has_pos_bool,
        );

        match signal {
            StatArbSignal::NoTrade => {}
            StatArbSignal::LongSpread => {
                let qty = self.config.qty;
                let coid = format!("staab-{}", ulid::Ulid::generate());
                if let Err(err) = self
                    .gateway
                    .create_order(limit_order(
                        &self.config.common.proto_exchange_id(),
                        &self.config.symbol_a,
                        coid,
                        true,
                        price_a,
                        qty,
                    ))
                    .await
                {
                    tracing::error!(error = %err, "stat arb buy A failed");
                }
                let coid = format!("staab-{}", ulid::Ulid::generate());
                let qty_b = qty * self.config.hedge_ratio;
                if let Err(err) = self
                    .gateway
                    .create_order(limit_order(
                        &self.config.common.proto_exchange_id(),
                        &self.config.symbol_b,
                        coid,
                        false,
                        price_b,
                        qty_b,
                    ))
                    .await
                {
                    tracing::error!(error = %err, "stat arb sell B failed");
                }
                *self.has_position.lock().await = 1;
            }
            StatArbSignal::ShortSpread => {
                let qty = self.config.qty;
                let coid = format!("staab-{}", ulid::Ulid::generate());
                if let Err(err) = self
                    .gateway
                    .create_order(limit_order(
                        &self.config.common.proto_exchange_id(),
                        &self.config.symbol_a,
                        coid,
                        false,
                        price_a,
                        qty,
                    ))
                    .await
                {
                    tracing::error!(error = %err, "stat arb sell A failed");
                }
                let coid = format!("staab-{}", ulid::Ulid::generate());
                let qty_b = qty * self.config.hedge_ratio;
                if let Err(err) = self
                    .gateway
                    .create_order(limit_order(
                        &self.config.common.proto_exchange_id(),
                        &self.config.symbol_b,
                        coid,
                        true,
                        price_b,
                        qty_b,
                    ))
                    .await
                {
                    tracing::error!(error = %err, "stat arb buy B failed");
                }
                *self.has_position.lock().await = -1;
            }
            StatArbSignal::Close => {
                let pos = *self.has_position.lock().await;
                let qty = self.config.qty;
                // Reverse the position to close.
                let coid = format!("staab-{}", ulid::Ulid::generate());
                let side_a = pos < 0; // Was short A → buy to close.
                if let Err(err) = self
                    .gateway
                    .create_order(limit_order(
                        &self.config.common.proto_exchange_id(),
                        &self.config.symbol_a,
                        coid,
                        side_a,
                        price_a,
                        qty,
                    ))
                    .await
                {
                    tracing::error!(error = %err, "stat arb close A failed");
                }
                let coid = format!("staab-{}", ulid::Ulid::generate());
                let qty_b = qty * self.config.hedge_ratio;
                let side_b = pos > 0; // Was long B → sell to close.
                if let Err(err) = self
                    .gateway
                    .create_order(limit_order(
                        &self.config.common.proto_exchange_id(),
                        &self.config.symbol_b,
                        coid,
                        side_b,
                        price_b,
                        qty_b,
                    ))
                    .await
                {
                    tracing::error!(error = %err, "stat arb close B failed");
                }
                *self.has_position.lock().await = 0;
            }
        }
        Ok(())
    }
}

#[async_trait]
impl Strategy for StatArb {
    async fn run(&self) -> Result<()> {
        tracing::info!(
            symbol_a = %self.config.symbol_a,
            symbol_b = %self.config.symbol_b,
            hedge_ratio = %self.config.hedge_ratio,
            "starting statistical arbitrage"
        );
        let poll = std::time::Duration::from_secs(self.config.common.poll_secs.max(1));
        loop {
            if let Err(err) = self.tick().await {
                tracing::error!(error = %err, "stat arb tick failed");
            }
            tokio::time::sleep(poll).await;
        }
    }
}

#[cfg(test)]
mod tests {
    use rust_decimal_macros::dec;

    use super::*;

    #[test]
    fn spread_tracker_mean_and_stdev() {
        let mut t = SpreadTracker::new(5);
        t.push(dec!(1));
        t.push(dec!(2));
        t.push(dec!(3));
        assert_eq!(t.mean(), Some(dec!(2)));
        assert!(t.stdev().is_some());
    }

    #[test]
    fn spread_tracker_z_score() {
        let mut t = SpreadTracker::new(10);
        for _ in 0..5 {
            t.push(dec!(10));
        }
        // All identical → stdev = 0 → no z-score.
        assert!(t.z_score(dec!(10)).is_none());
        t.push(dec!(20));
        assert!(t.z_score(dec!(20)).is_some());
    }

    #[test]
    fn spread_tracker_window_slides() {
        let mut t = SpreadTracker::new(2);
        t.push(dec!(10));
        t.push(dec!(20));
        t.push(dec!(30));
        assert_eq!(t.mean(), Some(dec!(25)));
    }

    #[test]
    fn classify_stat_arb_entry_and_exit() {
        assert_eq!(
            classify_stat_arb(Some(dec!(2.5)), dec!(2), dec!(0.5), false),
            StatArbSignal::ShortSpread
        );
        assert_eq!(
            classify_stat_arb(Some(dec!(-2.5)), dec!(2), dec!(0.5), false),
            StatArbSignal::LongSpread
        );
        assert_eq!(
            classify_stat_arb(Some(dec!(0.2)), dec!(2), dec!(0.5), true),
            StatArbSignal::Close
        );
    }

    #[test]
    fn config_parses_from_table() {
        let table: toml::Table = toml::from_str(
            "symbol = \"BTC/USDT\"\nsymbol_a = \"BTC/USDT\"\n\
             symbol_b = \"ETH/USDT\"\nexchange_id = \"mock\"\nentry_threshold = \"1.5\"",
        )
        .expect("toml");
        let cfg = StatArbConfig::from_params(&table).expect("parse");
        assert_eq!(cfg.symbol_a, "BTC/USDT");
        assert_eq!(cfg.symbol_b, "ETH/USDT");
        assert_eq!(cfg.entry_threshold, dec!(1.5));
    }

    #[test]
    fn config_overrides_defaults() {
        let table: toml::Table = toml::from_str(
            "symbol = \"BTC/USDT\"\nsymbol_a = \"BTC/USDT\"\n\
             symbol_b = \"ETH/USDT\"\nhedge_ratio = \"0.5\"\nwindow = 100\nqty = \"0.1\"",
        )
        .expect("toml");
        let cfg = StatArbConfig::from_params(&table).expect("parse");
        assert_eq!(cfg.hedge_ratio, dec!(0.5));
        assert_eq!(cfg.window, 100);
        assert_eq!(cfg.qty, dec!(0.1));
    }
}