grid_trader.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. from __future__ import annotations
  2. import time
  3. from datetime import datetime, timezone
  4. from src.trader_mcp.strategy_sdk import Strategy
  5. class Strategy(Strategy):
  6. LABEL = "Grid Trader"
  7. TICK_MINUTES = 0.2
  8. # NOTE:
  9. # This strategy is currently using a protective workaround for stale order state,
  10. # because exec-mcp can temporarily report order records that do not reflect the
  11. # clean post-reset strategy state. The grid prefers its own fresh persisted state
  12. # first, so the real exchange behavior stays testable while exec-mcp is improved.
  13. # Expect the reconciliation behavior to change again once exec-mcp is fixed.
  14. CONFIG_SCHEMA = {
  15. "grid_levels": {"type": "int", "default": 6, "min": 1, "max": 20},
  16. "grid_step_pct": {"type": "float", "default": 0.012, "min": 0.001, "max": 0.1},
  17. "volatility_timeframe": {"type": "string", "default": "1h"},
  18. "volatility_multiplier": {"type": "float", "default": 0.5, "min": 0.0, "max": 10.0},
  19. "grid_step_min_pct": {"type": "float", "default": 0.005, "min": 0.0001, "max": 0.5},
  20. "grid_step_max_pct": {"type": "float", "default": 0.03, "min": 0.0001, "max": 1.0},
  21. "order_size": {"type": "float", "default": 0.0, "min": 0.0},
  22. "inventory_cap_pct": {"type": "float", "default": 0.7, "min": 0.0, "max": 1.0},
  23. "recenter_pct": {"type": "float", "default": 0.05, "min": 0.0, "max": 0.5},
  24. "fee_rate": {"type": "float", "default": 0.0025, "min": 0.0, "max": 0.05},
  25. "trade_sides": {"type": "string", "default": "both"},
  26. "max_notional_per_order": {"type": "float", "default": 0.0, "min": 0.0},
  27. "order_call_delay_ms": {"type": "int", "default": 250, "min": 0, "max": 10000},
  28. "enable_trend_guard": {"type": "bool", "default": True},
  29. "trend_guard_reversal_max": {"type": "float", "default": 0.25, "min": 0.0, "max": 1.0},
  30. "debug_orders": {"type": "bool", "default": True},
  31. "use_all_available": {"type": "bool", "default": True},
  32. }
  33. STATE_SCHEMA = {
  34. "center_price": {"type": "float", "default": 0.0},
  35. "last_price": {"type": "float", "default": 0.0},
  36. "seeded": {"type": "bool", "default": False},
  37. "last_action": {"type": "string", "default": "idle"},
  38. "last_error": {"type": "string", "default": ""},
  39. "orders": {"type": "list", "default": []},
  40. "order_ids": {"type": "list", "default": []},
  41. "debug_log": {"type": "list", "default": []},
  42. "base_available": {"type": "float", "default": 0.0},
  43. "counter_available": {"type": "float", "default": 0.0},
  44. "trend_guard_active": {"type": "bool", "default": False},
  45. "regimes_updated_at": {"type": "string", "default": ""},
  46. "account_snapshot_updated_at": {"type": "string", "default": ""},
  47. }
  48. def init(self):
  49. return {
  50. "center_price": 0.0,
  51. "last_price": 0.0,
  52. "seeded": False,
  53. "last_action": "idle",
  54. "last_error": "",
  55. "orders": [],
  56. "order_ids": [],
  57. "debug_log": ["init cancel all orders"],
  58. "base_available": 0.0,
  59. "counter_available": 0.0,
  60. "trend_guard_active": False,
  61. "regimes_updated_at": "",
  62. "account_snapshot_updated_at": "",
  63. }
  64. def _log(self, message: str) -> None:
  65. state = getattr(self, "state", {}) or {}
  66. log = list(state.get("debug_log") or [])
  67. log.append(message)
  68. state["debug_log"] = log[-12:]
  69. self.state = state
  70. def _base_symbol(self) -> str:
  71. return (self.context.base_currency or self.context.market_symbol or "XRP").split("/")[0].upper()
  72. def _market_symbol(self) -> str:
  73. return self.context.market_symbol or f"{self._base_symbol().lower()}usd"
  74. def _mode(self) -> str:
  75. return getattr(self.context, "mode", "active") or "active"
  76. def _price(self) -> float:
  77. payload = self.context.get_price(self._base_symbol())
  78. return float(payload.get("price") or 0.0)
  79. def _regime_snapshot(self) -> dict:
  80. timeframes = ["1d", "4h", "1h", "15m"]
  81. snapshot = {}
  82. for tf in timeframes:
  83. try:
  84. snapshot[tf] = self.context.get_regime(self._base_symbol(), tf)
  85. except Exception as exc:
  86. snapshot[tf] = {"error": str(exc)}
  87. return snapshot
  88. def _refresh_regimes(self) -> None:
  89. self.state["regimes"] = self._regime_snapshot()
  90. self.state["regimes_updated_at"] = datetime.now(timezone.utc).isoformat()
  91. def _trend_guard_status(self) -> tuple[bool, str]:
  92. if not bool(self.config.get("enable_trend_guard", True)):
  93. return False, "disabled"
  94. reversal_max = float(self.config.get("trend_guard_reversal_max", 0.25) or 0.0)
  95. regimes = self.state.get("regimes") or self._regime_snapshot()
  96. d1 = (regimes.get("1d") or {}) if isinstance(regimes, dict) else {}
  97. h4 = (regimes.get("4h") or {}) if isinstance(regimes, dict) else {}
  98. d1_trend = str((d1.get("trend") or {}).get("state") or "unknown")
  99. h4_trend = str((h4.get("trend") or {}).get("state") or "unknown")
  100. d1_rev = float((d1.get("reversal") or {}).get("score") or 0.0)
  101. h4_rev = float((h4.get("reversal") or {}).get("score") or 0.0)
  102. strong_trend = d1_trend in {"bull", "bear"} and d1_trend == h4_trend
  103. weak_reversal = max(d1_rev, h4_rev) <= reversal_max
  104. active = bool(strong_trend and weak_reversal)
  105. reason = f"1d={d1_trend} 4h={h4_trend} rev={max(d1_rev, h4_rev):.3f}"
  106. return active, reason
  107. def _grid_step_pct(self) -> float:
  108. base_step = float(self.config.get("grid_step_pct", 0.012) or 0.012)
  109. tf = str(self.config.get("volatility_timeframe", "1h") or "1h")
  110. multiplier = float(self.config.get("volatility_multiplier", 0.5) or 0.0)
  111. min_step = float(self.config.get("grid_step_min_pct", 0.005) or 0.0)
  112. max_step = float(self.config.get("grid_step_max_pct", 0.03) or 1.0)
  113. try:
  114. regime = self.context.get_regime(self._base_symbol(), tf)
  115. short_regime = self.context.get_regime(self._base_symbol(), "15m")
  116. atr_pct = float((regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  117. short_atr_pct = float((short_regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  118. atr_pct = max(atr_pct, short_atr_pct)
  119. self.state["regimes"] = self._regime_snapshot()
  120. except Exception as exc:
  121. self._log(f"regime fetch failed: {exc}")
  122. atr_pct = 0.0
  123. adaptive = (atr_pct / 100.0) * multiplier if atr_pct > 0 else base_step
  124. step = adaptive if atr_pct > 0 else base_step
  125. step = max(step, min_step)
  126. step = min(step, max_step)
  127. self.state["grid_step_pct"] = step
  128. self.state["atr_percent"] = atr_pct
  129. return step
  130. def _available_balance(self, asset_code: str) -> float:
  131. try:
  132. info = self.context.get_account_info()
  133. except Exception as exc:
  134. self._log(f"account info failed: {exc}")
  135. return 0.0
  136. balances = info.get("balances") if isinstance(info, dict) else []
  137. if not isinstance(balances, list):
  138. return 0.0
  139. wanted = str(asset_code or "").upper()
  140. for balance in balances:
  141. if not isinstance(balance, dict):
  142. continue
  143. if str(balance.get("asset_code") or "").upper() != wanted:
  144. continue
  145. try:
  146. return float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  147. except Exception:
  148. return 0.0
  149. return 0.0
  150. def _refresh_balance_snapshot(self) -> None:
  151. try:
  152. info = self.context.get_account_info()
  153. except Exception as exc:
  154. self._log(f"balance refresh failed: {exc}")
  155. return
  156. balances = info.get("balances") if isinstance(info, dict) else []
  157. if not isinstance(balances, list):
  158. return
  159. base = self._base_symbol()
  160. quote = self.context.counter_currency or "USD"
  161. for balance in balances:
  162. if not isinstance(balance, dict):
  163. continue
  164. asset = str(balance.get("asset_code") or "").upper()
  165. try:
  166. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  167. except Exception:
  168. continue
  169. if asset == base:
  170. self.state["base_available"] = available
  171. if asset == str(quote).upper():
  172. self.state["counter_available"] = available
  173. self.state["account_snapshot_updated_at"] = datetime.now(timezone.utc).isoformat()
  174. def _supported_levels(self, side: str, price: float, min_notional: float) -> int:
  175. if min_notional <= 0 or price <= 0:
  176. return 0
  177. safety = 0.995
  178. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  179. if side == "buy":
  180. quote = self.context.counter_currency or "USD"
  181. quote_available = self._available_balance(quote)
  182. self.state["counter_available"] = quote_available
  183. usable_notional = quote_available * safety
  184. return max(int(usable_notional / min_notional), 0)
  185. base = self._base_symbol()
  186. base_available = self._available_balance(base)
  187. self.state["base_available"] = base_available
  188. usable_notional = base_available * safety * price / (1 + fee_rate)
  189. return max(int(usable_notional / min_notional), 0)
  190. def _side_allowed(self, side: str) -> bool:
  191. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  192. if selected == "both":
  193. return True
  194. return selected == side
  195. def _desired_sides(self) -> set[str]:
  196. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  197. if selected == "both":
  198. return {"buy", "sell"}
  199. if selected in {"buy", "sell"}:
  200. return {selected}
  201. return {"buy", "sell"}
  202. def _suggest_amount(self, side: str, price: float, levels: int, min_notional: float) -> float:
  203. if levels <= 0 or price <= 0:
  204. return 0.0
  205. safety = 0.995
  206. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  207. max_notional = float(self.config.get("max_notional_per_order", 0.0) or 0.0)
  208. manual = float(self.config.get("order_size", 0.0) or 0.0)
  209. min_amount = (min_notional / price) if min_notional > 0 else 0.0
  210. if side == "buy":
  211. quote = self.context.counter_currency or "USD"
  212. quote_available = self._available_balance(quote)
  213. self.state["counter_available"] = quote_available
  214. spendable_quote = quote_available * safety
  215. amount = spendable_quote / (max(levels, 1) * price * (1 + fee_rate))
  216. else:
  217. base = self._base_symbol()
  218. base_available = self._available_balance(base)
  219. self.state["base_available"] = base_available
  220. spendable_base = (base_available * safety) / (1 + fee_rate)
  221. amount = spendable_base / max(levels, 1)
  222. amount = max(amount, min_amount * 1.05)
  223. if max_notional > 0 and price > 0:
  224. amount = min(amount, max_notional / (price * (1 + fee_rate)))
  225. if manual > 0:
  226. if manual >= min_amount:
  227. amount = min(amount, manual)
  228. else:
  229. self._log(
  230. f"manual order_size below minimum: order_size={manual:.6g} min_amount={min_amount:.6g} price={price} min_notional={min_notional}"
  231. )
  232. return max(amount, 0.0)
  233. def _place_grid(self, center: float) -> None:
  234. mode = self._mode()
  235. levels = int(self.config.get("grid_levels", 6) or 6)
  236. step = self._grid_step_pct()
  237. min_notional = float(self.context.minimum_order_value or 0.0)
  238. market = self._market_symbol()
  239. orders = []
  240. order_ids = []
  241. def _capture_order_id(result):
  242. if isinstance(result, dict):
  243. return result.get("bitstamp_order_id") or result.get("order_id") or result.get("id") or result.get("client_order_id")
  244. return None
  245. buy_levels = min(levels, self._supported_levels("buy", center, min_notional)) if (mode == "active" and self._side_allowed("buy")) else (levels if self._side_allowed("buy") else 0)
  246. sell_levels = min(levels, self._supported_levels("sell", center, min_notional)) if (mode == "active" and self._side_allowed("sell")) else (levels if self._side_allowed("sell") else 0)
  247. buy_amount = self._suggest_amount("buy", center, max(buy_levels, 1), min_notional)
  248. sell_amount = self._suggest_amount("sell", center, max(sell_levels, 1), min_notional)
  249. for i in range(1, levels + 1):
  250. buy_price = round(center * (1 - (step * i)), 8)
  251. sell_price = round(center * (1 + (step * i)), 8)
  252. if mode != "active":
  253. orders.append({"side": "buy", "price": buy_price, "amount": buy_amount, "result": {"simulated": True}})
  254. orders.append({"side": "sell", "price": sell_price, "amount": sell_amount, "result": {"simulated": True}})
  255. self._log(f"plan level {i}: buy {buy_price} amount {buy_amount:.6g} / sell {sell_price} amount {sell_amount:.6g}")
  256. continue
  257. if i > buy_levels and i > sell_levels:
  258. self._log(f"skip level {i}: no capacity on either side")
  259. continue
  260. min_size_buy = (min_notional / buy_price) if buy_price > 0 else 0.0
  261. min_size_sell = (min_notional / sell_price) if sell_price > 0 else 0.0
  262. try:
  263. if i <= buy_levels and buy_amount >= min_size_buy:
  264. buy = self.context.place_order(side="buy", order_type="limit", amount=buy_amount, price=buy_price, market=market)
  265. orders.append({"side": "buy", "price": buy_price, "amount": buy_amount, "result": buy})
  266. buy_id = _capture_order_id(buy)
  267. if buy_id is not None:
  268. order_ids.append(str(buy_id))
  269. if i <= sell_levels and sell_amount >= min_size_sell:
  270. sell = self.context.place_order(side="sell", order_type="limit", amount=sell_amount, price=sell_price, market=market)
  271. orders.append({"side": "sell", "price": sell_price, "amount": sell_amount, "result": sell})
  272. sell_id = _capture_order_id(sell)
  273. if sell_id is not None:
  274. order_ids.append(str(sell_id))
  275. self._log(f"seed level {i}: buy {buy_price} amount {buy_amount:.6g} / sell {sell_price} amount {sell_amount:.6g}")
  276. except Exception as exc: # best effort for first draft
  277. self.state["last_error"] = str(exc)
  278. self._log(f"seed level {i} failed: {exc}")
  279. continue
  280. delay = max(int(self.config.get("order_call_delay_ms", 250) or 0), 0) / 1000.0
  281. if delay > 0:
  282. time.sleep(delay)
  283. self.state["orders"] = orders
  284. self.state["order_ids"] = order_ids
  285. self.state["last_action"] = "seeded grid"
  286. def _place_side_grid(self, side: str, center: float, *, start_level: int = 1) -> None:
  287. levels = int(self.config.get("grid_levels", 6) or 6)
  288. step = self._grid_step_pct()
  289. min_notional = float(self.context.minimum_order_value or 0.0)
  290. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  291. safety = 0.995
  292. market = self._market_symbol()
  293. orders = list(self.state.get("orders") or [])
  294. order_ids = list(self.state.get("order_ids") or [])
  295. side_levels = min(levels, self._supported_levels(side, center, min_notional))
  296. amount = self._suggest_amount(side, center, max(side_levels, 1), min_notional)
  297. if side == "buy":
  298. quote = self.context.counter_currency or "USD"
  299. quote_available = self._available_balance(quote)
  300. max_affordable_amount = (quote_available * safety) / (center * (1 + fee_rate)) if center > 0 else 0.0
  301. min_amount = (min_notional / center) if center > 0 and min_notional > 0 else 0.0
  302. if max_affordable_amount < min_amount:
  303. self._log(
  304. f"skip side buy: insufficient counter balance quote={quote_available:.6g} max_affordable_amount={max_affordable_amount:.6g} min_amount={min_amount:.6g} fee_rate={fee_rate}"
  305. )
  306. return
  307. amount = min(amount, max_affordable_amount)
  308. if side_levels <= 0 and min_notional > 0 and center > 0:
  309. min_amount = min_notional / center
  310. if amount >= min_amount:
  311. side_levels = 1
  312. self._log(f"side {side} restored to 1 level because amount clears minimum: amount={amount:.6g} min_amount={min_amount:.6g}")
  313. self._log(
  314. f"prepare side {side}: market={market} center={center} levels={side_levels} amount={amount:.6g} min_notional={min_notional} existing_ids={order_ids}"
  315. )
  316. for i in range(start_level, levels + 1):
  317. price = round(center * (1 - (step * i)) if side == "buy" else center * (1 + (step * i)), 8)
  318. min_size = (min_notional / price) if price > 0 else 0.0
  319. if i > side_levels or amount < min_size:
  320. self._log(
  321. f"skip side {side} level {i}: amount={amount:.6g} below min_size={min_size:.6g} min_notional={min_notional} price={price}"
  322. )
  323. continue
  324. try:
  325. self._log(f"place side {side} level {i}: price={price} amount={amount:.6g}")
  326. result = self.context.place_order(side=side, order_type="limit", amount=amount, price=price, market=market)
  327. status = None
  328. order_id = None
  329. if isinstance(result, dict):
  330. status = result.get("status")
  331. order_id = result.get("bitstamp_order_id") or result.get("order_id") or result.get("id") or result.get("client_order_id")
  332. self._log(f"place side {side} level {i} result status={status} order_id={order_id} raw={result}")
  333. orders.append({"side": side, "price": price, "amount": amount, "result": result})
  334. if order_id is not None:
  335. order_ids.append(str(order_id))
  336. self._log(f"seed side {side} level {i}: {price} amount {amount:.6g}")
  337. except Exception as exc:
  338. self.state["last_error"] = str(exc)
  339. self._log(f"seed side {side} level {i} failed: {exc}")
  340. continue
  341. delay = max(int(self.config.get("order_call_delay_ms", 250) or 0), 0) / 1000.0
  342. if delay > 0:
  343. time.sleep(delay)
  344. self.state["orders"] = orders
  345. self.state["order_ids"] = order_ids
  346. self._log(f"side {side} placement complete: tracked_ids={order_ids}")
  347. def _top_up_missing_levels(self, center: float, live_orders: list[dict]) -> None:
  348. target_levels = int(self.config.get("grid_levels", 6) or 6)
  349. if target_levels <= 0:
  350. return
  351. for side in ("buy", "sell"):
  352. count = 0
  353. for order in live_orders:
  354. if not isinstance(order, dict):
  355. continue
  356. if str(order.get("side") or "").lower() == side:
  357. count += 1
  358. if 0 < count < target_levels:
  359. self._log(f"top up side {side}: have {count}, want {target_levels}")
  360. self._place_side_grid(side, center, start_level=count + 1)
  361. def _cancel_obsolete_side_orders(self, open_orders: list[dict], desired_sides: set[str]) -> list[str]:
  362. removed: list[str] = []
  363. for order in open_orders:
  364. if not isinstance(order, dict):
  365. continue
  366. side = str(order.get("side") or "").lower()
  367. order_id = str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  368. if not order_id or side in desired_sides:
  369. continue
  370. try:
  371. self.context.cancel_order(order_id)
  372. removed.append(order_id)
  373. self._log(f"cancelled obsolete {side} order {order_id}")
  374. except Exception as exc:
  375. self.state["last_error"] = str(exc)
  376. self._log(f"cancel obsolete {side} order {order_id} failed: {exc}")
  377. return removed
  378. def _sync_open_orders_state(self) -> list[dict]:
  379. try:
  380. open_orders = self.context.get_open_orders()
  381. except Exception as exc:
  382. self.state["last_error"] = str(exc)
  383. self._log(f"open orders sync failed: {exc}")
  384. return []
  385. if not isinstance(open_orders, list):
  386. open_orders = []
  387. live_orders = [order for order in open_orders if isinstance(order, dict)]
  388. live_ids = [str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "") for order in live_orders]
  389. live_ids = [oid for oid in live_ids if oid]
  390. live_sides = [str(order.get("side") or "").lower() for order in live_orders]
  391. self.state["orders"] = live_orders
  392. self.state["order_ids"] = live_ids
  393. self.state["open_order_count"] = len(live_ids)
  394. self._log(f"sync live orders: count={len(live_ids)} sides={live_sides} ids={live_ids}")
  395. return live_orders
  396. def _cancel_orders(self, order_ids) -> None:
  397. for order_id in order_ids or []:
  398. self._log(f"dropping stale order {order_id} from state")
  399. def on_tick(self, tick):
  400. self._refresh_balance_snapshot()
  401. price = self._price()
  402. self.state["last_price"] = price
  403. self.state["last_error"] = ""
  404. self._refresh_regimes()
  405. try:
  406. live_orders = self._sync_open_orders_state()
  407. live_ids = list(self.state.get("order_ids") or [])
  408. open_order_count = len(live_ids)
  409. expected_ids = [str(oid) for oid in (self.state.get("order_ids") or []) if oid]
  410. stale_ids = []
  411. missing_ids = []
  412. except Exception as exc:
  413. open_order_count = -1
  414. live_orders = []
  415. live_ids = []
  416. expected_ids = []
  417. stale_ids = []
  418. missing_ids = []
  419. self.state["last_error"] = str(exc)
  420. self._log(f"open orders check failed: {exc}")
  421. # Workaround: after a reset, trust the fresh strategy state first.
  422. # This prevents stale exec-mcp records from blocking the next clean test.
  423. if not (self.state.get("order_ids") or []):
  424. live_orders = []
  425. live_ids = []
  426. open_order_count = 0
  427. expected_ids = []
  428. stale_ids = []
  429. missing_ids = []
  430. self.state["open_order_count"] = open_order_count
  431. desired_sides = self._desired_sides()
  432. mode = self._mode()
  433. guard_active, guard_reason = self._trend_guard_status()
  434. self.state["trend_guard_active"] = guard_active
  435. if mode == "active" and guard_active:
  436. self._log(f"trend guard active: {guard_reason}")
  437. try:
  438. self.context.cancel_all_orders()
  439. except Exception as exc:
  440. self.state["last_error"] = str(exc)
  441. self._log(f"trend guard cancel failed: {exc}")
  442. self.state["last_action"] = "trend_guard"
  443. return {"action": "guard", "price": price, "reason": guard_reason}
  444. if mode != "active":
  445. if not self.state.get("seeded") or not self.state.get("center_price"):
  446. self.state["center_price"] = price
  447. self._place_grid(price)
  448. self.state["seeded"] = True
  449. self._log(f"planned grid at {price}")
  450. return {"action": "plan", "price": price}
  451. center = float(self.state.get("center_price") or price)
  452. recenter_pct = float(self.config.get("recenter_pct", 0.05) or 0.05)
  453. deviation = abs(price - center) / center if center else 0.0
  454. if deviation >= recenter_pct:
  455. self.state["center_price"] = price
  456. self._place_grid(price)
  457. self._log(f"planned recenter to {price}")
  458. return {"action": "plan", "price": price, "deviation": deviation}
  459. self.state["last_action"] = "observe monitor"
  460. self._log(f"observe at {price} dev {deviation:.4f}")
  461. return {"action": "observe", "price": price, "deviation": deviation}
  462. if stale_ids:
  463. self._log(f"stale live orders: {stale_ids}")
  464. self._cancel_orders(stale_ids)
  465. live_ids = [oid for oid in live_ids if oid not in stale_ids]
  466. if missing_ids:
  467. self._log(f"missing tracked orders: {missing_ids}")
  468. self.state["order_ids"] = live_ids
  469. cancelled_obsolete = self._cancel_obsolete_side_orders(live_orders, desired_sides)
  470. if cancelled_obsolete:
  471. live_orders = self._sync_open_orders_state()
  472. live_ids = list(self.state.get("order_ids") or [])
  473. open_order_count = len(live_ids)
  474. if desired_sides != {"buy", "sell"}:
  475. current_sides = {str(order.get("side") or "").lower() for order in live_orders if isinstance(order, dict)}
  476. missing_side = next((side for side in desired_sides if side not in current_sides), None)
  477. if missing_side and self.state.get("center_price"):
  478. self._log(f"adding missing {missing_side} side after trade_sides change, live_sides={sorted(current_sides)} live_ids={live_ids}")
  479. self._place_side_grid(missing_side, float(self.state.get("center_price") or price))
  480. live_orders = self._sync_open_orders_state()
  481. self._log(f"post-add sync: open_order_count={self.state.get('open_order_count', 0)} live_ids={self.state.get('order_ids') or []}")
  482. self.state["last_action"] = f"added {missing_side} side"
  483. return {"action": "add_side", "price": price, "side": missing_side}
  484. if desired_sides == {"buy", "sell"}:
  485. current_sides = {str(order.get("side") or "").lower() for order in live_orders if isinstance(order, dict)}
  486. missing_sides = [side for side in ("buy", "sell") if side not in current_sides]
  487. if missing_sides and self.state.get("center_price"):
  488. for side in missing_sides:
  489. self._log(f"adding missing {side} side after trade_sides change, live_sides={sorted(current_sides)} live_ids={live_ids}")
  490. self._place_side_grid(side, float(self.state.get("center_price") or price))
  491. live_orders = self._sync_open_orders_state()
  492. self._log(f"post-add sync: open_order_count={self.state.get('open_order_count', 0)} live_ids={self.state.get('order_ids') or []}")
  493. self.state["last_action"] = f"added {','.join(missing_sides)} side(s)"
  494. return {"action": "add_side", "price": price, "side": ",".join(missing_sides)}
  495. if live_orders and self.state.get("center_price"):
  496. self._top_up_missing_levels(float(self.state.get("center_price") or price), live_orders)
  497. live_orders = self._sync_open_orders_state()
  498. if not self.state.get("seeded") or not self.state.get("center_price"):
  499. self.state["center_price"] = price
  500. self._place_grid(price)
  501. live_orders = self._sync_open_orders_state()
  502. self.state["seeded"] = True
  503. mode = self._mode()
  504. self._log(f"{'seeded' if mode == 'active' else 'planned'} grid at {price}")
  505. return {"action": "seed" if mode == "active" else "plan", "price": price}
  506. if open_order_count == 0 or (expected_ids and not set(expected_ids).intersection(set(live_ids))):
  507. self._log("no open orders, reseeding grid")
  508. self.state["center_price"] = price
  509. self._place_grid(price)
  510. live_orders = self._sync_open_orders_state()
  511. mode = self._mode()
  512. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  513. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  514. center = float(self.state.get("center_price") or price)
  515. recenter_pct = float(self.config.get("recenter_pct", 0.05) or 0.05)
  516. deviation = abs(price - center) / center if center else 0.0
  517. if deviation >= recenter_pct:
  518. try:
  519. self.context.cancel_all_orders()
  520. except Exception as exc:
  521. self.state["last_error"] = str(exc)
  522. self.state["center_price"] = price
  523. self._place_grid(price)
  524. live_orders = self._sync_open_orders_state()
  525. mode = self._mode()
  526. self.state["last_action"] = "recentered" if mode == "active" else f"{mode} monitor"
  527. self._log(f"recentered grid to {price}")
  528. return {"action": "recenter" if mode == "active" else "plan", "price": price, "deviation": deviation}
  529. mode = self._mode()
  530. self.state["last_action"] = "hold" if mode == "active" else f"{mode} monitor"
  531. self._log(f"hold at {price} dev {deviation:.4f}")
  532. return {"action": "hold" if mode == "active" else "plan", "price": price, "deviation": deviation}
  533. def render(self):
  534. return {
  535. "widgets": [
  536. {"type": "metric", "label": "market", "value": self._market_symbol()},
  537. {"type": "metric", "label": "center", "value": round(float(self.state.get("center_price") or 0.0), 6)},
  538. {"type": "metric", "label": "last price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  539. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  540. {"type": "metric", "label": "orders", "value": len(self.state.get("orders") or [])},
  541. {"type": "metric", "label": "open orders", "value": self.state.get("open_order_count", 0)},
  542. {"type": "metric", "label": "ATR %", "value": round(float(self.state.get("atr_percent") or 0.0), 4)},
  543. {"type": "metric", "label": "grid step %", "value": round(float(self.state.get("grid_step_pct") or 0.0) * 100.0, 4)},
  544. {"type": "metric", "label": "1d", "value": ((self.state.get('regimes') or {}).get('1d') or {}).get('trend', {}).get('state', 'n/a')},
  545. {"type": "metric", "label": "4h", "value": ((self.state.get('regimes') or {}).get('4h') or {}).get('trend', {}).get('state', 'n/a')},
  546. {"type": "metric", "label": "1h", "value": ((self.state.get('regimes') or {}).get('1h') or {}).get('trend', {}).get('state', 'n/a')},
  547. {"type": "metric", "label": "15m", "value": ((self.state.get('regimes') or {}).get('15m') or {}).get('trend', {}).get('state', 'n/a')},
  548. {"type": "metric", "label": f"{self._base_symbol()} avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  549. {"type": "metric", "label": f"{self.context.counter_currency or 'USD'} avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  550. *([
  551. {"type": "metric", "label": "trend guard active", "value": "on"},
  552. {"type": "text", "label": "trend guard reason", "value": "higher-timeframe trend conflict"},
  553. ] if self.state.get("trend_guard_active") else []),
  554. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  555. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  556. ]
  557. }