Quellcode durchsuchen

完成清仓模式开发(已测试,待对接中控)

JiahengHe vor 1 Jahr
Ursprung
Commit
97e0d224b3
4 geänderte Dateien mit 23 neuen und 28 gelöschten Zeilen
  1. 4 1
      global/src/params.rs
  2. 8 7
      src/main.rs
  3. 2 3
      standard/src/lib.rs
  4. 9 17
      strategy/src/clear_core.rs

+ 4 - 1
global/src/params.rs

@@ -51,7 +51,9 @@ pub struct Params {
     // 中控端口
     pub port: u32,
     // 运行模式 0.正常策略运行, 1.清理挂单及仓位
-    pub run_mode: i8
+    pub run_mode: i8,
+    // 机器人id
+    pub robot_id: String,
 }
 
 impl Params {
@@ -99,6 +101,7 @@ impl Params {
             log_level: "info".to_string(),
             port: call_port,
             run_mode: 0,
+            robot_id: "-1".to_string()
         };
         Ok(params)
     }

+ 8 - 7
src/main.rs

@@ -47,7 +47,7 @@ fn read_params_json() -> Params {
     let mut call_port = 5555;
     // 运行模式 0.正常策略运行, 1.清理挂单及仓位
     let mut run_mode = 0;
-    let robot_id;
+    let mut robot_id= "-1".to_string();
 
     let args: Vec<String> = std::env::args().collect();
 
@@ -86,22 +86,23 @@ fn read_params_json() -> Params {
         if arg.starts_with("--robot_id=") {
             let parts: Vec<&str> = arg.split('=').collect();
             if parts.len() == 2 {
-                robot_id = parts[1]
+                robot_id = parts[1].to_string();
             } else {
                 error!("启动失败,机器人id参数格式设置错误 --robot_id=xxx!");
                 panic!("启动失败,机器人id参数格式设置错误 --robot_id=xxx!");
             }
-        } else {
-            error!("启动失败,缺少机器人id参数!");
-            panic!("启动失败,缺少机器人id参数!");
         }
     }
-
+    if robot_id == "-1" {
+        error!("启动失败,缺少机器人id参数!");
+        panic!("启动失败,缺少机器人id参数!");
+    }
     println!("通讯端口:{}, 配置文件路径:{}", call_port, path);
     let mut params = Params::new_json(path, call_port).unwrap();
     if run_mode == 1{
         params.run_mode = 1;
     }
+    params.robot_id = robot_id;
     return params;
 }
 
