Quellcode durchsuchen

接入数据绘图,调整依赖版本

JiahengHe vor 10 Monaten
Ursprung
Commit
02cc1404b4
5 geänderte Dateien mit 91 neuen und 209 gelöschten Zeilen
  1. 29 25
      Cargo.toml
  2. 0 6
      src/core.rs
  3. 36 43
      src/strategy.rs
  4. 24 26
      src/trace_stack.rs
  5. 2 109
      src/utils.rs

+ 29 - 25
Cargo.toml

@@ -6,39 +6,43 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-tokio = { version = "1.31.0", features = ["full"] }
-chrono = "0.4.26"
-tracing = "0.1"
+tokio = { version = "=1.31.0", features = ["full"] }
+chrono = "=0.4.26"
+tracing = "=0.1"
 tracing-appender-timezone = { git = "https://github.com/skyfffire/tracing-appender-timezone.git" }
-serde = { version = "1.0.188", features = ["derive"] }
-actix-web = "4.0.0-beta.12"
-ctrlc = "3.2.5"
-serde_json = "1.0.105"
-rust_decimal = { version = "1.32.0", features = ["maths"] }
-rand = "0.8.5"
-futures-channel = "0.3.29"
-serde_derive = "1.0.190"
-futures = "0.3"
-reqwest = { version = "0.11.14", features = ["json"] }
-hex = "0.4"
-hmac = "0.8.1"
-sha2 = "0.9.8"
-base64 = "0.13"
+serde = { version = "=1.0.190", features = ["derive"] }
+actix-web = "=4.9.0"
+ctrlc = "=3.2.5"
+serde_json = "=1.0.105"
+rust_decimal = { version = "=1.32.0", features = ["maths"] }
+rand = "=0.8.5"
+futures-channel = "=0.3.29"
+serde_derive = "=1.0.190"
+futures = "=0.3"
+reqwest = { version = "=0.11.14", features = ["json"] }
+hex = "=0.4"
+hmac = "=0.8.1"
+sha2 = "=0.9.9"
+base64 = "=0.13"
 tokio-tungstenite= { git = "https://github.com/HonestHouLiang/tokio-tungstenite.git",rev = "208fc9b09bcc2e2c8cb52e1cde5087446464fc91"  }
