Parcourir la source

抽象方法已成

skyfffire il y a 2 semaines
Parent
commit
d5383146f5
2 fichiers modifiés avec 194 ajouts et 11 suppressions
  1. 1 3
      src/data_manager.rs
  2. 193 8
      src/strategy.rs

+ 1 - 3
src/data_manager.rs

@@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
 use anyhow::{anyhow, bail, Result};
 use rust_decimal::Decimal;
 use serde_json::Value;
-use tracing::{info, warn};
+use tracing::{warn};
 use crate::utils::response::Response;
 
 #[allow(dead_code)]
@@ -111,8 +111,6 @@ impl DataManager {
                 .map_err(|e| anyhow!("将价格字符串 '{}' 解析为 Decimal 失败: {},原始 JSON: {}", p, e, value_str))?;
         }
         
-        info!("{}, {}", self.best_ask, self.best_bid);
-        
         Ok(())
     }
 }

+ 193 - 8
src/strategy.rs

@@ -1,21 +1,206 @@
-use serde_json::Value;
-use tracing::info;
 use anyhow::Result;
+use rust_decimal::Decimal;
+use std::time::Instant;
+use tracing::info;
 use crate::data_manager::DataManager;
 
+#[derive(Debug, Clone, PartialEq)]
+pub enum StrategyState {
+    Idle,                           // 空闲状态,准备下单
+    WaitingLimitOrder {             // 等待限价单成交
+        order_id: String,
+        price: Decimal,
+        last_order_time: Instant,
+    },
+    CancellingOrder {               // 撤单中
+        order_id: String,
+        price: Decimal,
+        last_order_time: Instant,
+    },
+    ExecutingMarketOrder {          // 执行市价单
+        last_order_time: Instant,
+    },
+}
+
 #[allow(dead_code)]
 pub struct Strategy {
-    
+    state: StrategyState,
+    order_quantity: Decimal,        // 写死的订单数量
+    min_order_interval_ms: u128,    // 最小下单间隔(毫秒)
 }
 
 impl Strategy {
     pub fn new() -> Strategy {
-        Strategy {}
+        Strategy {
+            state: StrategyState::Idle,
+            order_quantity: Decimal::from(100), // 示例数量
+            min_order_interval_ms: 1000,
+        }
+    }
+
+    pub async fn do_strategy(&mut self, dm: &DataManager) -> Result<()> {
+        info!("Current state: {:?}", self.state);
+        info!("Best ask: {}, Best bid: {}", dm.best_ask, dm.best_bid);
+
+        match self.state.clone() {
+            StrategyState::Idle => {
+                self.handle_idle_state(dm).await?;
+            }
+            StrategyState::WaitingLimitOrder { order_id, price, last_order_time } => {
+                self.handle_waiting_limit_order(dm, order_id, price, last_order_time).await?;
+            }
+            StrategyState::CancellingOrder { order_id, price, last_order_time } => {
+                self.handle_cancelling_order(dm, order_id, price, last_order_time).await?;
+            }
+            StrategyState::ExecutingMarketOrder { last_order_time } => {
+                self.handle_executing_market_order(dm, last_order_time).await?;
+            }
+        }
+
+        Ok(())
+    }
+
+    // 状态1: 空闲状态,下限价买单
+    async fn handle_idle_state(&mut self, dm: &DataManager) -> Result<()> {
+        info!("进入空闲状态,准备下买单");
+
+        // 检查是否满足下单时间间隔
+        if let Some(last_time) = self.get_last_order_time() {
+            let elapsed = last_time.elapsed().as_millis();
+            if elapsed < self.min_order_interval_ms {
+                info!("距离上次下单时间不足{}ms,等待中...", self.min_order_interval_ms);
+                return Ok(());
+            }
+        }
+
+        let order_id = self.place_limit_buy_order(dm.best_bid, self.order_quantity).await?;
+
+        self.state = StrategyState::WaitingLimitOrder {
+            order_id,
+            price: dm.best_bid,
+            last_order_time: Instant::now(),
+        };
+
+        Ok(())
+    }
+
+    // 状态2&3: 等待限价单成交
+    async fn handle_waiting_limit_order(
+        &mut self,
+        dm: &DataManager,
+        order_id: String,
+        price: Decimal,
+        last_order_time: Instant,
+    ) -> Result<()> {
+        info!("等待限价单成交,订单ID: {}, 价格: {}", order_id, price);
+
+        // 检查订单是否已成交
+        if self.check_order_filled(&order_id).await? {
+            info!("限价单已成交,准备执行市价单");
+            self.state = StrategyState::ExecutingMarketOrder { last_order_time };
+            return Ok(());
+        }
+
+        // 检查价格是否变化
+        if dm.best_bid != price {
+            info!("价格已变化,从 {} 到 {},准备撤单", price, dm.best_bid);
+            self.state = StrategyState::CancellingOrder {
+                order_id,
+                price,
+                last_order_time,
+            };
+        }
+
+        Ok(())
+    }
+
+    // 状态3: 撤单处理
+    async fn handle_cancelling_order(
+        &mut self,
+        dm: &DataManager,
+        order_id: String,
+        price: Decimal,
+        last_order_time: Instant,
+    ) -> Result<()> {
+        info!("撤单中,订单ID: {}", order_id);
+
+        self.cancel_order(&order_id).await?;
+
+        // 撤单后检查是否有成交
+        if self.check_order_partially_filled(&order_id).await? {
+            info!("撤单时发现有成交,准备执行市价单");
+            self.state = StrategyState::ExecutingMarketOrder { last_order_time };
+        } else {
+            info!("撤单完成,无成交,返回空闲状态");
+            self.state = StrategyState::Idle;
+        }
+
+        Ok(())
     }
-    
-    pub async fn do_strategy(&mut self, data_manager: &DataManager) -> Result<()> {
-        
+
+    // 状态4: 执行市价单
+    async fn handle_executing_market_order(
+        &mut self,
+        dm: &DataManager,
+        last_order_time: Instant,
+    ) -> Result<()> {
+        info!("执行市价卖单");
+
+        let order_id = self.place_market_sell_order(self.order_quantity).await?;
+
+        // 等待市价单成交(市价单通常立即成交)
+        if self.check_order_filled(&order_id).await? {
+            info!("市价单已成交,返回空闲状态");
+            self.state = StrategyState::Idle;
+        }
 
         Ok(())
     }
-}
+
+    // 获取上次下单时间
+    fn get_last_order_time(&self) -> Option<Instant> {
+        match &self.state {
+            StrategyState::WaitingLimitOrder { last_order_time, .. } => Some(*last_order_time),
+            StrategyState::CancellingOrder { last_order_time, .. } => Some(*last_order_time),
+            StrategyState::ExecutingMarketOrder { last_order_time } => Some(*last_order_time),
+            _ => None,
+        }
+    }
+
+    // ==================== 抽象方法(待实现)====================
+
+    /// 下限价买单
+    async fn place_limit_buy_order(&self, price: Decimal, quantity: Decimal) -> Result<String> {
+        info!("下限价买单: 价格={}, 数量={}", price, quantity);
+        // TODO: 实现具体的下单逻辑
+        Ok("order_id_placeholder".to_string())
+    }
+
+    /// 下市价卖单
+    async fn place_market_sell_order(&self, quantity: Decimal) -> Result<String> {
+        info!("下市价卖单: 数量={}", quantity);
+        // TODO: 实现具体的下单逻辑
+        Ok("order_id_placeholder".to_string())
+    }
+
+    /// 撤单
+    async fn cancel_order(&self, order_id: &str) -> Result<()> {
+        info!("撤单: {}", order_id);
+        // TODO: 实现具体的撤单逻辑
+        Ok(())
+    }
+
+    /// 检查订单是否完全成交
+    async fn check_order_filled(&self, order_id: &str) -> Result<bool> {
+        info!("检查订单是否成交: {}", order_id);
+        // TODO: 实现具体的查询逻辑
+        Ok(false)
+    }
+
+    /// 检查订单是否有部分成交
+    async fn check_order_partially_filled(&self, order_id: &str) -> Result<bool> {
+        info!("检查订单是否有部分成交: {}", order_id);
+        // TODO: 实现具体的查询逻辑
+        Ok(false)
+    }
+}