Skip to content

Commit

Permalink
support env flag; fix f64 options;
Browse files Browse the repository at this point in the history
  • Loading branch information
royroyisroy committed May 2, 2024
1 parent 3903427 commit 92622a7
Show file tree
Hide file tree
Showing 10 changed files with 225 additions and 153 deletions.
28 changes: 14 additions & 14 deletions examples/rest_get_instruments.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use okx_rs::api::v5::model::InstrumentType::Spot;
use okx_rs::api::v5::testkit::with_public_client;
use okx_rs::api::v5::GetInstruments;
use okx_rs::api::{Options, Production, Rest};

#[tokio::main]
async fn main() {
with_public_client(|client| async move {
let response = client
.request(GetInstruments {
inst_type: Spot,
uly: None,
inst_family: None,
inst_id: None,
})
.await
.unwrap();
println!("{}", serde_json::to_string_pretty(&response).unwrap());
})
.await;
env_logger::try_init().unwrap();

let client = Rest::new(Options::new(Production));
let response = client
.request(GetInstruments {
inst_type: Spot,
uly: None,
inst_family: None,
inst_id: None,
})
.await
.unwrap();
println!("{}", serde_json::to_string_pretty(&response).unwrap());
}
7 changes: 4 additions & 3 deletions examples/ws_account.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use log::info;
use okx_rs::api::{DemoTrading, OKXEnv};
use tungstenite::Message;

use okx_rs::api::options::Options;
use okx_rs::api::v5::ws_convert::TryParseEvent;
use okx_rs::api::v5::{
AccountChannel, BalanceAndPositionChannel, InstrumentType, PositionsChannel,
};
use okx_rs::api::Options;
use okx_rs::websocket::OKXAuth;
use okx_rs::websocket::WebsocketChannel;

Expand All @@ -17,13 +18,13 @@ fn main() {
let secret = std::env::var("OKX_API_SECRET").unwrap();
let passphrase = std::env::var("OKX_API_PASSPHRASE").unwrap();
let options = Options {
env: DemoTrading,
key: Some(key),
secret: Some(secret),
passphrase: Some(passphrase),
};

let (mut client, response) =
tungstenite::connect("wss://ws.okx.com:8443/ws/v5/public").unwrap();
let (mut client, response) = tungstenite::connect(DemoTrading.private_websocket()).unwrap();
println!("Connected to the server");
println!("Response HTTP code: {}", response.status());
println!("Response contains the following headers:");
Expand Down
5 changes: 3 additions & 2 deletions examples/ws_books.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use okx_rs::api::v5::ws_convert::TryParseEvent;
use okx_rs::api::OKXEnv;
use okx_rs::api::Production;
use okx_rs::websocket::conn::Books5;
use okx_rs::websocket::WebsocketChannel;

fn main() {
let (mut client, response) =
tungstenite::connect("wss://ws.okx.com:8443/ws/v5/public").unwrap();
let (mut client, response) = tungstenite::connect(Production.public_websocket()).unwrap();
println!("Connected to the server");
println!("Response HTTP code: {}", response.status());
println!("Response contains the following headers:");
Expand Down
2 changes: 1 addition & 1 deletion src/api/credential.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::options::Options;
use super::Options;
use base64::encode;
use hmac::{Hmac, Mac};
use reqwest::{Method, Url};
Expand Down
12 changes: 6 additions & 6 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::api::credential::Credential;
use crate::api::error::Error;
use crate::api::options::Options;
use crate::api::v5::{ApiResponse, Request};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, ClientBuilder, Method, Url};
Expand All @@ -10,12 +9,14 @@ use std::time::Duration;

use self::error::ApiError;

mod options;

pub mod credential;
pub mod error;
pub mod options;
pub use self::options::*;
pub mod v5;

#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct Rest {
options: Options,
client: Client,
Expand Down Expand Up @@ -76,9 +77,8 @@ impl Rest {
path.push_str(&params);
}
}
let url = format!("{}{}", "https://www.okx.com/api/v5", path);
let url = format!("{}{}", self.options().rest(), path);
log::debug!("{} {}", url, body);
// let timestamp = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
let now = std::time::SystemTime::now();
let timestamp = now
.duration_since(std::time::UNIX_EPOCH)
Expand Down Expand Up @@ -171,7 +171,7 @@ impl Rest {
})),
},
Err(e) => {
log::debug!("{}", String::from_utf8_lossy(&body));
log::error!("{}", String::from_utf8_lossy(&body));
Err(Error::Json(e))
}
}
Expand Down
80 changes: 79 additions & 1 deletion src/api/options.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,84 @@
#[derive(Debug, Clone, Default)]
use std::sync::Arc;

#[derive(Clone)]
pub struct Production;

impl OKXEnv for Production {
fn rest(&self) -> &str {
"https://www.okx.com/api/v5"
}

fn public_websocket(&self) -> &str {
"wss://ws.okx.com:8443/ws/v5/public"
}

fn private_websocket(&self) -> &str {
"wss://ws.okx.com:8443/ws/v5/private"
}

fn business_websocket(&self) -> &str {
"wss://ws.okx.com:8443/ws/v5/business"
}
}

#[derive(Clone)]
pub struct DemoTrading;

impl OKXEnv for DemoTrading {
fn rest(&self) -> &str {
"https://www.okx.com/api/v5"
}

fn public_websocket(&self) -> &str {
"wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"
}

fn private_websocket(&self) -> &str {
"wss://wspap.okx.com:8443/ws/v5/private?brokerId=9999"
}

fn business_websocket(&self) -> &str {
"wss://wspap.okx.com:8443/ws/v5/business?brokerId=9999"
}
}

pub trait OKXEnv {
fn rest(&self) -> &str;
fn public_websocket(&self) -> &str;
fn private_websocket(&self) -> &str;
fn business_websocket(&self) -> &str;
}

#[derive(Clone)]
pub struct Options {
pub env: Arc<dyn OKXEnv>,
pub key: Option<String>,
pub secret: Option<String>,
pub passphrase: Option<String>,
}

impl Options {
pub fn new(env: impl OKXEnv + 'static) -> Options {
Self {
env: Arc::new(env),
key: None,
secret: None,
passphrase: None,
}
}
}

impl Options {
pub fn rest(&self) -> &str {
self.env.rest()
}
pub fn public_websocket(&self) -> &str {
self.env.public_websocket()
}
pub fn private_websocket(&self) -> &str {
self.env.private_websocket()
}
pub fn business_websocket(&self) -> &str {
self.env.business_websocket()
}
}
4 changes: 2 additions & 2 deletions src/api/v5/funding_account/withdrawal.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::api::v5::Request;
use crate::impl_string_enum;
use crate::serde_util::{deserialize_from_opt_str, MaybeFloat};
use crate::serde_util::{deserialize_from_opt_str, str_opt, MaybeFloat};
use reqwest::Method;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -100,7 +100,7 @@ pub struct WithdrawalRequest {
pub ccy: Option<String>,
/// Withdrawal amount
/// Withdrawal fee is not included in withdrawal amount.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(skip_serializing_if = "Option::is_none", with = "str_opt")]
pub amt: MaybeFloat,
/// Withdrawal method
/// 3: internal transfer
Expand Down
Loading

0 comments on commit 92622a7

Please sign in to comment.