Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: backups snapshot every 3 secs #43

Merged
merged 1 commit into from
Aug 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 35 additions & 4 deletions crates/engine/src/trade/engine.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use tokio::time::{self, Duration};

use super::orderbook::Orderbook;
use crate::utils::load_snapshot;
use crate::{types::SnapShot, utils::load_snapshot};
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize, Clone)]
Expand All @@ -18,15 +20,15 @@ pub struct UserBalance {
}
pub type Balances = Vec<Vec<UserBalance>>;

#[derive(Serialize, Deserialize, Clone)]
pub struct Engine {
orderbooks: Vec<Orderbook>,
balances: Vec<Balances>,
}

// TODO: save the snapshot after an interval and set the user balance
impl Engine {
pub fn new() -> Engine {
if let Ok(path) = env::var("SNAPSHOT_PATH") {
pub async fn new() -> Engine {
let mut engine = if let Ok(path) = env::var("SNAPSHOT_PATH") {
let snapshot = load_snapshot(path.as_str());
match snapshot {
Ok(snapshot) => Engine {
Expand All @@ -47,6 +49,35 @@ impl Engine {
orderbooks: vec![Orderbook::new(&vec![], &vec![], "BTC", "USDT", 0.0, "0")],
balances: vec![Balances::new()],
}
};

let mut engine_clone = engine.clone();
tokio::spawn(async move {
engine_clone.start_saving_snapshots().await;
});

engine
}

async fn save_snapshot(&self) {
let snap = SnapShot {
orderbooks: self.orderbooks.clone(),
balances: self.balances.clone(),
};

if let Ok(path) = env::var("SNAPSHOT_PATH") {
let snapshot = serde_json::to_string(&snap).unwrap();
fs::write(path, snapshot).unwrap();
} else {
println!("SNAPSHOT_PATH not set, snapshot not saved");
}
}

async fn start_saving_snapshots(&mut self) {
let mut interval = time::interval(Duration::from_secs(3));
loop {
interval.tick().await;
self.save_snapshot().await;
}
}
}
Loading