Skip to content

Commit ab55a2a

Browse files
committed
Continue Cache in Rust
1 parent 649238e commit ab55a2a

File tree

1 file changed

+79
-17
lines changed
  • nautilus_core/common/src/cache

1 file changed

+79
-17
lines changed

nautilus_core/common/src/cache/mod.rs

Lines changed: 79 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,28 +31,29 @@ use nautilus_model::{
3131
quote::QuoteTick,
3232
trade::TradeTick,
3333
},
34-
enums::{OrderSide, PositionSide},
34+
enums::{OrderSide, PositionSide, PriceType},
3535
identifiers::{
3636
account_id::AccountId, client_id::ClientId, client_order_id::ClientOrderId,
3737
component_id::ComponentId, exec_algorithm_id::ExecAlgorithmId, instrument_id::InstrumentId,
38-
position_id::PositionId, strategy_id::StrategyId, venue::Venue,
38+
order_list_id::OrderListId, position_id::PositionId, strategy_id::StrategyId, venue::Venue,
3939
venue_order_id::VenueOrderId,
4040
},
4141
instruments::{synthetic::SyntheticInstrument, InstrumentAny},
4242
orderbook::book::OrderBook,
43-
orders::base::OrderAny,
43+
orders::{base::OrderAny, list::OrderList},
4444
polymorphism::{
4545
GetClientOrderId, GetExecAlgorithmId, GetExecSpawnId, GetInstrumentId, GetOrderSide,
4646
GetStrategyId,
4747
},
4848
position::Position,
49-
types::currency::Currency,
49+
types::{currency::Currency, price::Price},
5050
};
5151
use ustr::Ustr;
5252

5353
use self::database::CacheDatabaseAdapter;
5454
use crate::{enums::SerializationEncoding, interface::account::Account};
5555

56+
/// The configuration for `Cache` instances.
5657
pub struct CacheConfig {
5758
pub encoding: SerializationEncoding,
5859
pub timestamps_as_iso8601: bool,
@@ -105,6 +106,7 @@ impl Default for CacheConfig {
105106
}
106107
}
107108

109+
/// A key-value lookup index for a `Cache`.
108110
pub struct CacheIndex {
109111
venue_account: HashMap<Venue, AccountId>,
110112
venue_orders: HashMap<Venue, HashSet<ClientOrderId>>,
@@ -168,6 +170,7 @@ impl CacheIndex {
168170
}
169171
}
170172