-ring = "0.16.20"
-futures-util = { version = "0.3.28", default-features = false, features = ["sink", "std"] }
-toml = "0.5.11"
-time = { version = "0.3.7", features = ["macros"] }
-tracing-subscriber = { version = "0.3.17", features = [
+ring = "=0.16.20"
+futures-util = { version = "=0.3.29", default-features = false, features = ["sink", "std"] }
+toml = "=0.5.11"
+time = { version = "=0.3.35", features = ["macros"] }
+tracing-subscriber = { version = "=0.3.17", features = [
     "env-filter",
     "time",
     "local-time"
 ] }
 
+[target.'cfg(any(target_os = "linux"))'.dependencies.openssl]
+version = "*"
+features = ["vendored"]
+
 # 在确认程序运行无误后 可开启以下配置,可减少打包后的程序大小
-#[profile.release]
-#lto = true   # 启用链接时优化
-#strip = "debuginfo"  # 剥离调试信息
+[profile.release]
+lto = true   # 启用链接时优化
+strip = "debuginfo"  # 剥离调试信息
 
 #[workspace]
 #members=[

+ 0 - 6
src/core.rs

@@ -426,7 +426,6 @@ impl Core {
                         self.strategy.local_time = Utc::now().timestamp_millis();
                         let mut order = self.strategy.on_tick(&self.local_orders,
                                                               &self.local_position_by_orders,
-                                                              &self.agg_market,
                                                               &self.local_cash,
                                                               &self.local_coin,
                                                               &self.ref_price,
@@ -574,7 +573,6 @@ impl Core {
             // 产生交易信号
             let mut orders = self.strategy.on_tick(&self.local_orders,
                                                    &self.local_position_by_orders,
-                                                   &self.agg_market,
                                                    &self.local_cash,
                                                    &self.local_coin,
                                                    &self.ref_price,
@@ -1492,14 +1490,12 @@ pub fn run_strategy(core_arc: Arc<Mutex<Core>>) -> JoinHandle<()> {
                             // 先执行onExit
                             let local_orders = core.local_orders.clone();
                             let position = core.local_position_by_orders.clone();
-                            let agg_market = core.agg_market.clone();
                             let local_cash = core.local_cash.clone();
                             let local_coin = core.local_coin.clone();
                             let ref_price = core.ref_price.clone();
 
                             let mut orders = core.strategy.on_exit(&local_orders,
                                                                    &position,
-                                                                   &agg_market,
                                                                    &local_cash,
                                                                    &local_coin,
                                                                    &ref_price);
@@ -1516,14 +1512,12 @@ pub fn run_strategy(core_arc: Arc<Mutex<Core>>) -> JoinHandle<()> {
                             // 再执行onSleep
                             let local_orders = core.local_orders.clone();
                             let position = core.local_position_by_orders.clone();
-                            let agg_market = core.agg_market.clone();
                             let local_cash = core.local_cash.clone();
                             let local_coin = core.local_coin.clone();
                             let ref_price = core.ref_price.clone();
 
                             let mut orders = core.strategy.on_sleep(&local_orders,
                                                                     &position,
-                                                                    &agg_market,
                                                                     &local_cash,
                                                                     &local_coin,
                                                                     &ref_price);

+ 36 - 43
src/strategy.rs

@@ -5,12 +5,14 @@ use std::collections::VecDeque;
 use std::ops::{Div, Mul};
 use std::str::FromStr;
 use chrono::Utc;
+use futures_util::StreamExt;
 use rust_decimal::Decimal;
 use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
 use tracing::{error, info, warn};
 use tokio::time::Instant;
 use crate::params::Params;
 use crate::model::{LocalPosition, OrderCommand, OrderInfo};
+use crate::utils;
 use crate::utils::{clip, fix_amount, fix_price, generate_client_id, get_limit_order_requests_num_per_second, get_limit_requests_num_per_second};
 
 #[derive(Debug)]
@@ -73,6 +75,9 @@ pub struct Strategy {
     pub ref_price: Decimal,                                         //
     pub ref_bp: Decimal,                                            //
     pub ref_ap: Decimal,                                            //
+    pub ref_bv: Decimal,
+    pub ref_av: Decimal,
+
     pub step_size: Decimal,                                         // 原文的stepSize
     pub tick_size: Decimal,                                         // 原文的tickSize
 
@@ -220,6 +225,8 @@ impl Strategy {
             ref_price: Default::default(),
             ref_bp: Default::default(),
             ref_ap: Default::default(),
+            ref_bv: Default::default(),
+            ref_av: Default::default(),
             step_size: Decimal::new(1, 10),
             tick_size: Decimal::new(1, 10),
             max_pos_rate: Default::default(),
@@ -287,7 +294,6 @@ impl Strategy {
     // 更新当前strategy的各类信息
     pub fn _update_data(&mut self,
                         local_position: &LocalPosition,
-                        agg_market: &Vec<Decimal>,
                         local_cash: &Decimal,
                         local_coin: &Decimal,
                         ref_price: &Vec<Vec<Decimal>>) -> bool {
@@ -303,8 +309,8 @@ impl Strategy {
         // debug!(?self.pos);
 
         // 价格值处理
-        self.bp = agg_market[crate::public_params::BID_PRICE_INDEX];
-        self.ap = agg_market[crate::public_params::ASK_PRICE_INDEX];
+        self.bp = ref_price[self.ref_index][0];
+        self.ap = ref_price[self.ref_index][1];
         self.mp = (self.bp + self.ap) * Decimal::from_str("0.5").unwrap();
         // 中间价的ema值处理
         if self.mp_ema.eq(&Decimal::ZERO) {
@@ -339,12 +345,12 @@ impl Strategy {
             self.ref_ap = self.ap;
             self.ref_price = self.mp;
         } else {
-            self.ref_bp = ref_price[self.ref_index][0];
-            self.ref_ap = ref_price[self.ref_index][1];
-            let bv = ref_price[self.ref_index][2];
-            let av = ref_price[self.ref_index][3];
+            self.ref_bp = self.bp;
+            self.ref_ap = self.ap;
+            self.ref_bv = ref_price[self.ref_index][2];
+            self.ref_av = ref_price[self.ref_index][3];
             // 微价格(加权中间价)作为基价 S = (ap*bv+bp*av)/(av+bv)
-            self.ref_price = (self.ref_ap * bv + self.ref_bp * av) / (av + bv);
+            self.ref_price = (self.ref_ap * self.ref_bv + self.ref_bp * self.ref_av) / (self.ref_av + self.ref_bv);
             // self.ref_price = (self.ref_bp + self.ref_ap) * dec!(0.5);
         }
         // debug!(?self.ref_bp, ?self.ref_ap, %self.ref_price);
@@ -741,14 +747,12 @@ impl Strategy {
     pub fn on_exit(&mut self,
                    local_orders: &HashMap<String, OrderInfo>,
                    local_position: &LocalPosition,
-                   agg_market: &Vec<Decimal>,
                    local_cash: &Decimal,
                    local_coin: &Decimal,
                    ref_price: &Vec<Vec<Decimal>>) -> OrderCommand {
         let mut command = OrderCommand::new();
 
         if self._update_data(local_position,
-                             agg_market,
                              local_cash,
                              local_coin,
                              ref_price) {
@@ -774,14 +778,12 @@ impl Strategy {
     pub fn on_sleep(&mut self,
                     local_orders: &HashMap<String, OrderInfo>,
                     local_position: &LocalPosition,
-                    agg_market: &Vec<Decimal>,
                     local_cash: &Decimal,
                     local_coin: &Decimal,
                     ref_price: &Vec<Vec<Decimal>>) -> OrderCommand {
         let mut command = OrderCommand::new();
 
         if self._update_data(local_position,
-                             agg_market,
                              local_cash,
                              local_coin,
                              ref_price) {
@@ -886,7 +888,7 @@ impl Strategy {
             info!("策略预热完毕,可以执行后续逻辑!")
         }
 
-        return false;
+        false
     }
 
     // 接近整点时刻 不允许报单 防止下单bug
@@ -1270,7 +1272,6 @@ impl Strategy {
     pub fn on_tick(&mut self,
                    local_orders: &HashMap<String, OrderInfo>,
                    local_position: &LocalPosition,
-                   agg_market: &Vec<Decimal>,
                    local_cash: &Decimal,
                    local_coin: &Decimal,
                    ref_price: &Vec<Vec<Decimal>>,
@@ -1282,7 +1283,6 @@ impl Strategy {
 
         // 更新逻辑数据出错时,不进行后面的逻辑处理
         if !self._update_data(local_position,
-                              agg_market,
                               local_cash,
                               local_coin,
                               ref_price) {
@@ -1318,18 +1318,13 @@ impl Strategy {
         if command.limits_open.len() != 0 {
             self.prev_place_order_timestamp = Utc::now().timestamp_millis();
         }
+        // 数据录入
+        self.processor();
         command
     }
 
 
-    async fn processor(&mut self) {
-        self.update_t_diff();
-        self.update_sigma_square();
-        self.update_gamma();
-        self.update_kappa();
-        self.update_delta();
-        self.update_optimal_ask_and_bid();
-
+    fn processor(&mut self) {
         self.check_ready();
         if !self.is_ready {
             return;
@@ -1345,28 +1340,26 @@ impl Strategy {
 
         // let cci_arc = self.cci_arc.clone();
         let now = Decimal::from_i64(Utc::now().timestamp_millis()).unwrap();
-        let mid_price = self.mid_price;
-        let ask_price = self.ask_price;
-        let bid_price = self.bid_price;
-        let last_price = self.last_price;
-
-        let spread = self.mid_price;
-        let spread_max = self.optimal_ask_price;
-        let spread_min = self.optimal_bid_price;
-        // let spread = self.price_times_avg;
-        // let spread_max = self.fair_price_vec[1] / self.fair_price_vec[0];
-        // let spread_min = self.fair_price / self.mid_price;
-
-        let optimal_ask_price = self.optimal_ask_price;
-        let optimal_bid_price = self.optimal_bid_price;
-
-        let inventory = self.inventory;
-        let sigma_square = if self.is_regressed { Decimal::ONE } else { Decimal::ZERO };
-        let gamma = now - self.last_update_time;
-        let kappa = self.fair_price / self.mid_price;
+        let mid_price = self.mp;
+        let ask_price = self.ref_ap;
+        let bid_price = self.ref_bp;
+        let last_price = Decimal::ZERO;
+
+        let spread = self.ref_price;
+        let spread_max = self.open_dist[2];
+        let spread_min = self.open_dist[0];
+
+
+        let optimal_ask_price = self.open_dist[2];
+        let optimal_bid_price = self.open_dist[0];
+
+        let inventory = Decimal::ZERO;
+        let sigma_square = Decimal::ZERO;
+        let gamma = Decimal::ZERO;
+        let kappa = Decimal::ZERO;
 
         let flow_ratio = Decimal::ZERO;
-        let ref_price = self.fair_price;
+        let ref_price = self.ref_price;
 
         let need_append = now - self.prev_insert_time > Decimal::ONE_HUNDRED;
         if !need_append {

+ 24 - 26
src/trace_stack.rs

@@ -1,9 +1,7 @@
 use std::fmt;
 use std::fmt::{Formatter};
-use chrono::Utc;
 use rust_decimal::prelude::ToPrimitive;
 use tokio::time::Instant;
-use tracing::info;
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct TraceStack {
@@ -44,30 +42,30 @@ impl TraceStack {
         }
     }
 
-    pub fn show_delay(ins: &Instant) {
-        pub static mut COUNT: u128 = 0u128;
-        pub static mut SUM_DELAY: u128 = 0u128;
-        pub static mut PREV_LOG_TIMESTAMP: i64 = 0;
-
-        unsafe {
-            let delay = ins.elapsed().as_nanos();
-            COUNT += 1;
-            SUM_DELAY += delay;
-
-            // 30s打印一次
-            let now = Utc::now().timestamp_millis();
-            if now - PREV_LOG_TIMESTAMP > 30 * 1000 {
-                PREV_LOG_TIMESTAMP = now;
-                info!("数据{}条, avg={}ns", COUNT, SUM_DELAY / COUNT);
-            }
-
-            // 总延迟满3亿ns清理一次
-            if SUM_DELAY > 300_000_000 {
-                COUNT = 0;
-                SUM_DELAY = 0;
-            }
-        }
-    }
+    // pub fn show_delay(ins: &Instant) {
+    //     pub static mut COUNT: u128 = 0u128;
+    //     pub static mut SUM_DELAY: u128 = 0u128;
+    //     pub static mut PREV_LOG_TIMESTAMP: i64 = 0;
+    //
+    //     unsafe {
+    //         let delay = ins.elapsed().as_nanos();
+    //         COUNT += 1;
+    //         SUM_DELAY += delay;
+    //
+    //         // 30s打印一次
+    //         let now = Utc::now().timestamp_millis();
+    //         if now - PREV_LOG_TIMESTAMP > 30 * 1000 {
+    //             PREV_LOG_TIMESTAMP = now;
+    //             info!("数据{}条, avg={}ns", COUNT, SUM_DELAY / COUNT);
+    //         }
+    //
+    //         // 总延迟满3亿ns清理一次
+    //         if SUM_DELAY > 300_000_000 {
+    //             COUNT = 0;
+    //             SUM_DELAY = 0;
+    //         }
+    //     }
+    // }
 
     pub fn on_before_network(&mut self, before_network_millis: i64) {
         self.before_network = before_network_millis;

+ 2 - 109
src/utils.rs

@@ -553,117 +553,10 @@ pub fn build_html_file(data_c: &Vec<VecDeque<Option<Decimal>>>) -> String {
 
 #[cfg(test)]
 mod tests {
-    use chrono::Utc;
-    use rust_decimal::Decimal;
-    use rust_decimal_macros::dec;
-    use tracing::log::trace;
-    use crate::exchange::ExchangeEnum;
-    use crate::proxy;
-    use crate::utils::{clip, fix_amount, fix_price, generate_client_id};
-
-    #[test]
-    fn clip_test() {
-        let num = dec!(11);
-        let num2 = dec!(2);
-
-        let lower_limit = dec!(3);
-        let upper_limit = dec!(6);
-
-        println!("mum: {}", clip(num, lower_limit, upper_limit));
-        println!("mum2: {}", clip(num, lower_limit, upper_limit));
-    }
-
-    #[test]
-    fn generate_client_id_test() {
-        println!("{}", generate_client_id(None));
-        println!("{}", generate_client_id(Some("binance".to_string())));
-    }
-
-    #[test]
-    fn fix_amount_test() {
-        println!("{}", fix_amount(dec!(0.9), dec!(0.04)));
-        println!("{}", fix_amount(dec!(1.0), dec!(0.1)));
-        println!("{}", fix_amount(dec!(0.9), dec!(0.05)));
-        println!("{}", fix_amount(dec!(1), dec!(0.1)));
-        println!("{}", fix_amount(dec!(0.01), dec!(0.05)));
-    }
-
-    #[test]
-    fn fix_price_test() {
-        println!("{}", fix_price(dec!(1), dec!(0.1)));
-        println!("{}", fix_price(dec!(0.9), dec!(2.0)));
-        println!("{}", fix_price(dec!(1.1), dec!(0.1)));
-        println!("{}", fix_price(dec!(1.2), dec!(0.5)));
-        println!("{}", fix_price(dec!(4999.99), dec!(0.5)));
-    }
-
-    #[test]
-    fn utc_timestamp_test() {
-        let now = Utc::now();
-
-        println!("timestamp: {}", now.timestamp());
-        println!("timestamp_millis: {}", now.timestamp_millis());
-        println!("timestamp_micros: {}", now.timestamp_micros());
-        println!("timestamp_nanos: {}", now.timestamp_nanos_opt().unwrap());
-    }
-
-
-
-    // standard utils
-    /// 修改交易对连接符号
-    /// - `symbol(str)`: 交易对, "BTC_USDT", 默认以下划线传递
-    /// - `pat(str)`: 替换字符, "-", 把 “_” 替换为 "-"
-    pub fn format_symbol(symbol: String, pat: &str) -> String {
-        return symbol.to_uppercase().replace("_", pat);
-    }
-
-    // 检测是否走代理
-    pub fn proxy_handle() {
-        if proxy::ParsingDetail::http_enable_proxy() {
-            trace!("检测有代理配置,配置走代理");
-        }
-    }
-
-    /// 币种映射器
-    #[allow(dead_code)]
-    pub fn symbol_enter_mapper(exchange_enum: ExchangeEnum, symbol: &str) -> String {
-        let symbol_upper = symbol.to_uppercase();
-        match exchange_enum {
-            // ExchangeEnum::KucoinSwap => {
-            //     if symbol_upper.contains("BTC") {
-            //         symbol_upper.replace("BTC", "XBT")
-            //     } else { symbol_upper.to_string() }
-            // }
-            _ => {
-                symbol_upper.to_string()
-            }
-        }
-    }
-
-    // 截取指定精度的decimal(不会四舍五入)
-    pub fn truncate_decimal(amount: Decimal, precision: u32) -> Decimal {
-        let scale = Decimal::new(10i64.pow(precision), 0);
-        (amount * scale).trunc() / scale
-    }
-
-    // 获取指定精度下的tick_size
-    pub fn get_tick_size(precision: u32) -> Decimal {
-        return Decimal::new(1, 0) / Decimal::new(10i64.pow(precision), 0);
-    }
-
     /// 币种映射器
     #[allow(dead_code)]
-    pub fn symbol_out_mapper(exchange_enum: ExchangeEnum, symbol: &str) -> String {
+    pub fn symbol_out_mapper(symbol: &str) -> String {
         let symbol_upper = symbol.to_uppercase();
-        match exchange_enum {
-            // ExchangeEnum::KucoinSwap => {
-            //     if symbol_upper.contains("XBT") {
-            //         symbol_upper.replace("XBT", "BTC")
-            //     } else { symbol_upper.to_string() }
-            // }
-            _ => {
-                symbol_upper.to_string()
-            }
-        }
+        symbol_upper.to_string()
     }
 }