Skip to content

Commit

Permalink
Fix clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
cjdsellers committed Dec 18, 2023
1 parent 88a3628 commit bd20220
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 33 deletions.
8 changes: 4 additions & 4 deletions nautilus_core/backtest/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ mod tests {
// Note: as_ptr returns a borrowed pointer. It is valid as long
// as the object is in scope. In this case `callback_ptr` is valid
// as long as `py_append` is in scope.
let callback_ptr = py_append.as_ptr() as *mut pyo3::ffi::PyObject;
let callback_ptr = py_append.as_ptr().cast::<pyo3::ffi::PyObject>();

let handler1 = TimeEventHandler {
event: time_event1.clone(),
Expand All @@ -150,9 +150,9 @@ mod tests {
callback_ptr,
};

accumulator.event_handlers.push(handler1.clone());
accumulator.event_handlers.push(handler2.clone());
accumulator.event_handlers.push(handler3.clone());
accumulator.event_handlers.push(handler1);
accumulator.event_handlers.push(handler2);
accumulator.event_handlers.push(handler3);

let drained_handlers = accumulator.drain();

Expand Down
4 changes: 2 additions & 2 deletions nautilus_core/core/src/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,11 @@ pub fn last_weekday_nanos(year: i32, month: u32, day: u32) -> Result<UnixNanos>
let current_weekday = date.weekday().number_from_monday();

// Calculate the offset in days for closest weekday (Mon-Fri)
let offset = match current_weekday {
let offset = i64::from(match current_weekday {
1..=5 => 0, // Monday to Friday, no adjustment needed
6 => 1, // Saturday, adjust to previous Friday
_ => 2, // Sunday, adjust to previous Friday
} as i64;
});

// Calculate last closest weekday
let last_closest = date - chrono::Duration::days(offset);
Expand Down
37 changes: 22 additions & 15 deletions nautilus_core/core/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,17 @@ pub enum ClockMode {
STATIC,
}

/// Atomic clock stores the last recorded time in nanoseconds
/// Atomic clock stores the last recorded time in nanoseconds.
///
/// It uses AtomicU64 to atomically update the value using only immutable
/// It uses `AtomicU64` to atomically update the value using only immutable
/// references.
///
/// AtomicClock can act as a live clock and static clock based on its mode.
/// `AtomicClock` can act as a live clock and static clock based on its mode.
#[derive(Debug, Clone)]
pub struct AtomicTime {
/// Atomic clock is operating in live or static mode
/// Atomic clock is operating in live or static mode.
mode: ClockMode,
/// The last recorded time in nanoseconds for the clock
/// The last recorded time in nanoseconds for the clock.
timestamp_ns: Arc<AtomicU64>,
}

Expand All @@ -68,9 +68,10 @@ impl Deref for AtomicTime {
}

impl AtomicTime {
/// New atomic clock set with the given time
/// New atomic clock set with the given time.
#[must_use]
pub fn new(mode: ClockMode, time: u64) -> Self {
AtomicTime {
Self {
mode,
timestamp_ns: Arc::new(AtomicU64::new(time)),
}
Expand All @@ -80,41 +81,47 @@ impl AtomicTime {
///
/// * Live mode returns current wall clock time since UNIX epoch (unique and monotonic)
/// * Static mode returns currently stored time.
#[must_use]
pub fn get_time_ns(&self) -> u64 {
match self.mode {
ClockMode::LIVE => self.time_since_epoch(),
ClockMode::STATIC => self.timestamp_ns.load(Ordering::Relaxed),
}
}

/// Get time as microseconds
/// Get time as microseconds.
#[must_use]
pub fn get_time_us(&self) -> u64 {
self.get_time_ns() / NANOSECONDS_IN_MICROSECOND
}

/// Get time as milliseconds
/// Get time as milliseconds.
#[must_use]
pub fn get_time_ms(&self) -> u64 {
self.get_time_ns() / NANOSECONDS_IN_MILLISECOND
}

/// Get time as seconds
/// Get time as seconds.
#[must_use]
pub fn get_time(&self) -> f64 {
self.get_time_ns() as f64 / (NANOSECONDS_IN_SECOND as f64)
}

/// Sets new time for the clock
/// Sets new time for the clock.
pub fn set_time(&self, time: u64) {
self.store(time, Ordering::Relaxed)
self.store(time, Ordering::Relaxed);
}

/// Increments current time with a delta and returns the updated time
/// Increments current time with a delta and returns the updated time.
#[must_use]
pub fn increment_time(&self, delta: u64) -> u64 {
self.fetch_add(delta, Ordering::Relaxed) + delta
}

/// Stores and returns current time
/// Stores and returns current time.
#[must_use]
pub fn time_since_epoch(&self) -> u64 {
// increment by 1 nanosecond to keep increasing time
// Increment by 1 nanosecond to keep increasing time
let now = duration_since_unix_epoch().as_nanos() as u64 + 1;
let last = self.load(Ordering::SeqCst) + 1;
let new = now.max(last);
Expand Down
2 changes: 1 addition & 1 deletion nautilus_core/indicators/src/average/hma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ impl HullMovingAverage {
let _ma2 = WeightedMovingAverage::new(period, w2, price_type)?;
let _ma3 = WeightedMovingAverage::new(period_sqrt, w3, price_type)?;

Ok(HullMovingAverage {
Ok(Self {
period,
price_type: price_type.unwrap_or(PriceType::Last),
value: 0.0,
Expand Down
2 changes: 1 addition & 1 deletion nautilus_core/network/src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ impl SocketClient {
(true, true) => {
debug!("Shutting down inner client");
match inner.shutdown().await {
Ok(_) => debug!("Closed connection"),
Ok(()) => debug!("Closed connection"),
Err(e) => error!("Error on `shutdown`: {e}"),
}

Expand Down
4 changes: 2 additions & 2 deletions nautilus_core/persistence/src/db/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ pub async fn init_db_schema(db: &Database, schema_dir: &str) -> Result<()> {
let mut sql_files =
std::fs::read_dir(schema_dir)?.collect::<Result<Vec<_>, std::io::Error>>()?;

for file in sql_files.iter_mut() {
for file in &mut sql_files {
let file_name = file.file_name();
println!("Executing SQL file: {:?}", file_name);
println!("Executing SQL file: {file_name:?}");
let file_path = file.path();
let sql_content = std::fs::read_to_string(file_path.clone())?;
for sql_statement in sql_content.split(';').filter(|s| !s.trim().is_empty()) {
Expand Down
10 changes: 6 additions & 4 deletions nautilus_core/persistence/src/db/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,32 @@ pub struct SqlCacheDatabase {
}

impl SqlCacheDatabase {
#[must_use]
pub fn new(trader_id: TraderId, database: Database) -> Self {
Self {
trader_id,
db: database,
}
}
#[must_use]
pub fn key_trader(&self) -> String {
format!("trader-{}", self.trader_id)
}

#[must_use]
pub fn key_general(&self) -> String {
format!("{}:general:", self.key_trader())
}

pub async fn add(&self, key: String, value: String) -> Result<u64, Error> {
let query = format!(
"INSERT INTO general (key, value) VALUES ('{}', '{}') ON CONFLICT (key) DO NOTHING;",
key, value
"INSERT INTO general (key, value) VALUES ('{key}', '{value}') ON CONFLICT (key) DO NOTHING;"
);
self.db.execute(query.as_str()).await
}

pub async fn get(&self, key: String) -> Vec<GeneralItem> {
let query = format!("SELECT * FROM general WHERE key = '{}'", key);
let query = format!("SELECT * FROM general WHERE key = '{key}'");
self.db
.fetch_all::<GeneralItem>(query.as_str())
.await
Expand Down Expand Up @@ -93,7 +95,7 @@ mod tests {
.expect("Failed to add key");
let value = cache.get(String::from("key1")).await;
assert_eq!(value.len(), 1);
let item = value.get(0).unwrap();
let item = value.first().unwrap();
assert_eq!(item.key, "key1");
assert_eq!(item.value, "value1");
}
Expand Down
8 changes: 4 additions & 4 deletions nautilus_core/persistence/tests/test_catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ fn test_quote_tick_python_interface() {
.add_file::<QuoteTick>("quote_005", file_path, None)
.unwrap();
let query_result: QueryResult = catalog.get_query_result();
let mut query_result = DataQueryResult::new(query_result, catalog.chunk_size);
let query_result = DataQueryResult::new(query_result, catalog.chunk_size);
let mut count = 0;
while let Some(chunk) = query_result.next() {
if chunk.len() == 0 {
for chunk in query_result {
if chunk.is_empty() {
break;
}
let chunk: CVec = chunk.into();
let ticks: &[Data] =
unsafe { std::slice::from_raw_parts(chunk.ptr as *const Data, chunk.len) };
count += ticks.len();
assert!(is_monotonically_increasing_by_init(&ticks));
assert!(is_monotonically_increasing_by_init(ticks));
}

assert_eq!(expected_length, count);
Expand Down

0 comments on commit bd20220

Please sign in to comment.