173+
/// A common in-memory `Cache` for market and execution related data.
171174
pub struct Cache {
172175
config: CacheConfig,
173176
index: CacheIndex,
@@ -182,7 +185,7 @@ pub struct Cache {
182185
synthetics: HashMap<InstrumentId, SyntheticInstrument>,
183186
accounts: HashMap<AccountId, Box<dyn Account>>,
184187
orders: HashMap<ClientOrderId, OrderAny>,
185-
// order_lists: HashMap<OrderListId, VecDeque<OrderList>>, TODO: Need `OrderList`
188+
order_lists: HashMap<OrderListId, VecDeque<OrderList>>,
186189
positions: HashMap<PositionId, Position>,
187190
position_snapshots: HashMap<PositionId, Vec<u8>>,
188191
}
@@ -240,7 +243,7 @@ impl Cache {
240243
synthetics: HashMap::new(),
241244
accounts: HashMap::new(),
242245
orders: HashMap::new(),
243-
// order_lists: HashMap<OrderListId, VecDeque<OrderList>>, TODO: Need `OrderList`
246+
order_lists: HashMap::new(),
244247
positions: HashMap::new(),
245248
position_snapshots: HashMap::new(),
246249
}
@@ -317,13 +320,6 @@ impl Cache {
317320
Ok(())
318321
}
319322

320-
// pub fn cache_order_lists(&mut self) -> anyhow::Result<()> {
321-
//
322-
//
323-
// info!("Cached {} order lists from database", self.general.len());
324-
// Ok(())
325-
// }
326-
327323
pub fn cache_positions(&mut self) -> anyhow::Result<()> {
328324
self.positions = match &self.database {
329325
Some(db) => db.load_positions()?,
@@ -1185,12 +1181,78 @@ impl Cache {
11851181
self.orders(venue, instrument_id, strategy_id, side).len()
11861182
}
11871183

1188-
// -- DATA QUERIES --------------------------------------------------------
1184+
// -- GENERAL -------------------------------------------------------------
11891185

1190-
pub fn get(&self, key: &str) -> anyhow::Result<Option<&Vec<u8>>> {
1186+
pub fn get(&self, key: &str) -> anyhow::Result<Option<&[u8]>> {
11911187
check_valid_string(key, stringify!(key))?;
11921188

1193-
Ok(self.general.get(key))
1189+
Ok(self.general.get(key).map(|x| x.as_slice()))
1190+
}
1191+
1192+
// -- DATA QUERIES --------------------------------------------------------
1193+
1194+
pub fn price(&self, instrument_id: &InstrumentId, price_type: PriceType) -> Option<Price> {
1195+
match price_type {
1196+
PriceType::Bid => self
1197+
.quotes
1198+
.get(instrument_id)
1199+
.and_then(|quotes| quotes.front().map(|quote| quote.bid_price)),
1200+
PriceType::Ask => self
1201+
.quotes
1202+
.get(instrument_id)
1203+
.and_then(|quotes| quotes.front().map(|quote| quote.ask_price)),
1204+
PriceType::Mid => self.quotes.get(instrument_id).and_then(|quotes| {
1205+
quotes.front().map(|quote| {
1206+
Price::new(
1207+
(quote.ask_price.as_f64() + quote.bid_price.as_f64()) / 2.0,
1208+
quote.bid_price.precision + 1,
1209+
)
1210+
.expect("Error calculating mid price")
1211+
})
1212+
}),
1213+
PriceType::Last => self
1214+
.trades
1215+
.get(instrument_id)
1216+
.and_then(|trades| trades.front().map(|trade| trade.price)),
1217+
}
1218+
}
1219+
1220+
pub fn quote_ticks(&self, instrument_id: &InstrumentId) -> Option<Vec<QuoteTick>> {
1221+
self.quotes
1222+
.get(instrument_id)
1223+
.map(|quotes| quotes.iter().cloned().collect())
1224+
}
1225+
1226+
pub fn trade_ticks(&self, instrument_id: &InstrumentId) -> Option<Vec<TradeTick>> {
1227+
self.trades
1228+
.get(instrument_id)
1229+
.map(|trades| trades.iter().cloned().collect())
1230+
}
1231+
1232+
pub fn bars(&self, bar_type: &BarType) -> Option<Vec<Bar>> {
1233+
self.bars
1234+
.get(bar_type)
1235+
.map(|bars| bars.iter().cloned().collect())
1236+
}
1237+
1238+
pub fn order_book(&self, instrument_id: &InstrumentId) -> Option<&OrderBook> {
1239+
self.books.get(instrument_id)
1240+
}
1241+
1242+
pub fn quote_tick(&self, instrument_id: &InstrumentId) -> Option<&QuoteTick> {
1243+
self.quotes
1244+
.get(instrument_id)
1245+
.and_then(|quotes| quotes.front())
1246+
}
1247+
1248+
pub fn trade_tick(&self, instrument_id: &InstrumentId) -> Option<&TradeTick> {
1249+
self.trades
1250+
.get(instrument_id)
1251+
.and_then(|trades| trades.front())
1252+
}
1253+
1254+
pub fn bar(&self, bar_type: &BarType) -> Option<&Bar> {
1255+
self.bars.get(bar_type).and_then(|bars| bars.front())
11941256
}
11951257
}
11961258

@@ -1245,6 +1307,6 @@ mod tests {
12451307
cache.add(key, value.clone()).unwrap();
12461308

12471309
let result = cache.get(key).unwrap();
1248-
assert_eq!(result, Some(&value));
1310+
assert_eq!(result, Some(&value.as_slice()).copied());
12491311
}
12501312
}

0 commit comments

Comments
 (0)