@@ -145,7 +146,7 @@ async fn main() {
         // core初始化动作
         let mut core_arc = clear_core_libs::init(params.clone(), ws_running.clone(), running.clone(), cci_arc.clone()).await;
         info!("开始执行清仓程序");
-        core_arc.exit("123456".to_string()).await;
+        core_arc.exit(params.robot_id).await;
         info!("清仓程序执行完毕");
         // 强制退出
         std::process::exit(0);

+ 2 - 3
standard/src/lib.rs

@@ -4,7 +4,6 @@ use std::fmt::Formatter;
 use std::io::{Error};
 use async_trait::async_trait;
 use rust_decimal::Decimal;
-use serde::Serialize;
 use serde_json::Value;
 use tokio::time::Instant;
 use global::trace_stack::TraceStack;
@@ -279,7 +278,7 @@ impl SpecialOrder {
 /// - `avg_price(Decimal)`: 成交均价
 /// - `status(String)`: 订单状态
 /// - `order_type(String)`: 订单类型
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Order {
     pub id: String,
     pub custom_id: String,
@@ -398,7 +397,7 @@ impl Market {
 /// - `profit(Decimal)`: 持仓浮动盈亏
 /// - `position_mode(PositionModeEnum)`: 持仓模式
 /// - `margin(Decimal)`: 仓位占用的保证金
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Position {
     pub symbol: String,
     pub margin_level: Decimal,

+ 9 - 17
strategy/src/clear_core.rs

@@ -2,12 +2,11 @@ use tokio::time::Instant;
 use std::collections::{BTreeMap, HashMap};
 use std::io::Error;
 use std::sync::Arc;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool};
 use std::time::Duration;
 use chrono::{Utc};
 use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderValue};
 use rust_decimal::Decimal;
-use rust_decimal::prelude::ToPrimitive;
 use rust_decimal_macros::dec;
 use tokio::sync::mpsc::{Sender};
 use tokio::sync::{Mutex};
@@ -432,14 +431,12 @@ impl ClearCore {
         let mut result = ClearPositionResult::new();
         info!("------------------------------------------------------------------------------------------------------------");
         info!("步骤一:检查挂单:");
-        let mut is_order_clear = false;
         match self.platform_rest.cancel_orders_all().await {
             Ok(val) => {
                 let length = val.len();
-                is_order_clear = length == 0;
                 result.clear_order_num = length.to_string();
                 info!("已清空所有挂单({}条)", length);
-                result.clear_order_str = serde_json::to_string(&val).expect("Failed to serialize to JSON---- order");
+                result.clear_order_str = format!("清空所有挂单:{:?}", val);
                 for o in val {
                     info!("    {:?}", o);
                 }
@@ -449,9 +446,8 @@ impl ClearCore {
                 match self.platform_rest.cancel_orders().await {
                     Ok(val) => {
                         let length = val.len();
-                        is_order_clear = length == 0;
                         result.clear_order_num = length.to_string();
-                        result.clear_order_str = serde_json::to_string(&val).expect("Failed to serialize to JSON----  order");
+                        result.clear_order_str = format!("清空所有挂单(备用):{:?}", val);
                         info!("清空所有挂单({}条):{:?}", length, val);
                     }
                     Err(exc) => {
@@ -543,11 +539,10 @@ impl ClearCore {
         // 设置机器人id
         result.robot_id = robot_id;
         info!("清仓程序结果 {:?}", result);
-        /**
-         * todo: 判断是否有清仓,是否有异常
-        **/
+        // 判断是否有清仓,是否有异常
         if result.clear_position_num != "0" || result.clear_order_num != "0" || result.clear_other_err{
-            send_clear_msg_request(&result).await;
+            info!("上报了清仓信息!!!")
+            // send_clear_msg_request(&result).await;
             // 上报清仓日志
         }
 
@@ -589,8 +584,6 @@ impl ClearCore {
         // 初始化策略基础信息
         if mp <= Decimal::ZERO {
             self.exit_msg = format!("{}{}", "初始价格获取错误: ", mp);
-            // 停止程序
-            self.stop().await;
             return false;
         } else {
             info!("初始价格为 {}", mp);
@@ -614,8 +607,6 @@ impl ClearCore {
         }
         if self.strategy.step_size.is_zero() || self.strategy.tick_size.is_zero() {
             self.exit_msg = format!("{}{}{}{}", "交易精度未正常获取 step_size: ", self.strategy.step_size, " tick_size:", self.strategy.tick_size);
-            // 停止程序
-            self.stop().await;
             return false;
         } else {
             info!("数量精度 {}", self.strategy.step_size);
@@ -655,12 +646,13 @@ pub async fn send_clear_msg_request(body_params: &ClearPositionResult) {
         .await;
     match res {
         Ok(response) => {
+            let status = response.status();
             let response_text = response.text().await.unwrap_or("获取请求的响应文本异常".to_string());
             // 检查响应状态并读取响应体
-            if response.status().is_success() {
+            if status.is_success() {
                 info!("清仓结果上报中控,请求成功,响应文本: {}", response_text);
             } else {
-                println!("清仓结果上报中控,请求失败: 响应异常码 {},响应文本 {}", response.status(), response_text);
+                println!("清仓结果上报中控,请求失败: 响应异常码 {},响应文本 {}", status, response_text);
             }
         },
         Err(e) => {