Skip to content

Commit

Permalink
respect config and add persistence to it
Browse files Browse the repository at this point in the history
  • Loading branch information
x86y committed Mar 18, 2024
1 parent 636bfab commit aae12ff
Show file tree
Hide file tree
Showing 9 changed files with 282 additions and 95 deletions.
48 changes: 47 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ iced_native = "0.10.3"
itertools = "0.11.0"
lazy_static = "1.4.0"
once_cell = "1.18.0"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.114"
warp = "0.3.5"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
directories-next = "2.0"

[target.'cfg(target_arch = "wasm32")'.dependencies]
uuid = { version = "1.0", features = ["js"] }
web-sys = { features = ["Window", "Storage"] }
Expand Down
25 changes: 10 additions & 15 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
use std::env;

use binance::account::Account;
use binance::api::Binance;
use binance::errors::Error;
use binance::rest_model::{Balance, Order, OrderSide, Transaction};
use binance::wallet::Wallet;
use futures::future::join_all;
use lazy_static::lazy_static;

lazy_static! {
pub static ref PUB: Option<String> = env::var_os("DYN_PUB").map(|s| s.into_string().unwrap());
static ref SEC: Option<String> = env::var_os("DYN_SEC").map(|s| s.into_string().unwrap());
static ref B: Account = Binance::new(PUB.clone(), SEC.clone());
static ref W: Wallet = Binance::new(PUB.clone(), SEC.clone());
}

pub async fn orders_history() -> Vec<Order> {
pub async fn orders_history(public: String, secret: String) -> Vec<Order> {
let b: Account = Binance::new(Some(public), Some(secret));
let now = chrono::offset::Local::now();
let ago = now
.checked_sub_signed(chrono::Duration::try_weeks(8).unwrap())
Expand All @@ -29,7 +20,7 @@ pub async fn orders_history() -> Vec<Order> {
"SYNUSDT",
];
let mut os: Vec<Order> = join_all(assets.iter().map(|a: &&str| {
B.get_all_orders(binance::account::OrdersQuery {
b.get_all_orders(binance::account::OrdersQuery {
symbol: a.to_string(),
order_id: None,
start_time: Some(ago.timestamp_millis() as u64),
Expand All @@ -48,12 +39,15 @@ pub async fn orders_history() -> Vec<Order> {
}

pub async fn trade_spot(
public: String,
secret: String,
pair: String,
price: f64,
amt: f64,
side: OrderSide,
) -> Result<Transaction, Error> {
B.place_order(binance::account::OrderRequest {
let b: Account = Binance::new(Some(public), Some(secret));
b.place_order(binance::account::OrderRequest {
symbol: pair,
side,
order_type: binance::rest_model::OrderType::Limit,
Expand All @@ -70,9 +64,10 @@ pub async fn trade_spot(
.await
}

pub async fn balances() -> Vec<Balance> {
pub async fn balances(public: String, secret: String) -> Vec<Balance> {
let b: Account = Binance::new(Some(public), Some(secret));
let assets = ["LINK", "UNI", "ARB", "OP", "SYN", "USDT", "OP"];
join_all(assets.iter().map(|a| B.get_balance(a.to_string())))
join_all(assets.iter().map(|a| b.get_balance(a.to_string())))
.await
.into_iter()
.flatten()
Expand Down
104 changes: 104 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
pub api_key: String,
pub api_secret_key: String,
}

#[derive(Debug, Clone)]
pub enum LoadError {
File,
Format,
}

#[derive(Debug, Clone)]
pub enum SaveError {
File,
Write,
Format,
}

#[cfg(not(target_arch = "wasm32"))]
impl Config {
fn path() -> std::path::PathBuf {
let mut path = if let Some(project_dirs) =
directories_next::ProjectDirs::from("rs", "x86y", "Dynasty")
{
project_dirs.data_dir().into()
} else {
std::env::current_dir().unwrap_or_default()
};
path.push("config.json");
path
}

pub async fn load() -> Result<Config, LoadError> {
use tokio::fs::File;
use tokio::io::AsyncReadExt;

let mut contents = String::new();
let mut file = File::open(Self::path())
.await
.map_err(|_| LoadError::File)?;
file.read_to_string(&mut contents)
.await
.map_err(|_| LoadError::File)?;
serde_json::from_str(&contents).map_err(|_| LoadError::Format)
}

pub async fn save(self) -> Result<(), SaveError> {
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?;
let path = Self::path();
if let Some(dir) = path.parent() {
tokio::fs::create_dir_all(dir)
.await
.map_err(|_| SaveError::File)?;
}
{
let mut file = File::create(path).await.map_err(|_| SaveError::File)?;
file.write_all(json.as_bytes())
.await
.map_err(|_| SaveError::Write)?;
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
Ok(())
}
}

#[cfg(target_arch = "wasm32")]
impl Config {
fn storage() -> Option<web_sys::Storage> {
let window = web_sys::window()?;

window.local_storage().ok()?
}

async fn load() -> Result<Config, LoadError> {
let storage = Self::storage().ok_or(LoadError::File)?;

let contents = storage
.get_item("state")
.map_err(|_| LoadError::File)?
.ok_or(LoadError::File)?;

serde_json::from_str(&contents).map_err(|_| LoadError::Format)
}

async fn save(self) -> Result<(), SaveError> {
let storage = Self::storage().ok_or(SaveError::File)?;

let json = serde_json::to_string_pretty(&self).map_err(|_| SaveError::Format)?;

storage
.set_item("state", &json)
.map_err(|_| SaveError::Write)?;

let _ = wasm_timer::Delay::new(std::time::Duration::from_secs(2)).await;

Ok(())
}
}
Loading

0 comments on commit aae12ff

Please sign in to comment.