Browse Source

市价风控完成(gate)

JiahengHe 1 năm trước cách đây
mục cha
commit
06466d343d
3 tập tin đã thay đổi với 68 bổ sung4 xóa
  1. 27 0
      src/core_libs.rs
  2. 41 3
      strategy/src/core.rs
  3. 0 1
      strategy/src/strategy.rs

+ 27 - 0
src/core_libs.rs

@@ -7,6 +7,7 @@ use std::sync::Arc;
 use std::sync::atomic::{AtomicBool};
 use std::time::Duration;
 use chrono::Utc;
+use rust_decimal::Decimal;
 use tokio::sync::{mpsc, Mutex};
 use tokio::time::Instant;
 use tracing::{error, info};
@@ -105,6 +106,32 @@ pub async fn init(params: Params,
             }
         }
     });
+    // 市价数据更新(市价风控)
+    let markt_price_core_arc = core_arc.clone();
+    tokio::spawn(async move {
+        info!("市价风控数据更新启动...");
+        loop {
+            tokio::time::sleep(Duration::from_millis(100)).await;
+
+            let mut core = markt_price_core_arc.lock().await;
+            // 有仓位时检测
+            if core.local_position.long_pos > Decimal::ZERO || core.local_position.short_pos > Decimal::ZERO{
+                let positions = core.platform_rest.get_position().await;
+                match positions {
+                    Ok(pos) => {
+                        let total_price: Decimal = pos.iter()
+                            .map(|p| &p.profit)
+                            .sum();
+                        core.update_equity_profit_including_unrealized(total_price).await;
+                    },
+                    Err(err) => {
+                        error!("市价风控数据获取异常 {}", err);
+                    }
+                }
+            }
+        }
+    });
+
 
     let _error_handler_core_arc = core_arc.clone();
     tokio::spawn(async move {

+ 41 - 3
strategy/src/core.rs

@@ -53,8 +53,10 @@ pub struct Core {
     pub handled_orders_cid: Vec<String>,
     // 本地利润值
     pub local_profit: Decimal,
-    // 本地利润值(包含未实现盈亏)
-    pub local_profit_including_unrealized: Decimal,
+    // 本地U值(包含未实现盈亏)
+    pub local_cash_including_unrealized: Decimal,
+    // 本地U值(包含未实现盈亏)
+    pub max_local_cash_including_unrealized: Decimal,
     // 本地U保证金
     pub local_cash: Decimal,
     // 本地币保证金
@@ -143,6 +145,8 @@ impl Core {
             local_orders_backup_cid: Default::default(),
             handled_orders_cid: Default::default(),
             local_profit: Default::default(),
+            local_cash_including_unrealized: Default::default(),
+            max_local_cash_including_unrealized: Default::default(),
             local_cash: Default::default(),
             local_coin: Default::default(),
             local_position: LocalPosition {
@@ -944,6 +948,17 @@ impl Core {
             }
         }
     }
+    // 更新本地值(市场价)
+    pub async fn update_equity_profit_including_unrealized(&mut self, profit:Decimal){
+        self.local_cash_including_unrealized = self.local_cash + profit;
+        if self.local_cash_including_unrealized > self.max_local_cash_including_unrealized{
+            self.max_local_cash_including_unrealized = self.local_cash_including_unrealized.clone();
+        }
+    }
+
+    pub async fn check_market_price_risk(&mut self){
+
+    }
 
     // #[instrument(skip(self), level="TRACE")]
     pub async fn check_risk(&mut self) {
@@ -960,6 +975,27 @@ impl Core {
             return;
         }
 
+        // 不是现货执行的回撤风控0
+        if !self.exchange.contains("spot") {  // 市场价盈亏风控
+            let draw_back = Decimal::ONE - self.local_cash_including_unrealized / self.max_local_cash_including_unrealized;
+
+            if draw_back > self.stop_loss {
+                let exit_msg = format!("{} 总资金吊灯回撤(市价风控) {}。当前值:{}, 最高净值{},触发止损,准备停机。",
+                                       self.params.account_name, draw_back, self.local_cash_including_unrealized, self.max_local_cash_including_unrealized);
+                warn!(exit_msg);
+                self.exit_msg = exit_msg;
+                self.stop().await;
+            }
+        }
+        // // 市场价盈亏风控
+        let draw_back = self.local_cash_including_unrealized / self.strategy.start_equity;
+        if draw_back < -self.stop_loss {
+            let exit_msg = format!("{} 交易亏损,触发止损,准备停机(市价风控)。", self.params.account_name);
+            warn!(exit_msg);
+            self.exit_msg = exit_msg;
+            self.stop().await;
+        }
+
         // 不是现货执行的回撤风控1
         if !self.exchange.contains("spot") {
             let draw_back = Decimal::ONE - self.strategy.equity / self.strategy.max_equity;
@@ -1536,7 +1572,7 @@ impl Core {
         let short_one_hand_value: Decimal;
         let long_one_hand_amount: Decimal = (long_one_hand_value / mp / &self.strategy.step_size).floor() * self.strategy.step_size;
         let short_one_hand_amount: Decimal;
-
+        info!("mp {}", mp);
         if self.exchange.contains("spot") {
             short_one_hand_value = start_coin * mp * self.params.lever_rate / grid;
             short_one_hand_amount = (short_one_hand_value / mp / self.strategy.step_size).floor() * self.strategy.step_size;
@@ -1556,6 +1592,8 @@ impl Core {
         }
         // 初始化调度器
         self.local_cash = start_cash;
+        self.local_cash_including_unrealized = start_cash;
+        self.max_local_cash_including_unrealized = start_cash;
         self.local_coin = start_coin;
 
         // 买入平台币

+ 0 - 1
strategy/src/strategy.rs

@@ -61,7 +61,6 @@ pub struct Strategy {
     pub start_coin: Decimal,                                        //
     pub start_cash: Decimal,                                        //
     pub max_equity: Decimal,                                        // 最大净值
-    pub max_equity_including_unrealized: Decimal,                   // 最大净值(包含未实现盈亏)
     pub local_profit: Decimal,                                      //
     pub total_amount: Decimal,                                      //
     pub is_ready: bool,                                             // 程序是否已经准备好,ready