Parcourir la source

线性拟合v1

skyffire il y a 9 mois
Parent
commit
9c67bb5735
2 fichiers modifiés avec 72 ajouts et 44 suppressions
  1. 71 43
      strategy/src/predictor.rs
  2. 1 1
      strategy/src/strategy.rs

+ 71 - 43
strategy/src/predictor.rs

@@ -23,6 +23,8 @@ pub struct Predictor {
     pub trade_233_vec: FixedTimeRangeDeque<Trade>,
     pub trade_0_vec: FixedTimeRangeDeque<Trade>,
 
+    pub prices: Vec<Vec<VecDeque<Decimal>>>,                                    // [[[做市所], [参考所0]], ...]
+
     pub mid_price: Decimal,                                                     // 中间价
     pub fair_price: Decimal,
     pub ask_price: Decimal,                                                     // 卖一价
@@ -38,12 +40,9 @@ pub struct Predictor {
     pub balance: Decimal,                                                       // 初始余额
     pub prev_balance: Decimal,
 
-    pub signal: Decimal,                                                        // 大于0代表此时是正向信号,小于0则相反
-
     pub ask_delta: Decimal,                                                     // δa
     pub bid_delta: Decimal,                                                     // δb
 
-    pub fair_price_vec: Vec<Decimal>,                                           // 公平价格列表
     pub fair_price_std_vec: Vec<Decimal>,                                       // 公平价格列表,标准化之后的
     pub price_avg_times_vec: Vec<Decimal>,                                      // 公平所与做市所的价格倍率的平均值
     pub price_avg_times_long_vec: Vec<Decimal>,                                 // 公平所与做市所的价格倍率的平均值
@@ -56,7 +55,7 @@ pub struct Predictor {
     pub prev_insert_time: Decimal,
     pub prev_save_time: Decimal,
     pub init_time: Decimal,
-    pub prev_update_open_params_time: Decimal,
+    pub nihe_time: Decimal,
 
     pub params: Params,
 
@@ -122,10 +121,11 @@ impl Predictor {
             // 接针版本
             depth_vec: vec![Depth::new(); params.ref_exchange.len()],
             fair_price_std_vec: vec![Decimal::ZERO; params.ref_exchange.len()],
-            fair_price_vec: vec![Decimal::ZERO; params.ref_exchange.len()],
             price_avg_times_vec: vec![Decimal::ZERO; params.ref_exchange.len()],
             price_avg_times_long_vec: vec![Decimal::ZERO; params.ref_exchange.len()],
 
+            prices: vec![vec![VecDeque::new(); 2]; params.ref_exchange.len()],
+
             record_vec: VecDeque::new(),
 
             trade_price_long_vec: FixedTimeRangeDeque::new(Self::TRADE_LONG_RANGE_MICROS),
@@ -151,8 +151,6 @@ impl Predictor {
             balance: Default::default(),
             prev_balance: Default::default(),
 
-            signal: Default::default(),
-
             last_update_time: Default::default(),
             last_index: Default::default(),
 
@@ -160,7 +158,7 @@ impl Predictor {
             prev_save_time: Decimal::from(Utc::now().timestamp_millis()),
             init_time: Decimal::from(Utc::now().timestamp_millis()),
 
-            prev_update_open_params_time: Default::default(),
+            nihe_time: Default::default(),
             params,
 
             debug_sender: tx,
@@ -266,36 +264,27 @@ impl Predictor {
 
         // 生成fp
         // self.fair_price_vec[index] = a1.price * b1.value / total + b1.price * a1.value / total;
-        self.fair_price_vec[index] = (a1.price + b1.price) / Decimal::TWO;
-        self.fair_price_vec[index].rescale(self.mid_price.scale());
+        let mut mp = (a1.price + b1.price) / Decimal::TWO;
+        mp.rescale(self.mid_price.scale());
 
-        // 求价格倍率
-        self.price_avg_times_vec[index] = if !self.is_ready {
-            self.fair_price_vec[index] / self.mid_price
-        } else {
-            self.price_avg_times_vec[index] * dec!(0.999) + dec!(0.001) * self.fair_price_vec[index] / self.mid_price
-        };
-        self.price_avg_times_long_vec[index] = if !self.is_ready {
-            self.fair_price_vec[index] / self.mid_price
-        } else {
-            self.price_avg_times_long_vec[index] * dec!(0.9995) + dec!(0.0005) * self.fair_price_vec[index] / self.mid_price
-        };
+        self.prices[index][0].push_back(self.mid_price);
+        self.prices[index][1].push_back(mp);
 
-        // 合成公平价格
-        self.fair_price_std_vec[index] = self.fair_price_vec[index] / self.price_avg_times_vec[index];
+        // 长度限制
+        if self.prices[index][0].len() > 10000 {
+            self.prices[index][0].pop_front();
+            self.prices[index][1].pop_front();
+        }
 
-        // 开仓信号处理
-        self.signal = Decimal::ZERO;
-        for (i, price_avg_times_long) in self.price_avg_times_long_vec.iter().enumerate() {
-            if price_avg_times_long.is_zero() {
-                return;
-            }
-            let price_avg_times_short = self.price_avg_times_vec[i];
+        // 拟合
+        let prev = Utc::now().timestamp_millis();
+        if let Some((k, b)) = self.linear_least_squares(index).await {
+            self.fair_price_std_vec[index] = k * mp + b;
 
-            self.signal = self.signal + price_avg_times_short - price_avg_times_long;
+            self.nihe_time = Decimal::from(Utc::now().timestamp_millis() - prev);
+        } else {
+            return;
         }
-        // self.signal = self.signal / self.params.min_spread;
-        // self.signal.rescale(0);
 
         // 生成最终用于挂单的公平价格
         let fair_price_sum: Decimal = self.fair_price_std_vec.iter().sum();
@@ -324,12 +313,6 @@ impl Predictor {
             return;
         }
 
-        for fair_price in &self.fair_price_vec {
-            if fair_price.is_zero() {
-                return;
-            }
-        }
-
         let is_close_long = self.inventory > Decimal::ZERO;
         let is_close_short = self.inventory < Decimal::ZERO;
 
@@ -350,13 +333,13 @@ impl Predictor {
                 self.bid_delta = dec!(0);
                 self.ask_delta = dec!(-2);
 
-                self.optimal_bid_price = self.fair_price - self.fair_price * (self.params.open - self.signal);
+                self.optimal_bid_price = self.fair_price - self.fair_price * self.params.open;
                 self.optimal_ask_price = Self::DONT_VIEW;
             } else if self.fair_price < self.mid_price {
                 self.ask_delta = dec!(0);
                 self.bid_delta = dec!(-2);
 
-                self.optimal_ask_price = self.fair_price + self.fair_price * (self.params.open + self.signal);
+                self.optimal_ask_price = self.fair_price + self.fair_price * self.params.open;
                 self.optimal_bid_price = Self::DONT_VIEW;
             } else {
                 self.bid_delta = dec!(0);
@@ -380,7 +363,7 @@ impl Predictor {
            return;
         }
 
-        for fair_price in &self.fair_price_vec {
+        for fair_price in &self.fair_price_std_vec {
             if fair_price.is_zero() {
                 return;
             }
@@ -402,6 +385,51 @@ impl Predictor {
         info!("========================================行情数据预热完毕==================================")
     }
 
+    // 最小二乘法拟合函数,支持VecDeque
+    pub async fn linear_least_squares(&mut self, index: usize) -> Option<(Decimal, Decimal)> {
+        let x = &self.prices[index][1];
+        let y = &self.prices[index][0];
+
+        // 检查数组长度是否相同
+        if x.len() != y.len() {
+            return None;
+        }
+        let n = x.len();
+        if n == 0 {
+            return None;
+        }
+
+        let mut sum_x = Decimal::zero();
+        let mut sum_y = Decimal::zero();
+        let mut sum_xx = Decimal::zero();
+        let mut sum_xy = Decimal::zero();
+
+        // 遍历VecDeque中的元素
+        for (xi, yi) in x.iter().zip(y.iter()) {
+            sum_x += xi;
+            sum_y += yi;
+            let xi_sq = xi * xi;
+            sum_xx += xi_sq;
+            sum_xy += xi * yi;
+        }
+
+        // 计算分子和分母
+        let numerator = sum_xy - (sum_x * sum_y) / Decimal::from(n);
+        let denominator = sum_xx - (sum_x * sum_x) / Decimal::from(n);
+
+        // 如果分母为0,返回None
+        if denominator == Decimal::zero() {
+            return None;
+        }
+
+        let k = numerator / denominator;
+        let mean_x = sum_x / Decimal::from(n);
+        let mean_y = sum_y / Decimal::from(n);
+        let b = mean_y - k * mean_x;
+
+        Some((k, b))
+    }
+
     // #[instrument(skip(self), level="TRACE")]
     async fn processor(&mut self, data_time: Decimal, is_hard_update: bool) {
         self.check_ready();
@@ -448,7 +476,7 @@ impl Predictor {
         };
 
         let gamma = self.balance;
-        let kappa = Decimal::from(Utc::now().timestamp_millis()) - data_time;
+        let kappa = self.nihe_time;
 
         let flow_ratio = Decimal::ZERO;
 

+ 1 - 1
strategy/src/strategy.rs

@@ -1091,7 +1091,7 @@ impl Strategy {
 
         self._cancel_open(&mut command, local_orders, predictor);   // 撤单命令处理
         self._post_close(&mut command, local_orders, predictor);    // 平仓单命令处理
-        self._post_open(&mut command, local_orders, predictor);     // 限价单命令处理
+        // self._post_open(&mut command, local_orders, predictor);     // 限价单命令处理
         self._check_local_orders(&mut command, local_orders);       // 固定时间检查超时订单
         self._update_in_cancel(&mut command, local_orders);         // 更新撤单队列,是一个filter
         self._check_request_limit(&mut command);                    // 限制频率,移除不合规则之订单,是一个filter