Browse Source

预定价格挂单

JiahengHe 1 year ago
parent
commit
0cacefa581

+ 9 - 0
config.toml.sample

@@ -40,3 +40,12 @@ colo = 0
 log_level = "info"
 # 中控端口
 port = 6000
+
+// 最大价差(价差区间结束值)
+max_spread = 0.0005
+// 最小价差(价差区间开始值)
+min_spread = 0.0001
+// 取价列表的最大长度
+rl_num = 30
+// 不用设置,暂时没用
+max_position_value = 20

+ 2 - 1
global/src/params.rs

@@ -53,7 +53,8 @@ pub struct Params {
     pub max_spread: Decimal,
     pub min_spread: Decimal,
     pub rl_num: Decimal,
-    pub max_position_value: Decimal
+    pub max_position_value: Decimal,
+    pub ira: Decimal
 }
 
 impl Params {

+ 1 - 0
strategy/Cargo.toml

@@ -20,6 +20,7 @@ standard = { path = "../standard" }
 global = { path = "../global" }
 exchanges = { path = "../exchanges" }
 ndarray = "0.15.6"
+argmin = "0.7"
 
 futures-util = { version = "0.3.28", default-features = false, features = ["sink", "std"] }
 futures-channel = "0.3.28"

+ 0 - 2
strategy/src/instant_volatility_indicator.rs

@@ -7,7 +7,6 @@ use crate::ring_buffer::RingBuffer;
 pub struct InstantVolatilityIndicator {
     sampling_buffer: RingBuffer,
     processing_buffer: RingBuffer,
-    samples_length: usize
 }
 
 impl InstantVolatilityIndicator {
@@ -15,7 +14,6 @@ impl InstantVolatilityIndicator {
         InstantVolatilityIndicator{
             sampling_buffer: RingBuffer::new(sampling_length),
             processing_buffer: RingBuffer::new(processing_length),
-            samples_length: 0,
         }
     }
 

+ 1 - 2
strategy/src/lib.rs

@@ -13,5 +13,4 @@ mod kucoin_spot;
 mod bitget_spot;
 mod predictor_new;
 mod instant_volatility_indicator;
-mod ring_buffer;
-mod memoized_func;
+mod ring_buffer;

+ 0 - 37
strategy/src/memoized_func.rs

@@ -1,37 +0,0 @@
-use std::cell::RefCell;
-use std::rc::Rc;
-use rust_decimal::Decimal;
-
-type Func = Rc<dyn Fn(Decimal, Decimal) -> Vec<Decimal>>;
-
-pub struct MemoizedFunc {
-    func: Func,
-    last_a: Decimal,
-    last_b: Decimal,
-    last_val: Vec<Decimal>
-}
-
-impl MemoizedFunc {
-    pub(crate) fn new(func: Func) -> Self {
-        MemoizedFunc {
-            func,
-            last_a: Decimal::ZERO,
-            last_b: Decimal::ZERO,
-            last_val: Vec::new()
-        }
-    }
-
-    pub fn call(&mut self, a: Decimal, b: Decimal) -> Vec<Decimal> {
-        if self.last_a == a  && self.last_b == b{
-            return self.last_val.clone();
-        }
-
-        let val = (self.func)(a.clone(), b.clone());
-
-        self.last_a = a;
-        self.last_b = b;
-        self.last_val = val.clone();
-
-        val
-    }
-}

+ 35 - 21
strategy/src/predictor_new.rs

@@ -1,10 +1,8 @@
 
 use rust_decimal::prelude::*;
 use rust_decimal_macros::dec;
-use tracing::{debug, info};
-use tracing::field::debug;
+use tracing::{debug};
 use global::public_params;
-use standard::Ticker;
 use crate::instant_volatility_indicator::InstantVolatilityIndicator;
 
 #[derive(Debug)]
@@ -26,6 +24,7 @@ pub struct PredictorNew {
     pub max_spread: Decimal,                                                // 最大点差
     pub min_spread: Decimal,                                                // 最小点差
     pub rl_num: Decimal,                                                    // 取价坐标
+    pub ira: Decimal,                                                       // 取值坐标
     pub max_position_value: Decimal,                                         // 最大持仓(u)
 
     pub vol: InstantVolatilityIndicator                                     // 波动率计算类
@@ -36,7 +35,7 @@ pub struct PredictorNew {
     下面的单元测试有使用示例
 */
 impl PredictorNew {
-    pub fn new(ref_exchange_length: usize, max_spread: Decimal, min_spread: Decimal, rl_num: Decimal, max_position_value: Decimal) -> Self {
+    pub fn new(ref_exchange_length: usize, max_spread: Decimal, min_spread: Decimal, rl_num: Decimal, max_position_value: Decimal, ira: Decimal) -> Self {
         Self {
             loop_count: 0,
             market_info_list: vec![],
@@ -53,6 +52,7 @@ impl PredictorNew {
             variance: Decimal::ZERO,
             balance_value: Decimal::ZERO,
             rl_num,
+            ira,
             max_position_value,
             vol: InstantVolatilityIndicator::new(30, 15)
         }
@@ -76,8 +76,8 @@ impl PredictorNew {
         let bid_price = last_market_info[public_params::BID_PRICE_INDEX];
         let ask_price = last_market_info[public_params::ASK_PRICE_INDEX];
         let mid_price = (bid_price + ask_price) * dec!(0.5);
-        debug!(?last_market_info);
-        debug!(?bid_price, ?ask_price, ?mid_price);
+        // debug!(?last_market_info);
+        // debug!(?bid_price, ?ask_price, ?mid_price);
         self.mid_price_list.push(mid_price.clone());
         self.transaction_prices.push(mid_price);
         // 更新参考ref_mid_price
@@ -111,6 +111,10 @@ impl PredictorNew {
         //     gamma = 0.9f64;
         // }
         let len = self.transaction_prices.len();
+        if len < 3usize {
+            return;
+        }
+        // info!(?self.transaction_prices);
         let rtn: Decimal = (self.transaction_prices[len - 1] / self.transaction_prices[len - 2]).ln();
         let result: Decimal = gamma * rtn.powi(2) + (Decimal::ONE - gamma) * self.variance;
         self.variance = result.sqrt().unwrap();
@@ -119,7 +123,7 @@ impl PredictorNew {
     /**
        计算gamma值
     **/
-    pub fn calc_gamma(&mut self, ira: Decimal, variance: Decimal) -> Decimal {
+    pub fn calc_gamma(&mut self, ira: Decimal, variance: &Decimal) -> Decimal {
         self.max_spread / Decimal::TWO * self.balance_value * variance.powi(2) * ira
     }
 
@@ -133,16 +137,16 @@ impl PredictorNew {
     /**
        计算预定价格
     **/
-    pub fn calc_rp(&mut self, gamma: &Decimal) -> Decimal{
+    pub fn calc_rp(&mut self, gamma: &Decimal, std: &Decimal) -> Decimal{
         let last_market_info = self.market_info_list.last().unwrap();
         let ref_bid_price = last_market_info[public_params::LENGTH+public_params::BID_PRICE_INDEX];
         let ref_ask_price = last_market_info[public_params::LENGTH+public_params::ASK_PRICE_INDEX];
         let ref_mid_price = (ref_bid_price + ref_ask_price) * dec!(0.5);
-        ref_mid_price - self.balance_value * gamma * self.variance * self.variance
+        ref_mid_price - self.balance_value * gamma * std * std
     }
 
-    pub fn calc_dk(&mut self, gamma: &Decimal) -> Decimal {
-        return ((self.max_spread + self.min_spread)/Decimal::TWO * gamma - self.variance * self.variance * gamma * gamma) / Decimal::TWO;
+    pub fn calc_dk(&mut self, gamma: &Decimal, std: &Decimal) -> Decimal {
+        return ((self.max_spread + self.min_spread)/Decimal::TWO * gamma - std * std * gamma * gamma) / Decimal::TWO;
     }
 
     pub fn calc_kappa(&mut self, gamma: &Decimal, dk: Decimal, deviation_range: Decimal) -> Decimal {
@@ -153,8 +157,8 @@ impl PredictorNew {
     /**
         计算价差
     **/
-    pub fn calc_theta(&mut self, gamma: Decimal, kappa: Decimal) -> Decimal {
-        let a = gamma * self.variance * self.variance;
+    pub fn calc_theta(&mut self, gamma: Decimal, kappa: Decimal, std: &Decimal) -> Decimal {
+        let a = gamma * std * std;
         let ln = (Decimal::ONE + gamma / kappa).ln();
         let b = Decimal::TWO / gamma * ln;
         (a + b) / Decimal::TWO
@@ -205,7 +209,7 @@ impl PredictorNew {
 
     // 市场信息处理器,也是python里的onTime方法
     pub fn market_info_handler(&mut self, new_market_info: &Vec<Decimal>) {
-        debug!(?new_market_info);
+        // debug!(?new_market_info);
         // 空数据不处理
         if new_market_info.len() == 0 {
             return;
@@ -245,19 +249,29 @@ impl PredictorNew {
     // }
     pub fn get_ref_price(&mut self) -> Vec<Vec<Decimal>>{
         let mut ref_price_list = Vec::new();
-        let std = self.variance;
+        let std = self.vol.processing_calculation();
         if std == Decimal::ZERO {
             return Vec::new();
         }
-        let ira = Decimal::from_str("5").unwrap();
+        let ira = self.ira;
         let dd = self.calc_deviation_range(ira.clone());
-        let gamma = self.calc_gamma(ira, std);
-        let rp = self.calc_rp(&gamma);
-        let dk = self.calc_dk(&gamma);
+        let gamma = self.calc_gamma(ira.clone(), &std);
+        let rp = self.calc_rp(&gamma, &std);
+        let dk = self.calc_dk(&gamma, &std);
         let kappa = self.calc_kappa(&gamma, dk, dd);
-        let theta = self.calc_theta(gamma, kappa);
+        let theta = self.calc_theta(gamma, kappa, &std);
         ref_price_list.push(vec![rp + theta , rp - theta]);
-        debug!(?ref_price_list);
+        // info!(?std, ?dd, ?gamma, ?rp, ?dk, ?kappa, ?theta, ?ref_price_list);
+
+        // let std2 = self.variance;
+        // let dd2 = self.calc_deviation_range(ira.clone());
+        // let gamma2 = self.calc_gamma(ira, &std2);
+        // let rp2 = self.calc_rp(&gamma, &std2);
+        // let dk2 = self.calc_dk(&gamma, &std2);
+        // let kappa2 = self.calc_kappa(&gamma, dk, dd);
+        // let theta2 = self.calc_theta(gamma, kappa, &std2);
+        // let x = vec![rp2 + theta2 , rp2 - theta2];
+        // info!(?std2, ?dd2, ?gamma2, ?rp2, ?dk2, ?kappa2, ?theta2, ?x);
         ref_price_list
     }
 }

+ 2 - 2
strategy/src/quant.rs

@@ -24,7 +24,6 @@ use standard::exchange::ExchangeEnum::{BinanceSpot, BinanceSwap, BitgetSpot, Gat
 use crate::instant_volatility_indicator::InstantVolatilityIndicator;
 
 use crate::model::{LocalPosition, OrderInfo, TokenParam, TraderMsg};
-use crate::predictor::Predictor;
 use crate::predictor_new::PredictorNew;
 use crate::strategy::Strategy;
 use crate::utils;
@@ -181,6 +180,7 @@ impl Quant {
                 max_spread: Default::default(),
                 min_spread: Default::default(),
                 rl_num: Default::default(),
+                ira: Default::default(),
                 max_position_value: Default::default(),
                 vol: InstantVolatilityIndicator::new(1, 1),
             },
@@ -269,7 +269,7 @@ impl Quant {
             }
         }
         info!("价格系数:{:?}", price_alpha);
-        quant_obj.predictor = PredictorNew::new(quant_obj.ref_name.len(), params.max_spread, params.min_spread, params.rl_num, params.max_position_value)
+        quant_obj.predictor = PredictorNew::new(quant_obj.ref_name.len(), params.max_spread, params.min_spread, params.rl_num, params.max_position_value, params.ira)
             .alpha(price_alpha)
             .gamma(params.gamma);
         // quant_obj.predictor = Predictor::new(quant_obj.ref_name.len())

+ 43 - 43
strategy/src/ring_buffer.rs

@@ -1,6 +1,5 @@
 use std::collections::VecDeque;
-use rust_decimal::{Decimal, MathematicalOps};
-use rust_decimal::prelude::{FromPrimitive};
+use rust_decimal::{Decimal};
 use tracing::info;
 
 /**
@@ -21,9 +20,9 @@ impl RingBuffer {
     }
 
     // 清空缓存
-    pub fn dealloc(&mut self){
-        self.buffer = VecDeque::with_capacity(self.length);
-    }
+    // pub fn dealloc(&mut self){
+    //     self.buffer = VecDeque::with_capacity(self.length);
+    // }
 
     pub fn process(&self){
         info!("行情收集进度:{} / {}", self.buffer.len(), self.length);
@@ -51,9 +50,9 @@ impl RingBuffer {
     }
 
     // 是否是空的
-    pub fn is_empty(&self) -> bool {
-        return self.buffer.len() == 0
-    }
+    // pub fn is_empty(&self) -> bool {
+    //     return self.buffer.len() == 0
+    // }
 
     // 是否已达到最大缓存长度
     pub fn is_full(&self) -> bool {
@@ -61,43 +60,44 @@ impl RingBuffer {
     }
 
     // 平均值
-    pub fn mean_value(&self) -> Decimal {
-        if self.is_full() {
-            let item_sum: Decimal = self.buffer.iter().sum();
-            return item_sum / Decimal::from_usize(self.length).unwrap();
-        }
-        Decimal::ZERO
-    }
-
-    // 获取标准差(标准差 = 方差 * 方差)
-    pub fn std_dev(&self) -> Decimal {
-        self.variance().sqrt().unwrap()
-    }
-
-    // 获取方差
-    pub fn variance(&self) -> Decimal {
-        let data_mean = self.mean_value();
-        let std_deviation = self.buffer.iter().map(|value| {
-            let diff = data_mean - value;
-            diff * diff
-        }).sum::<Decimal>() / Decimal::from_usize(self.length).unwrap();
-        std_deviation
-    }
+    // #[warn(dead_code)]
+    // fn mean_value(&self) -> Decimal {
+    //     if self.is_full() {
+    //         let item_sum: Decimal = self.buffer.iter().sum();
+    //         return item_sum / Decimal::from_usize(self.length).unwrap();
+    //     }
+    //     Decimal::ZERO
+    // }
+    //
+    // // 获取标准差(标准差 = 方差 * 方差)
+    // fn std_dev(&self) -> Decimal {
+    //     self.variance().sqrt().unwrap()
+    // }
+    //
+    // // 获取方差
+    // fn variance(&self) -> Decimal {
+    //     let data_mean = self.mean_value();
+    //     let std_deviation = self.buffer.iter().map(|value| {
+    //         let diff = data_mean - value;
+    //         diff * diff
+    //     }).sum::<Decimal>() / Decimal::from_usize(self.length).unwrap();
+    //     std_deviation
+    // }
 
     // 获取缓存长度
-    pub fn len(&self) -> usize {
-        self.buffer.len()
-    }
-
-    // 设置最大缓存长度
-    pub fn set_length(&mut self, new_length: usize) {
-        if new_length < self.length {
-            for _ in 0..(self.length - new_length) {
-                self.buffer.pop_front();
-            }
-        }
-        self.length = new_length;
-    }
+    // pub fn len(&self) -> usize {
+    //     self.buffer.len()
+    // }
+    //
+    // // 设置最大缓存长度
+    // pub fn set_length(&mut self, new_length: usize) {
+    //     if new_length < self.length {
+    //         for _ in 0..(self.length - new_length) {
+    //             self.buffer.pop_front();
+    //         }
+    //     }
+    //     self.length = new_length;
+    // }
 }
 
 #[cfg(test)]

+ 48 - 43
strategy/src/strategy.rs

@@ -1,7 +1,6 @@
 use std::cmp::{max, min};
 use std::collections::HashMap;
 use std::ops::{Div, Mul};
-use std::str::FromStr;
 use chrono::Utc;
 use rust_decimal::Decimal;
 use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
@@ -464,13 +463,13 @@ impl Strategy {
     // 生成各类挂单价格,原文是gen_dist
     #[instrument(skip(self), level="TRACE")]
     pub fn generate_dist(&mut self) {
-        let open = self.trade_open_dist;
+        // let open = self.trade_open_dist;
         let close = self.trade_close_dist;
-        let pos_rate = vec![self.long_hold_rate, self.short_hold_rate];
+        // let pos_rate = vec![self.long_hold_rate, self.short_hold_rate];
         let ref_bp = self.ref_bp;
         let ref_ap = self.ref_ap;
         let predict = self.predict;
-        let grid = self.grid;
+        // let grid = self.grid;
         let mode = self.maker_mode.clone();
 
         // let mut mp = (ref_bp + ref_ap) * dec!(0.5);
@@ -485,10 +484,10 @@ impl Strategy {
         // ];
 
         // 平仓相关
-        let mut mp = (ref_bp + ref_ap) * dec!(0.5);
+        let mp = (ref_bp + ref_ap) * dec!(0.5);
         let mut buy_start = mp;
         let mut sell_start = mp;
-        let mut avoid = min(dec!(0.0005), close * dec!(0.5));
+        let avoid = min(dec!(0.0005), close * dec!(0.5));
         let mut close_dist = vec![
             buy_start * (Decimal::ONE + predict - close + avoid),                    // buy upper
             buy_start * (Decimal::ONE + predict - close - avoid),                    // buy lower
@@ -504,9 +503,11 @@ impl Strategy {
         }
         // 跟随做市模式
         else if mode == "follow".to_string() {
-            mp = (ref_bp + ref_ap) * dec!(0.5);
-            buy_start = mp;
-            sell_start = mp;
+            // mp = (ref_bp + ref_ap) * dec!(0.5);
+            // buy_start = mp;
+            // sell_start = mp;
+            buy_start = ref_bp;
+            sell_start = ref_ap;
         } else {
             error!("未知做市类型:mode={}", mode);
             panic!("未知做市类型:mode={}", mode);
@@ -514,15 +515,19 @@ impl Strategy {
         // info!(?mode, ?buy_start, ?sell_start, ?mp);
 
         // 开仓相关
-        avoid = min(dec!(0.001), open * dec!(0.05));
-        // 持仓偏移
-        let buy_shift = Decimal::ONE + pos_rate[0] * grid;
-        let sell_shift = Decimal::ONE + pos_rate[1] * grid;
+        // avoid = min(dec!(0.001), open * dec!(0.05));
+        // // 持仓偏移
+        // let buy_shift = Decimal::ONE + pos_rate[0] * grid;
+        // let sell_shift = Decimal::ONE + pos_rate[1] * grid;
         let mut open_dist = vec![
-            buy_start * (Decimal::ONE + predict - open * buy_shift  + avoid),             // buy upper
-            buy_start * (Decimal::ONE + predict - open * buy_shift  - avoid),             // buy lower
-            sell_start * (Decimal::ONE + predict + open * sell_shift - avoid),            // sell lower
-            sell_start * (Decimal::ONE + predict + open * sell_shift + avoid),            // sell upper
+            // buy_start * (Decimal::ONE + predict - open * buy_shift  + avoid),             // buy upper
+            // buy_start * (Decimal::ONE + predict - open * buy_shift  - avoid),             // buy lower
+            // sell_start * (Decimal::ONE + predict + open * sell_shift - avoid),            // sell lower
+            // sell_start * (Decimal::ONE + predict + open * sell_shift + avoid),            // sell upper
+            buy_start,
+            buy_start,
+            sell_start,
+            sell_start
         ];
         // debug!(?avoid, ?buy_shift, ?sell_shift, ?avoid, ?open_dist);
 
@@ -974,19 +979,19 @@ impl Strategy {
                     command.limits_close.insert(order_client_id, order.clone());
 
                     // 定价止损平仓单
-                    let mut price_limit = self.pos.long_avg * Decimal::from_str("0.995").unwrap();
-                    price_limit = utils::fix_price(price_limit, self.tick_size);
-
-                    let order_client_limit_id = utils::generate_client_id(Some(self.broker_id.clone()));
-                    let order_limit = vec![
-                        self.pos.long_pos.to_string(),
-                        "pd".to_string(),
-                        price_limit.to_string(),
-                        order_client_limit_id.clone()
-                    ];
-
-                    command.limits_close.insert(order_client_limit_id, order_limit.clone());
-                    info!(?command);
+                    // let mut price_limit = self.pos.long_avg * Decimal::from_str("0.995").unwrap();
+                    // price_limit = utils::fix_price(price_limit, self.tick_size);
+                    //
+                    // let order_client_limit_id = utils::generate_client_id(Some(self.broker_id.clone()));
+                    // let order_limit = vec![
+                    //     self.pos.long_pos.to_string(),
+                    //     "pd".to_string(),
+                    //     price_limit.to_string(),
+                    //     order_client_limit_id.clone()
+                    // ];
+                    //
+                    // command.limits_close.insert(order_client_limit_id, order_limit.clone());
+                    // info!(?command);
                     // debug!(?command);
                 }
             }
@@ -1008,19 +1013,19 @@ impl Strategy {
                     command.limits_close.insert(order_client_id, order.clone());
 
                     // 定价止损平仓单
-                    let mut price_limit = self.pos.short_avg * Decimal::from_str("1.005").unwrap();
-                    price_limit = utils::fix_price(price_limit, self.tick_size);
-
-                    let order_client_limit_id = utils::generate_client_id(Some(self.broker_id.clone()));
-                    let order_limit = vec![
-                        self.pos.short_pos.to_string(),
-                        "pk".to_string(),
-                        price_limit.to_string(),
-                        order_client_limit_id.clone()
-                    ];
-
-                    command.limits_close.insert(order_client_limit_id, order_limit.clone());
-                    info!(?command);
+                    // let mut price_limit = self.pos.short_avg * Decimal::from_str("1.005").unwrap();
+                    // price_limit = utils::fix_price(price_limit, self.tick_size);
+                    //
+                    // let order_client_limit_id = utils::generate_client_id(Some(self.broker_id.clone()));
+                    // let order_limit = vec![
+                    //     self.pos.short_pos.to_string(),
+                    //     "pk".to_string(),
+                    //     price_limit.to_string(),
+                    //     order_client_limit_id.clone()
+                    // ];
+                    //
+                    // command.limits_close.insert(order_client_limit_id, order_limit.clone());
+                    // info!(?command);
                     // debug!(?command);
                 }
             }

+ 2 - 277
strategy/src/utils.rs

@@ -1,19 +1,9 @@
-use std::collections::HashMap;
-use std::iter::Map;
 use std::ops::{Div, Mul};
-use std::rc::Rc;
-use std::str::FromStr;
-use std::sync::Arc;
-use chrono::Month::December;
 use chrono::Utc;
 use rand::Rng;
-use rust_decimal::{Decimal, MathematicalOps};
+use rust_decimal::{Decimal};
 use tracing::error;
 use global::public_params;
-use ndarray::Array1;
-use rust_decimal::prelude::FromPrimitive;
-use tokio::fs::DirEntry;
-use crate::memoized_func::MemoizedFunc;
 
 // 生成订单的id,可以根据交易所名字来
 pub fn generate_client_id(exchange_name_some: Option<String>) -> String {
@@ -105,268 +95,11 @@ pub fn get_limit_order_requests_num_per_second(exchange: String) -> i64 {
     }
 }
 
-// 生成等差数列 [start, end)
-pub fn equidistant_sequence(start: i32, end: i32, step: i32) -> Vec<i32> {
-    let mut current = start;
-    let series: Vec<i32> = std::iter::repeat_with(move || {
-        let i = current;
-        current += step;
-        i
-    })
-        .take_while(|&i| i < end)
-        .collect();
-    series
-}
-
-// params = curve_fit(lambda t, a, b: a*np.exp(-b*t),
-//                                price_levels,
-//                                lambdas_adj,
-//                                p0=(self._alpha, self._kappa),
-//                                method='dogbox',
-//                                bounds=([0, 0], [np.inf, np.inf]))
-pub fn curve_fit(f: Rc<dyn Fn(&Vec<Decimal>, Decimal, Decimal) -> Vec<Decimal>>, x_data: Vec<Decimal>, y_data: Vec<Decimal>,
-                                                              p0: (Decimal, Decimal), method: String, bounds: (Vec<Decimal>, Vec<Decimal>)) {
-    let p0_arr = vec![p0.0, p0.1];
-    let n = p0_arr.len();
-    let lb = bounds.0;
-    let ub = bounds.1;
-    let bounded_problem = lb.iter().any(|&x| x > -Decimal::MIN) | ub.iter().any(|&y| y < Decimal::MAX);
-
-    if method.eq("lm") && bounded_problem {
-        // 主动抛出异常
-    }
-    let func: MemoizedFunc = MemoizedFunc::new(wrap_func(f, x_data, y_data));
-    let jac: &str = "2-point";
-}
-
-fn wrap_func(func: Rc<dyn Fn(&Vec<Decimal>, Decimal, Decimal) -> Vec<Decimal>>,
-              xdata: Vec<Decimal>,
-              ydata: Vec<Decimal>)
-              -> Rc<dyn Fn(Decimal, Decimal) -> Vec<Decimal>> {
-    let y_data = ydata.clone();
-    Rc::new(move |a, b| {
-        let m_data = func(&xdata, a, b);
-        m_data.iter().zip(y_data.iter()).map(|(&x_data, &y_item)| x_data - y_item).collect()
-    })
-}
-
-
-
-fn least_squares(mut fun: MemoizedFunc, x0: Vec<Decimal>){
-    let jac: &str = "2-point";
-    let bounds = (vec![Decimal::ZERO, Decimal::ZERO], vec![Decimal::MAX, Decimal::MAX]);
-    let method = "dogbox";
-    let kwargs: HashMap<&str, &str> = HashMap::new();
-    let lb = bounds.0;
-    let ub = bounds.1;
-    let x_scale: Vec<Decimal> = vec![Decimal::ONE];
-    let loos: &str = "linear";
-    let f_scale: Decimal = Decimal::ONE;
-
-    let f0 = fun.call(x0[0], x0[1]);
-    let f0_1 = f0.clone();
-    let n = x0.len();
-    let m = f0.len();
-    let dot: Decimal = f0.iter().zip(f0_1.iter()).map(|(x, y)| x * y).sum();
-    let initial_cost = Decimal::ONE/ Decimal::TWO * dot;
-
-    let j0 = approx_derivative(&mut fun, x0, f0);
-    let tr_solver = "exact";
-    let tr_options = {};
-    let verbose = 0;
-    let ftol = Decimal::ONE.powi(-8);
-    let xtol = Decimal::ONE.powi(-8);
-    let gtol = Decimal::ONE.powi(-8);
-    let max_nfev = {};
-    let loss_function = "NONE";
-    let jac_wrapped = jac_wrapped(&mut fun);
-
-
-
-}
-
-fn dogbox<F: Fn(Vec<Decimal>, Vec<Decimal>) -> Vec<Vec<Decimal>>>(fun: Rc<dyn Fn(&Vec<Decimal>, Decimal, Decimal) -> Vec<Decimal>>,
-                                                                  jac_wrapped: F, x0: Vec<Decimal>, f0: Vec<Decimal>, j0: Vec<Vec<Decimal>>,
-                                                                  lb: Vec<Decimal>, ub: Vec<Decimal>, ftol: Decimal, xtol: Decimal, gtol: Decimal,
-                                                                  x_scale: Vec<Decimal>, tr_solver: &str, verbose: i32) {
-    let f = f0.clone();
-    let f_true = f.clone();
-    let nfev = 1;
-    let J = j0.clone();
-    let njev = 1;
-    // 0.5 * np.dot(f, f)
-    let cost: Decimal = Decimal::ONE / Decimal::TWO * f.iter().zip(&f).map(|(a, b)| a * b).sum::<Decimal>();
-    let J_T = transpose(&j0);
-    let g: Vec<Decimal> = (0..J_T[0].len()).map(|i| {
-        J_T.iter().zip(&f).map(|(row, &f_value)| row[i] * f_value).sum()
-    }).collect();
-    let scale = x_scale.clone();
-    let scale_inv: Vec<Decimal> = x_scale.iter().map(|&val| Decimal::ONE / val).collect();
-
-    // let norm_params = x0.iter().map(|&val| val * scale_inv).collect();
-    // let delta
-
-
-
-}
-
-fn norm(x: Vec<Decimal>, ord: Decimal){
-
-
-
-}
-
-
-fn jac_wrapped(fun: &mut MemoizedFunc) -> impl FnMut(Vec<Decimal>, Vec<Decimal>) -> Vec<Vec<Decimal>> + '_{
-    |x, f| {
-        approx_derivative(fun, x, f)
-    }
-}
-
-
-
-fn approx_derivative(fun: &mut MemoizedFunc, x0: Vec<Decimal>, f0: Vec<Decimal>) -> Vec<Vec<Decimal>>{
-    // let rel_step: Vec<Decimal> = Vec::new();
-    // let method = "2-point";
-    let bounds = (vec![Decimal::ZERO, Decimal::ZERO], vec![Decimal::MAX, Decimal::MAX]);
-    let lb = bounds.0;
-    let ub = bounds.1;
-    let mut h = compute_absolute_step(x0.clone());
-    let h_use_one_sided = adjust_scheme_to_bounds(x0.clone(), h, lb, ub);
-    h = h_use_one_sided.0;
-    // let use_one_sided = h_use_one_sided.1;
-    return dense_difference(fun, x0, f0, h);
-}
-
-fn dense_difference(fun: &mut MemoizedFunc, x0: Vec<Decimal>, f0: Vec<Decimal>, h: Vec<Decimal>) -> Vec<Vec<Decimal>>{
-    let method = "2-point";
-    let m = f0.len();
-    let n = x0.len();
-    let h_len = h.len();
-    let mut j_transposed = vec![vec![Decimal::ZERO; n]; m];
-    let mut h_vecs = vec![vec![Decimal::ZERO; h_len]; h_len];
-
-    for i in 0..h_len {
-        h_vecs[i][i] = h[i];
-    }
-
-    for i in 0..h_len {
-        let x0_clone = x0.clone();
-        let x :Vec<Decimal> = x0_clone.iter().zip(h_vecs[i].iter()).map(|(&x0_val, &h_vec_val)| x0_val + h_vec_val).collect();
-        let dx: Decimal = x[i] - x0_clone[i];
-        let df = fun.call(x[0], x[1]);
-        j_transposed[i] = df.iter().map(|&df_val| df_val/dx).collect();
-    }
-    // if m == 1usize {
-    //     let result = j_transposed.into_iter().flatten().collect();
-    //     return result;
-    // } else if m == 2usize {
-    //
-    // } else{
-    //
-    // }
-    let transposed = transpose(&j_transposed);
-    return transposed
-}
-
-// 二维数组的转置操作
-fn transpose<T: Clone>(v: &Vec<Vec<T>>) -> Vec<Vec<T>> {
-    let mut result = vec![vec![v[0][0].clone(); v.len()]; v[0].len()];
-    for (i, row) in v.iter().enumerate() {
-        for (j, value) in row.iter().enumerate() {
-            result[j][i] = value.clone();
-        }
-    }
-    result
-}
-
-fn adjust_scheme_to_bounds(x0: Vec<Decimal>, h: Vec<Decimal>, lb: Vec<Decimal>, ub: Vec<Decimal>) -> (Vec<Decimal>, Vec<bool>){
-    let num_steps: Decimal = Decimal::ONE;
-    // let scheme = "1-sided";
-    let use_one_sided: Vec<bool> = vec![true; h.len()];
-    let all_inf = lb.iter().zip(ub.iter()).all(|(&lb_val, &ub_val)| lb_val == -Decimal::MAX && ub_val == Decimal::MAX);
-    if all_inf {
-       return (h, use_one_sided);
-    }
-
-    let h_total: Vec<Decimal> = h.iter().map(|&d| d * num_steps).collect();
-    let mut h_adjusted = h.clone();
-    let lower_dist: Vec<Decimal> = x0.iter().zip(lb.iter()).map(|(&x0_val, &lb_val)| x0_val - lb_val).collect();
-    let upper_dist: Vec<Decimal> = ub.iter().zip(x0.iter()).map(|(&ub_val, &x0_val)| {
-        if ub_val == Decimal::MAX{
-            Decimal::MAX
-        }else {
-            ub_val - x0_val
-        }
-    }).collect();
-
-    let x: Vec<Decimal> = x0.iter().zip(h_total.iter()).map(|(&d1, &d2)| d1 + d2).collect();
-    let violated_lb: Vec<bool> = x.iter().zip(lb.iter()).map(|(&x_val, &lb_val)| x_val < lb_val).collect();
-    let violated_ub: Vec<bool> = x.iter().zip(ub.iter()).map(|(&x_val, &ub_val)| x_val > ub_val).collect();
-    let violated: Vec<bool> = violated_lb.iter().zip(violated_ub.iter()).map(|(&vl_val, &vu_val)| vl_val | vu_val).collect();
-    let max_arr: Vec<Decimal> = lower_dist.iter().zip(upper_dist.iter()).map(|(&lower_val, &upper_val)|  upper_val.max(lower_val)).collect();
-    let abs_h_total: Vec<Decimal> = h_total.iter().map(|&h| h.abs()).collect();
-    let fitting: Vec<bool> = abs_h_total.iter().zip(max_arr.iter()).map(|(&abs_val, &max_val)| abs_val <= max_val).collect();
-    for ((h, &v), &f) in h_adjusted.iter_mut().zip(&violated).zip(&fitting) {
-        if v && f {
-            *h = -*h;
-        }
-    }
-    let forward: Vec<bool> = upper_dist.iter()
-        .zip(&lower_dist)
-        .zip(&fitting)
-        .map(|((&u, &l), &f)| u >= l && !f)
-        .collect();
-
-    for ((h, &u), &f) in h_adjusted.iter_mut().zip(&upper_dist).zip(&forward) {
-        if f {
-            *h = u / num_steps;
-        }
-    }
-    let backward: Vec<bool> = upper_dist.iter()
-        .zip(&lower_dist)
-        .zip(&fitting)
-        .map(|((&u, &l), &f)| u < l && !f)
-        .collect();
-
-    for ((h, &u), &f) in h_adjusted.iter_mut().zip(&lower_dist).zip(&backward) {
-        if f {
-            *h = u / num_steps;
-        }
-    }
-
-    return (h_adjusted, use_one_sided);
-}
-
-fn compute_absolute_step(x0: Vec<Decimal>) -> Vec<Decimal>{
-
-    // sign_x0 = (x0 >= 0).astype(float) * 2 - 1
-    let sign_x0: Vec<Decimal> = x0.iter().map(|&x| if x >= Decimal::ZERO { Decimal::ONE } else { Decimal::from_str("-1").unwrap() }).collect();
-
-    // Define rstep
-    let rstep = eps_for_method();
-    // abs_step = rstep * sign_x0 * np.maximum(1.0, np.abs(x0))
-    let abs_step: Vec<Decimal> = sign_x0.iter().zip(x0.iter()).map(|(&sign, &x)| rstep * sign * std::cmp::max(Decimal::ONE, x.abs())).collect();
-    abs_step
-}
-
-fn eps_for_method() -> Decimal{
-    let eps = f64::EPSILON;
-    Decimal::from_f64(eps.sqrt()).unwrap()
-}
-
-
-pub fn aaa(a: Decimal, b: Decimal) -> Decimal{
-    return a + b;
-}
-
 #[cfg(test)]
 mod tests {
     use chrono::Utc;
-    use ndarray::Array1;
-    use rust_decimal::Decimal;
     use rust_decimal_macros::dec;
-    use crate::utils::{aaa, clip, equidistant_sequence, fix_amount, fix_price, generate_client_id};
+    use crate::utils::{clip, fix_amount, fix_price, generate_client_id};
 
     #[test]
     fn clip_test() {
@@ -414,12 +147,4 @@ mod tests {
         println!("timestamp_nanos: {}", now.timestamp_nanos());
     }
 
-    #[test]
-    fn equidistant_sequence_test() {
-        let v: Vec<Decimal> = vec![Decimal::from(1), Decimal::from(2), Decimal::from(3)];
-        let a = aaa(v[0], v[1]);
-        println!("{:?}", a);
-        println!("{:?}", v);
-    }
-
 }