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
use crate::{
    error::DataError,
    event::{MarketEvent, MarketIter},
    exchange::Connector,
    subscription::{book::OrderBook, Map, SubKind},
    transformer::ExchangeTransformer,
    Identifier,
};
use async_trait::async_trait;
use barter_integration::{
    model::{Instrument, SubscriptionId},
    protocol::websocket::WsMessage,
    Transformer,
};
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use tokio::sync::mpsc;

/// Defines how to apply a [`Self::Update`] to an [`Self::OrderBook`].
#[async_trait]
pub trait OrderBookUpdater
where
    Self: Sized,
{
    type OrderBook;
    type Update;

    /// Initialises the [`InstrumentOrderBook`] for the provided [`Instrument`]. This often requires
    /// a HTTP call to receive a starting [`OrderBook`] snapshot.
    async fn init<Exchange, Kind>(
        ws_sink_tx: mpsc::UnboundedSender<WsMessage>,
        instrument: Instrument,
    ) -> Result<InstrumentOrderBook<Self>, DataError>
    where
        Exchange: Send,
        Kind: Send;

    /// Apply the [`Self::Update`] to the provided mutable [`Self::OrderBook`].
    fn update(
        &mut self,
        book: &mut Self::OrderBook,
        update: Self::Update,
    ) -> Result<Option<Self::OrderBook>, DataError>;
}

/// [`OrderBook`] for an [`Instrument`] with an exchange specific [`OrderBookUpdater`] to define
/// how to update it.
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct InstrumentOrderBook<Updater> {
    pub instrument: Instrument,
    pub updater: Updater,
    pub book: OrderBook,
}

/// Standard generic [`ExchangeTransformer`] to translate exchange specific OrderBook types into
/// normalised Barter OrderBook types. Requires an exchange specific [`OrderBookUpdater`]
/// implementation.
#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
pub struct MultiBookTransformer<Exchange, Kind, Updater> {
    pub book_map: Map<InstrumentOrderBook<Updater>>,
    phantom: PhantomData<(Exchange, Kind)>,
}

#[async_trait]
impl<Exchange, Kind, Updater> ExchangeTransformer<Exchange, Kind>
    for MultiBookTransformer<Exchange, Kind, Updater>
where
    Exchange: Connector + Send,
    Kind: SubKind<Event = OrderBook> + Send,
    Updater: OrderBookUpdater<OrderBook = Kind::Event> + Send,
    Updater::Update: Identifier<Option<SubscriptionId>> + for<'de> Deserialize<'de>,
{
    async fn new(
        ws_sink_tx: mpsc::UnboundedSender<WsMessage>,
        map: Map<Instrument>,
    ) -> Result<Self, DataError> {
        // Initialise InstrumentOrderBooks for all Subscriptions
        let (sub_ids, init_book_requests): (Vec<_>, Vec<_>) = map
            .0
            .into_iter()
            .map(|(sub_id, instrument)| {
                (
                    sub_id,
                    Updater::init::<Exchange, Kind>(ws_sink_tx.clone(), instrument),
                )
            })
            .unzip();

        // Await all initial OrderBook snapshot requests
        let init_order_books = futures::future::join_all(init_book_requests)
            .await
            .into_iter()
            .collect::<Result<Vec<InstrumentOrderBook<Updater>>, DataError>>()?;

        // Construct OrderBookMap if all requests successful
        let book_map = sub_ids
            .into_iter()
            .zip(init_order_books.into_iter())
            .collect::<Map<InstrumentOrderBook<Updater>>>();

        Ok(Self {
            book_map,
            phantom: PhantomData::default(),
        })
    }
}

impl<Exchange, Kind, Updater> Transformer for MultiBookTransformer<Exchange, Kind, Updater>
where
    Exchange: Connector,
    Kind: SubKind<Event = OrderBook>,
    Updater: OrderBookUpdater<OrderBook = Kind::Event>,
    Updater::Update: Identifier<Option<SubscriptionId>> + for<'de> Deserialize<'de>,
{
    type Error = DataError;
    type Input = Updater::Update;
    type Output = MarketEvent<Kind::Event>;
    type OutputIter = Vec<Result<Self::Output, Self::Error>>;

    fn transform(&mut self, update: Self::Input) -> Self::OutputIter {
        // Determine if the update has an identifiable SubscriptionId
        let subscription_id = match update.id() {
            Some(subscription_id) => subscription_id,
            None => return vec![],
        };

        // Retrieve the InstrumentOrderBook associated with this update (snapshot or delta)
        let book = match self.book_map.find_mut(&subscription_id) {
            Ok(book) => book,
            Err(unidentifiable) => return vec![Err(DataError::Socket(unidentifiable))],
        };

        // De-structure for ease
        let InstrumentOrderBook {
            instrument,
            book,
            updater,
        } = book;

        // Apply update (snapshot or delta) to OrderBook & generate Market<OrderBook> snapshot
        match updater.update(book, update) {
            Ok(Some(book)) => {
                MarketIter::<OrderBook>::from((Exchange::ID, instrument.clone(), book)).0
            }
            Ok(None) => vec![],
            Err(error) => vec![Err(error)],
        }
    }
}