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
//! Crypto-bank exchanges implementation

use std::sync::Arc;

use colored::*;
use futures_locks::RwLock;
use hashbrown::hash_map::Entry;
use hashbrown::HashMap;

use cxmr_exchanges::{AccountInfo, Exchange, Market, MarketOrder, OrderStatus};
use cxmr_feeds::{EventData, Events, ExecutionReport, UserEvent};
use cxmr_orderbook::OrderBook;

use super::account::BrokerAccount;
use super::exchange::ExchangeBroker;
use super::market::MarketBroker;

use super::Error;

/// Shared Broker type alias.
pub type SharedBroker = Arc<RwLock<Broker>>;

/// Broker exchanges.
pub type BrokerExchanges = HashMap<Exchange, ExchangeBroker>;

/// Account orders by order ID.
pub type AccountOrders = HashMap<String, MarketOrder>;

/// Broker orders by account name.
pub type OrderMap = HashMap<String, AccountOrders>;

/// Exchanges broker.
pub struct Broker {
    orders: OrderMap,
    accounts: Vec<BrokerAccount>,
    exchanges: BrokerExchanges,
    data_keys: HashMap<String, String>,
}

impl Broker {
    /// Creates new broker.
    pub fn new(accounts: Vec<BrokerAccount>, exchanges: BrokerExchanges) -> Self {
        Broker {
            orders: HashMap::new(),
            accounts: accounts,
            exchanges: exchanges,
            data_keys: HashMap::new(),
        }
    }

    /// Creates new broker for simulation.
    pub fn new_simulation(exchanges: BrokerExchanges) -> Self {
        Broker {
            orders: HashMap::new(),
            accounts: Vec::new(),
            exchanges: exchanges,
            data_keys: HashMap::new(),
        }
    }

    /// Returns all broker accounts.
    pub fn accounts(&self) -> &[BrokerAccount] {
        &self.accounts
    }

    /// Returns all broker orders.
    pub fn orders(&self) -> &OrderMap {
        &self.orders
    }

    /// Returns all exchanges brokers.
    pub fn exchanges(&self) -> Vec<&ExchangeBroker> {
        self.exchanges.iter().map(|(_, b)| b).collect()
    }

    /// Returns broker exchange by it's identifier.
    pub fn get(&self, exchange: &Exchange) -> Option<&ExchangeBroker> {
        self.exchanges.get(exchange)
    }

    /// Gets market by exchange and currency pair.
    pub fn get_market(&self, market: Market) -> Option<&MarketBroker> {
        self.exchanges
            .get(&market.exchange())?
            .get(&market.currency_pair())
    }

    /// Gets market by exchange and currency pair.
    pub fn get_market_mut(&mut self, market: Market) -> Option<&mut MarketBroker> {
        self.exchanges
            .get_mut(&market.exchange())?
            .get_mut(&market.currency_pair())
    }

    /// Gets ask price on a market.
    pub fn get_ask_price(&self, market: Market) -> Option<u64> {
        self.get_market(market)?.asks().first()
    }

    /// Gets bid price on a market.
    pub fn get_bid_price(&self, market: Market) -> Option<u64> {
        self.get_market(market)?.bids().first()
    }

    /// Updates order book and accounts.
    pub fn update(&mut self, events: Events) -> Result<Events, Error> {
        let market = self.get_market_mut(events.market.clone())?;
        Ok(market.orderbook.consume(events)?)
    }

    /// Updates order book and accounts.
    pub fn update_private<'a, I>(&mut self, acc: &str, events: Vec<UserEvent>)
    where
        I: Iterator<Item = &'a UserEvent>,
    {
        for event in events {
            match event {
                UserEvent::UpdateAccount(ref info) => self.update_account(acc.to_owned(), info),
                UserEvent::OrderExecution(ref order) => self.update_order(acc.to_owned(), order),
            }
        }
    }

    /// Returns user data stream key for account, if any.
    pub fn user_data_key(&self, name: &str) -> Option<String> {
        self.data_keys.get(name).map(|v| v.clone())
    }

    /// Sets user data stream key for account.
    pub fn set_user_data_key(&mut self, name: String, key: String) {
        self.data_keys.insert(name, key);
    }

    /// Inserts orders under account name.
    pub fn insert_orders(&mut self, account: String, orders: Vec<MarketOrder>) {
        let result = self.orders.entry(account).or_insert(HashMap::new());
        orders.into_iter().for_each(|order| {
            result.insert(order.id.clone(), order);
        });
    }

    /// Updates market order books from data rows.
    pub fn update_from_row(&mut self, market: Market, row: &EventData) -> Result<(), Error> {
        let market = self.get_market_mut(market)?;
        market.orderbook.update_from_row(row);
        Ok(())
    }

    /// Updates market order books from data rows.
    pub fn update_from_rows(&mut self, market: Market, rows: &Vec<EventData>) -> Result<(), Error> {
        let market = self.get_market_mut(market)?;
        market.orderbook.update_from_rows(rows);
        Ok(())
    }

    /// Updates market order books.
    pub fn update_orderbook(&mut self, market: Market, orderbook: OrderBook) -> Result<(), Error> {
        let market = self.get_market_mut(market)?;
        market.orderbook = orderbook;
        Ok(())
    }

    fn update_account(&mut self, account: String, info: &AccountInfo) {
        let account = self
            .accounts
            .iter_mut()
            .find(|acc| acc.name() == &account)
            .unwrap();
        account.update_info(info.clone());
    }

    fn update_order(&mut self, account: String, report: &ExecutionReport) {
        let orders = self.orders.entry(account).or_insert(HashMap::new());
        match report.status {
            OrderStatus::New | OrderStatus::PartiallyFilled => {
                match orders.entry(report.id.clone()) {
                    Entry::Occupied(mut entry) => {
                        let order = entry.get_mut();
                        order.rate = report.rate;
                        order.stop = report.stop;
                        order.amount = report.amount;
                        order.executed = report.executed;
                        order.updated_at = report.updated_at;
                        info!("Order {} {}", &report.id, "created".green());
                    }
                    Entry::Vacant(_) => {
                        error!("Order created with Web Interface");
                    }
                }
            }
            OrderStatus::Filled
            | OrderStatus::Canceled
            | OrderStatus::PendingCancel
            | OrderStatus::Rejected
            | OrderStatus::Expired => {
                info!("Order {} {}", &report.id, "removed".bright_red());
                orders.remove(&report.id);
            }
        }
    }

    /// Wraps broker in an `Arc` and `RwLock`.
    pub fn into_shared(self) -> SharedBroker {
        Arc::new(RwLock::new(self))
    }
}