redis保存状态

This commit is contained in:
zhangkun9038@dingtalk.com 2025-11-27 17:02:40 +08:00
parent ed0c8fcda0
commit dd2c4dc470

View File

@ -135,6 +135,9 @@ class GridManager:
self.last_report_candle = 0 # 上次报告的蜡烛线
self.report_interval_candles = 600 # 每 600 个蜡烛线报告一次(约 10h1h K线
# 控制标志:是否已从 Trade 对象初始化过持仓
self._synced_from_trade_once = False
def update_state(self, current_price: float, candle_index: int) -> None:
"""
更新网格对象的当前状态
@ -409,9 +412,8 @@ class GridManager:
"""
Freqtrade Trade 对象同步状态
由于 Trade 对象提供了实际持仓信息使用其更新网格状态
- 根据平均价找到应该填满的网格
- 全部低于平均价的网格为 FILLED高于平均价的为 EMPTY
仅在第一次同步时更新网格状态其他时候仅更新持仓股数
不修改 FILLED/EMPTY 网格状态 apply_adjustment 专管管理
Args:
trade: Freqtrade Trade 对象
@ -422,40 +424,43 @@ class GridManager:
self.total_invested = trade.stake_amount
self.avg_entry_price = trade.open_rate
# 根据 Trade 对象的平均价,更新所有网格的状态
# 下沿 → 平均价:全部 FILLED
# 平均价 → 上沿:全部 EMPTY
avg_grid_price = self._round_to_grid(self.avg_entry_price)
for price, grid_state in self.grid_states.items():
if price < avg_grid_price:
# 下沿:应该是 FILLED
if self.total_quantity > 0:
# 仅当不是 FILLED 或 quantity 为 0 时,才一次性设置
# 不然锻会每次慢成 FILLED造成或眅效率低
if grid_state.status != "filled" or grid_state.quantity == 0:
# 仅在第一次同步时,根据均价、更新所有网格的状态
if not self._synced_from_trade_once and self.total_quantity > 0:
self._synced_from_trade_once = True
# 根据 Trade 对象的平均价,更新所有网格的状态
# 下沿 → 平均价:全部 FILLED
# 平均价 → 上沿:全部 EMPTY
avg_grid_price = self._round_to_grid(self.avg_entry_price)
for price, grid_state in self.grid_states.items():
if price < avg_grid_price:
# 下沿:应该是 FILLED
if self.total_quantity > 0:
grid_state.status = "filled"
grid_state.entry_price = self.avg_entry_price
grid_state.entry_time = candle_index
else:
elif price > avg_grid_price:
# 上沿:应该是 EMPTY
grid_state.status = "empty"
grid_state.quantity = 0
elif price > avg_grid_price:
# 上沿:应该是 EMPTY
grid_state.status = "empty"
grid_state.quantity = 0
else:
# 不太可能,但为了严谨标记为 FILLED
if self.total_quantity > 0:
grid_state.status = "filled"
grid_state.entry_price = self.avg_entry_price
grid_state.entry_time = candle_index
print(f"[GridManager] {self.pair} 从 Trade 对象同步 - "
f"持仓: {self.total_quantity:.6f}, "
f"平均价: {self.avg_entry_price:.2f}, "
f"下沿到平均价的网格标记为 FILLED",
file=sys.stderr, flush=True)
else:
# 平均价所在的网格
if self.total_quantity > 0:
grid_state.status = "filled"
grid_state.entry_price = self.avg_entry_price
grid_state.entry_time = candle_index
print(f"[GridManager] {self.pair} 从 Trade 对象初始化 - "
f"持仓: {self.total_quantity:.6f}, "
f"平均价: {self.avg_entry_price:.2f}, "
f"下沿到平均价的网格标记为 FILLED",
file=sys.stderr, flush=True)
else:
# 之后的同步:仅更新持仓信息,不修改网格状态
if not self._synced_from_trade_once and self.total_quantity == 0:
print(f"[GridManager] {self.pair} Trade 对象尚无持仓,跳过初始化",
file=sys.stderr, flush=True)
def record_pending_order(self, order_id: str, adjustment: PositionRecord) -> None:
"""