grid_trader.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. from __future__ import annotations
  2. import time
  3. from datetime import datetime, timezone
  4. from src.trader_mcp.strategy_sizing import suggest_quote_sized_amount
  5. from src.trader_mcp.strategy_sdk import Strategy
  6. from src.trader_mcp.logging_utils import log_event
  7. class Strategy(Strategy):
  8. LABEL = "Grid Trader"
  9. STRATEGY_PROFILE = {
  10. "expects": {
  11. "trend": "none",
  12. "volatility": "low",
  13. "event_risk": "low",
  14. "liquidity": "normal",
  15. },
  16. "avoids": {
  17. "trend": "strong",
  18. "volatility": "expanding",
  19. "event_risk": "high",
  20. "liquidity": "thin",
  21. },
  22. "risk_profile": "medium",
  23. "capabilities": ["mean_reversion", "range_harvesting", "two_sided_inventory"],
  24. "role": "primary",
  25. "inventory_behavior": "balanced",
  26. "requires_rebalance_before_start": False,
  27. "requires_rebalance_before_stop": False,
  28. "safe_when_unbalanced": False,
  29. "can_run_with": ["exposure_protector"],
  30. }
  31. TICK_MINUTES = 0.50
  32. CONFIG_SCHEMA = {
  33. "grid_levels": {"type": "int", "default": 6, "min": 1, "max": 20},
  34. "grid_step_pct": {"type": "float", "default": 0.012, "min": 0.001, "max": 0.1},
  35. "volatility_timeframe": {"type": "string", "default": "1h"},
  36. "volatility_multiplier": {"type": "float", "default": 0.5, "min": 0.0, "max": 10.0},
  37. "grid_step_min_pct": {"type": "float", "default": 0.005, "min": 0.0001, "max": 0.5},
  38. "grid_step_max_pct": {"type": "float", "default": 0.03, "min": 0.0001, "max": 1.0},
  39. "inventory_rebalance_step_factor": {"type": "float", "default": 0.15, "min": 0.0, "max": 0.9},
  40. "order_notional_quote": {"type": "float", "default": 0.0, "min": 0.0},
  41. "max_order_notional_quote": {"type": "float", "default": 0.0, "min": 0.0},
  42. "recenter_pct": {"type": "float", "default": 0.05, "min": 0.0, "max": 0.5},
  43. "recenter_atr_multiplier": {"type": "float", "default": 0.35, "min": 0.0, "max": 10.0},
  44. "recenter_min_pct": {"type": "float", "default": 0.0025, "min": 0.0, "max": 0.5},
  45. "recenter_max_pct": {"type": "float", "default": 0.03, "min": 0.0, "max": 0.5},
  46. "trade_sides": {"type": "string", "default": "both"},
  47. "dust_collect": {"type": "bool", "default": False},
  48. "order_call_delay_ms": {"type": "int", "default": 250, "min": 0, "max": 10000},
  49. "debug_orders": {"type": "bool", "default": True},
  50. }
  51. STATE_SCHEMA = {
  52. "center_price": {"type": "float", "default": 0.0},
  53. "last_price": {"type": "float", "default": 0.0},
  54. "seeded": {"type": "bool", "default": False},
  55. "last_action": {"type": "string", "default": "idle"},
  56. "last_error": {"type": "string", "default": ""},
  57. "cleanup_status": {"type": "string", "default": ""},
  58. "orders": {"type": "list", "default": []},
  59. "order_ids": {"type": "list", "default": []},
  60. "debug_log": {"type": "list", "default": []},
  61. "base_available": {"type": "float", "default": 0.0},
  62. "counter_available": {"type": "float", "default": 0.0},
  63. "grid_step_pct_buy": {"type": "float", "default": 0.0},
  64. "grid_step_pct_sell": {"type": "float", "default": 0.0},
  65. "inventory_skew_side": {"type": "string", "default": "none"},
  66. "inventory_skew_ratio": {"type": "float", "default": 0.5},
  67. "inventory_skew_imbalance": {"type": "float", "default": 0.0},
  68. "inventory_skew_reduction_pct": {"type": "float", "default": 0.0},
  69. "regimes_updated_at": {"type": "string", "default": ""},
  70. "account_snapshot_updated_at": {"type": "string", "default": ""},
  71. "last_balance_log_signature": {"type": "string", "default": ""},
  72. "last_balance_log_at": {"type": "string", "default": ""},
  73. "grid_refresh_pending_until": {"type": "string", "default": ""},
  74. "mismatch_ticks": {"type": "int", "default": 0},
  75. "recovery_cooldown_until": {"type": "string", "default": ""},
  76. }
  77. def init(self):
  78. return {
  79. "center_price": 0.0,
  80. "last_price": 0.0,
  81. "seeded": False,
  82. "last_action": "idle",
  83. "last_error": "",
  84. "cleanup_status": "",
  85. "orders": [],
  86. "order_ids": [],
  87. "debug_log": ["init cancel all orders"],
  88. "base_available": 0.0,
  89. "counter_available": 0.0,
  90. "grid_step_pct_buy": 0.0,
  91. "grid_step_pct_sell": 0.0,
  92. "inventory_skew_side": "none",
  93. "inventory_skew_ratio": 0.5,
  94. "inventory_skew_imbalance": 0.0,
  95. "inventory_skew_reduction_pct": 0.0,
  96. "regimes_updated_at": "",
  97. "account_snapshot_updated_at": "",
  98. "last_balance_log_signature": "",
  99. "last_balance_log_at": "",
  100. "grid_refresh_pending_until": "",
  101. "mismatch_ticks": 0,
  102. "recovery_cooldown_until": "",
  103. }
  104. def _log(self, message: str) -> None:
  105. state = getattr(self, "state", {}) or {}
  106. log = list(state.get("debug_log") or [])
  107. log.append(message)
  108. state["debug_log"] = log[-12:]
  109. self.state = state
  110. log_event("grid", message)
  111. def _log_decision(self, action: str, **fields) -> None:
  112. parts = [action]
  113. for key, value in fields.items():
  114. parts.append(f"{key}={value}")
  115. self._log(", ".join(parts))
  116. def _set_grid_refresh_pause(self, seconds: float = 30.0) -> None:
  117. self.state["grid_refresh_pending_until"] = (datetime.now(timezone.utc).timestamp() + max(seconds, 0.0))
  118. def _grid_refresh_paused(self) -> bool:
  119. try:
  120. until = float(self.state.get("grid_refresh_pending_until") or 0.0)
  121. except Exception:
  122. until = 0.0
  123. return until > datetime.now(timezone.utc).timestamp()
  124. def _recovery_paused(self) -> bool:
  125. try:
  126. until = float(self.state.get("recovery_cooldown_until") or 0.0)
  127. except Exception:
  128. until = 0.0
  129. return until > datetime.now(timezone.utc).timestamp()
  130. def _trip_recovery_pause(self, seconds: float = 30.0) -> None:
  131. self.state["recovery_cooldown_until"] = (datetime.now(timezone.utc).timestamp() + max(seconds, 0.0))
  132. def _tracked_order_id(self, order: dict | object) -> str:
  133. if not isinstance(order, dict):
  134. return ""
  135. for key in ("bitstamp_order_id", "order_id", "id", "client_order_id"):
  136. value = order.get(key)
  137. if value is not None and str(value).strip():
  138. return str(value).strip()
  139. result = order.get("result")
  140. if isinstance(result, dict):
  141. for key in ("bitstamp_order_id", "order_id", "id", "client_order_id"):
  142. value = result.get(key)
  143. if value is not None and str(value).strip():
  144. return str(value).strip()
  145. return ""
  146. def _drop_tracked_orders(self, order_ids: list[str] | set[str]) -> int:
  147. drop_ids = {str(order_id).strip() for order_id in (order_ids or []) if str(order_id).strip()}
  148. if not drop_ids:
  149. return 0
  150. tracked_orders = list(self.state.get("orders") or [])
  151. tracked_ids = [str(order_id).strip() for order_id in (self.state.get("order_ids") or []) if str(order_id).strip()]
  152. kept_orders = [
  153. order for order in tracked_orders
  154. if self._tracked_order_id(order) not in drop_ids
  155. ]
  156. kept_ids = [order_id for order_id in tracked_ids if order_id not in drop_ids]
  157. removed = len(tracked_ids) - len(kept_ids)
  158. self.state["orders"] = kept_orders
  159. self.state["order_ids"] = kept_ids
  160. self.state["open_order_count"] = len(kept_ids)
  161. return max(removed, 0)
  162. def _cancel_all_orders_conclusive(self, failure_prefix: str) -> bool:
  163. strict_cancel = getattr(self.context, "cancel_all_orders_confirmed", None)
  164. if callable(strict_cancel):
  165. result = strict_cancel()
  166. cancelled_order_ids = result.get("cancelled_order_ids") or []
  167. removed = self._drop_tracked_orders(cancelled_order_ids)
  168. cleanup_status = str(result.get("cleanup_status") or ("cleanup_confirmed" if bool(result.get("conclusive")) else "cleanup_partial"))
  169. self.state["cleanup_status"] = cleanup_status
  170. if removed > 0:
  171. self._log(f"cleanup removed tracked orders: ids={cancelled_order_ids}")
  172. if bool(result.get("conclusive")):
  173. return True
  174. error = str(result.get("error") or "cancel-all inconclusive")
  175. else:
  176. try:
  177. self.context.cancel_all_orders()
  178. self.state["cleanup_status"] = "cleanup_confirmed"
  179. return True
  180. except Exception as exc:
  181. self.state["cleanup_status"] = "cleanup_failed"
  182. error = str(exc)
  183. self.state["last_error"] = error
  184. self._log(f"{failure_prefix}: {error}")
  185. return False
  186. def _recover_grid(self, price: float) -> None:
  187. self._log(f"recovery mode: cancel all and rebuild from {price}")
  188. if not self._cancel_all_orders_conclusive("recovery cancel-all failed"):
  189. self.state["last_action"] = "recovery cleanup pending"
  190. return
  191. self.state["orders"] = []
  192. self.state["order_ids"] = []
  193. self.state["open_order_count"] = 0
  194. self.state["center_price"] = price
  195. self.state["seeded"] = True
  196. self._place_grid(price)
  197. self._sync_open_orders_state()
  198. self.state["mismatch_ticks"] = 0
  199. self._trip_recovery_pause()
  200. def _order_count_mismatch(self, tracked_ids: list[str], live_orders: list[dict]) -> bool:
  201. 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 if isinstance(order, dict)]
  202. live_ids = [oid for oid in live_ids if oid]
  203. if len(live_ids) != len([oid for oid in tracked_ids if oid]):
  204. return True
  205. return False
  206. def _base_symbol(self) -> str:
  207. return (self.context.base_currency or self.context.market_symbol or "XRP").split("/")[0].upper()
  208. def _market_symbol(self) -> str:
  209. return self.context.market_symbol or f"{self._base_symbol().lower()}usd"
  210. def _live_fee_rates(self) -> tuple[float, float]:
  211. try:
  212. payload = self.context.get_fee_rates(self._market_symbol())
  213. maker = float(payload.get("maker") or 0.0)
  214. taker = float(payload.get("taker") or 0.0)
  215. return maker, taker
  216. except Exception as exc:
  217. self._log(f"fee lookup failed: {exc}")
  218. return 0.0, 0.0
  219. def _live_fee_rate(self) -> float:
  220. _maker, taker = self._live_fee_rates()
  221. return taker
  222. def _mode(self) -> str:
  223. return getattr(self.context, "mode", "active") or "active"
  224. def apply_policy(self):
  225. policy = super().apply_policy()
  226. risk = str(policy.get("risk_posture") or "normal").lower()
  227. priority = str(policy.get("priority") or "normal").lower()
  228. step_map = {"cautious": 0.008, "normal": 0.012, "assertive": 0.018}
  229. recenter_map = {"cautious": 0.035, "normal": 0.05, "assertive": 0.07}
  230. levels_map = {"cautious": 4, "normal": 6, "assertive": 8}
  231. delay_map = {"cautious": 500, "normal": 250, "assertive": 120}
  232. if priority in {"low", "background"}:
  233. risk = "cautious"
  234. elif priority in {"high", "urgent"}:
  235. risk = "assertive"
  236. self.config["grid_step_pct"] = step_map.get(risk, 0.012)
  237. self.config["recenter_pct"] = recenter_map.get(risk, 0.05)
  238. if self.config.get("grid_levels") in {None, "", 0}:
  239. self.config["grid_levels"] = levels_map.get(risk, 6)
  240. else:
  241. try:
  242. self.config["grid_levels"] = max(int(self.config.get("grid_levels") or 0), 1)
  243. except Exception:
  244. self.config["grid_levels"] = levels_map.get(risk, 6)
  245. self.config["order_call_delay_ms"] = delay_map.get(risk, 250)
  246. self.state["policy_derived"] = {
  247. "grid_step_pct": self.config["grid_step_pct"],
  248. "recenter_pct": self.config["recenter_pct"],
  249. "grid_levels": self.config["grid_levels"],
  250. "order_call_delay_ms": self.config["order_call_delay_ms"],
  251. }
  252. return policy
  253. def _price(self) -> float:
  254. payload = self.context.get_price(self._base_symbol())
  255. return float(payload.get("price") or 0.0)
  256. def _regime_snapshot(self) -> dict:
  257. timeframes = ["1d", "4h", "1h", "15m"]
  258. snapshot = {}
  259. for tf in timeframes:
  260. try:
  261. snapshot[tf] = self.context.get_regime(self._base_symbol(), tf)
  262. except Exception as exc:
  263. snapshot[tf] = {"error": str(exc)}
  264. return snapshot
  265. def _refresh_regimes(self) -> None:
  266. self.state["regimes"] = self._regime_snapshot()
  267. self.state["regimes_updated_at"] = datetime.now(timezone.utc).isoformat()
  268. def _recenter_threshold_pct(self) -> float:
  269. base_threshold = float(self.config.get("recenter_pct", 0.05) or 0.05)
  270. atr_multiplier = float(self.config.get("recenter_atr_multiplier", 0.35) or 0.0)
  271. min_threshold = float(self.config.get("recenter_min_pct", 0.0025) or 0.0)
  272. max_threshold = float(self.config.get("recenter_max_pct", 0.03) or 1.0)
  273. try:
  274. tf = str(self.config.get("volatility_timeframe", "1h") or "1h")
  275. regime = self.context.get_regime(self._base_symbol(), tf)
  276. short_regime = self.context.get_regime(self._base_symbol(), "15m")
  277. atr_pct = float((regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  278. short_atr_pct = float((short_regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  279. atr_pct = max(atr_pct, short_atr_pct)
  280. except Exception:
  281. atr_pct = 0.0
  282. threshold = (atr_pct / 100.0) * atr_multiplier if atr_pct > 0 else base_threshold
  283. threshold = max(threshold, min_threshold)
  284. threshold = min(threshold, max_threshold)
  285. self.state["recenter_pct_live"] = threshold
  286. self.state["recenter_atr_percent"] = atr_pct
  287. return threshold
  288. def _grid_step_pct(self) -> float:
  289. base_step = float(self.config.get("grid_step_pct", 0.012) or 0.012)
  290. tf = str(self.config.get("volatility_timeframe", "1h") or "1h")
  291. multiplier = float(self.config.get("volatility_multiplier", 0.5) or 0.0)
  292. min_step = float(self.config.get("grid_step_min_pct", 0.005) or 0.0)
  293. max_step = float(self.config.get("grid_step_max_pct", 0.03) or 1.0)
  294. try:
  295. regime = self.context.get_regime(self._base_symbol(), tf)
  296. short_regime = self.context.get_regime(self._base_symbol(), "15m")
  297. tf_atr_pct = float((regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  298. atr_pct = float((regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  299. short_atr_pct = float((short_regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  300. atr_pct = max(atr_pct, short_atr_pct)
  301. self.state["regimes"] = self._regime_snapshot()
  302. except Exception as exc:
  303. self._log(f"regime fetch failed: {exc}")
  304. tf_atr_pct = 0.0
  305. atr_pct = 0.0
  306. short_atr_pct = 0.0
  307. adaptive = (atr_pct / 100.0) * multiplier if atr_pct > 0 else base_step
  308. step = adaptive if atr_pct > 0 else base_step
  309. step = max(step, min_step)
  310. step = min(step, max_step)
  311. self.state["grid_step_pct"] = step
  312. self.state["atr_percent_tf"] = tf_atr_pct
  313. self.state["atr_percent_15m"] = short_atr_pct
  314. self.state["atr_percent"] = atr_pct
  315. return step
  316. def _inventory_rebalance_profile(
  317. self,
  318. price: float,
  319. *,
  320. base_total: float | None = None,
  321. quote_total: float | None = None,
  322. ) -> dict[str, float | str]:
  323. ratio_price = price if price > 0 else float(self.state.get("last_price") or self.state.get("center_price") or 1.0)
  324. if base_total is None or quote_total is None:
  325. live_orders = list(self.state.get("orders") or [])
  326. reserved_quote = sum(
  327. float(order.get("price") or 0.0) * float(order.get("amount") or 0.0)
  328. for order in live_orders
  329. if isinstance(order, dict) and str(order.get("side") or "").lower() == "buy"
  330. )
  331. reserved_base = sum(
  332. float(order.get("amount") or 0.0)
  333. for order in live_orders
  334. if isinstance(order, dict) and str(order.get("side") or "").lower() == "sell"
  335. )
  336. if base_total is None:
  337. base_total = max(float(self.state.get("base_available") or 0.0), 0.0) + reserved_base
  338. if quote_total is None:
  339. quote_total = max(float(self.state.get("counter_available") or 0.0), 0.0) + reserved_quote
  340. # Rebalance bias must see the whole wallet, not only the free slice.
  341. base_value = max(float(base_total or 0.0), 0.0) * ratio_price
  342. counter_value = max(float(quote_total or 0.0), 0.0)
  343. total = base_value + counter_value
  344. ratio = base_value / total if total > 0 else 0.5
  345. imbalance = min(abs(ratio - 0.5) * 2.0, 1.0)
  346. factor = float(self.config.get("inventory_rebalance_step_factor", 0.15) or 0.0)
  347. factor = min(max(factor, 0.0), 0.9)
  348. favored_side = "sell" if ratio > 0.5 else "buy" if ratio < 0.5 else "none"
  349. reduction = factor * imbalance if favored_side in {"buy", "sell"} else 0.0
  350. self.state["inventory_skew_side"] = favored_side
  351. self.state["inventory_skew_ratio"] = ratio
  352. self.state["inventory_skew_imbalance"] = imbalance
  353. self.state["inventory_skew_reduction_pct"] = reduction
  354. return {
  355. "ratio": ratio,
  356. "imbalance": imbalance,
  357. "favored_side": favored_side,
  358. "reduction": reduction,
  359. }
  360. def _effective_grid_steps(
  361. self,
  362. price: float,
  363. *,
  364. base_total: float | None = None,
  365. quote_total: float | None = None,
  366. ) -> dict[str, float | str]:
  367. base_step = float(self.state.get("grid_step_pct") or self._grid_step_pct())
  368. min_step = float(self.config.get("grid_step_min_pct", 0.005) or 0.0)
  369. profile = self._inventory_rebalance_profile(price, base_total=base_total, quote_total=quote_total)
  370. favored_side = str(profile.get("favored_side") or "none")
  371. reduction = float(profile.get("reduction") or 0.0)
  372. buy_step = base_step
  373. sell_step = base_step
  374. if favored_side == "buy":
  375. buy_step = max(base_step * (1.0 - reduction), min_step)
  376. elif favored_side == "sell":
  377. sell_step = max(base_step * (1.0 - reduction), min_step)
  378. self.state["grid_step_pct_buy"] = buy_step
  379. self.state["grid_step_pct_sell"] = sell_step
  380. return {
  381. "base": base_step,
  382. "buy": buy_step,
  383. "sell": sell_step,
  384. "favored_side": favored_side,
  385. "reduction": reduction,
  386. "ratio": float(profile.get("ratio") or 0.5),
  387. "imbalance": float(profile.get("imbalance") or 0.0),
  388. }
  389. def _config_warning(self) -> str | None:
  390. recenter_pct = float(self.state.get("recenter_pct_live") or self._recenter_threshold_pct())
  391. steps = self._effective_grid_steps(float(self.state.get("last_price") or self.state.get("center_price") or 0.0))
  392. grid_step_pct = min(float(steps.get("buy") or 0.0), float(steps.get("sell") or 0.0))
  393. if grid_step_pct <= 0:
  394. return None
  395. ratio = recenter_pct / grid_step_pct
  396. # If the recenter threshold is too close to the first step, the grid
  397. # can keep rebuilding before it has a fair chance to trade.
  398. if ratio <= 1.0:
  399. return f"warning: recenter threshold ({recenter_pct:.4f}) is <= grid step ({grid_step_pct:.4f}), it may recenter before trading"
  400. if ratio < 1.5:
  401. return f"warning: recenter threshold ({recenter_pct:.4f}) is only {ratio:.2f}x the grid step ({grid_step_pct:.4f}), consider widening it"
  402. return None
  403. def _inventory_ratio(self, price: float) -> float:
  404. base_value = float(self.state.get("base_available") or 0.0) * price
  405. counter_value = float(self.state.get("counter_available") or 0.0)
  406. total = base_value + counter_value
  407. if total <= 0:
  408. return 0.5
  409. return base_value / total
  410. def _supervision(self) -> dict:
  411. price = float(self.state.get("last_price") or 0.0)
  412. ratio = self._inventory_ratio(price if price > 0 else 1.0)
  413. step_profile = self._effective_grid_steps(price)
  414. last_error = str(self.state.get("last_error") or "")
  415. config_warning = self._config_warning()
  416. regime_1h = (((self.state.get("regimes") or {}).get("1h") or {}).get("trend") or {}).get("state")
  417. center_price = float(self.state.get("center_price") or self.state.get("last_price") or 0.0)
  418. if ratio >= 0.88:
  419. pressure = "base_side_depleted"
  420. elif ratio <= 0.12:
  421. pressure = "quote_side_depleted"
  422. elif ratio >= 0.65:
  423. pressure = "base_heavy"
  424. elif ratio <= 0.35:
  425. pressure = "quote_heavy"
  426. else:
  427. pressure = "balanced"
  428. if price > 0 and center_price > 0:
  429. if price > center_price:
  430. market_bias = "bullish"
  431. adverse_side = "sell"
  432. elif price < center_price:
  433. market_bias = "bearish"
  434. adverse_side = "buy"
  435. else:
  436. market_bias = "flat"
  437. adverse_side = "unknown"
  438. else:
  439. market_bias = "unknown"
  440. adverse_side = "unknown"
  441. open_orders = self.state.get("orders") or []
  442. order_distribution = {"buy": {"count": 0, "notional_quote": 0.0}, "sell": {"count": 0, "notional_quote": 0.0}}
  443. adverse_side_nearest_distance_pct = None
  444. for order in open_orders:
  445. if not isinstance(order, dict):
  446. continue
  447. side = str(order.get("side") or "").lower()
  448. if side not in order_distribution:
  449. continue
  450. try:
  451. order_price = float(order.get("price") or 0.0)
  452. amount = float(order.get("amount") or order.get("amount_remaining") or 0.0)
  453. except Exception:
  454. continue
  455. if order_price <= 0 or amount <= 0:
  456. continue
  457. order_distribution[side]["count"] += 1
  458. order_distribution[side]["notional_quote"] += amount * order_price
  459. if side == adverse_side and price > 0:
  460. distance_pct = abs(order_price - price) / price * 100.0
  461. if adverse_side_nearest_distance_pct is None or distance_pct < adverse_side_nearest_distance_pct:
  462. adverse_side_nearest_distance_pct = distance_pct
  463. adverse_count = int(order_distribution.get(adverse_side, {}).get("count") or 0) if adverse_side in order_distribution else 0
  464. adverse_notional = float(order_distribution.get(adverse_side, {}).get("notional_quote") or 0.0) if adverse_side in order_distribution else 0.0
  465. concerns = []
  466. if adverse_side in {"buy", "sell"} and adverse_count > 0:
  467. concerns.append(f"{adverse_side} ladder exposed to {market_bias} drift")
  468. if pressure in {"base_side_depleted", "quote_side_depleted"}:
  469. concerns.append(f"inventory pressure={pressure}")
  470. if config_warning:
  471. concerns.append(config_warning)
  472. side_capacity = {
  473. "buy": pressure not in {"quote_side_depleted"},
  474. "sell": pressure not in {"base_side_depleted"},
  475. }
  476. return {
  477. "health": "degraded" if last_error or config_warning else "healthy",
  478. "degraded": bool(last_error or config_warning),
  479. "inventory_pressure": pressure,
  480. "inventory_ratio": round(ratio, 4),
  481. "inventory_rebalance_side": step_profile.get("favored_side", "none"),
  482. "inventory_rebalance_reduction_pct": round(float(step_profile.get("reduction") or 0.0) * 100.0, 4),
  483. "grid_step_pct": {
  484. "base": round(float(step_profile.get("base") or 0.0), 6),
  485. "buy": round(float(step_profile.get("buy") or 0.0), 6),
  486. "sell": round(float(step_profile.get("sell") or 0.0), 6),
  487. },
  488. "capacity_available": pressure == "balanced",
  489. "side_capacity": side_capacity,
  490. "market_bias": market_bias,
  491. "adverse_side": adverse_side,
  492. "adverse_side_open_order_count": adverse_count,
  493. "adverse_side_open_order_notional_quote": round(adverse_notional, 4),
  494. "adverse_side_nearest_distance_pct": round(adverse_side_nearest_distance_pct, 4) if adverse_side_nearest_distance_pct is not None else None,
  495. "open_order_distribution": order_distribution,
  496. "concerns": concerns,
  497. "last_reason": last_error or config_warning or f"base_ratio={ratio:.3f}, trend_1h={regime_1h or 'unknown'}",
  498. }
  499. def _available_balance(self, asset_code: str) -> float:
  500. try:
  501. info = self.context.get_account_info()
  502. except Exception as exc:
  503. self._log(f"account info failed: {exc}")
  504. # A failed balance read makes this tick unsuitable for shape decisions.
  505. self.state["balance_shape_inconclusive"] = True
  506. return 0.0
  507. balances = info.get("balances") if isinstance(info, dict) else []
  508. if not isinstance(balances, list):
  509. self.state["balance_shape_inconclusive"] = True
  510. return 0.0
  511. wanted = str(asset_code or "").upper()
  512. for balance in balances:
  513. if not isinstance(balance, dict):
  514. continue
  515. if str(balance.get("asset_code") or "").upper() != wanted:
  516. continue
  517. try:
  518. return float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  519. except Exception:
  520. self.state["balance_shape_inconclusive"] = True
  521. return 0.0
  522. self.state["balance_shape_inconclusive"] = True
  523. return 0.0
  524. def _refresh_balance_snapshot(self) -> bool:
  525. try:
  526. info = self.context.get_account_info()
  527. except Exception as exc:
  528. self._log(f"balance refresh failed: {exc}")
  529. self.state["balance_shape_inconclusive"] = True
  530. return False
  531. balances = info.get("balances") if isinstance(info, dict) else []
  532. if not isinstance(balances, list):
  533. self.state["balance_shape_inconclusive"] = True
  534. return False
  535. base = self._base_symbol()
  536. quote = self.context.counter_currency or "USD"
  537. for balance in balances:
  538. if not isinstance(balance, dict):
  539. continue
  540. asset = str(balance.get("asset_code") or "").upper()
  541. try:
  542. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  543. except Exception:
  544. self.state["balance_shape_inconclusive"] = True
  545. continue
  546. if asset == base:
  547. self.state["base_available"] = available
  548. if asset == str(quote).upper():
  549. self.state["counter_available"] = available
  550. self.state["account_snapshot_updated_at"] = datetime.now(timezone.utc).isoformat()
  551. signature = f"{base}:{self.state.get('base_available', 0.0):.8f}|{quote}:{self.state.get('counter_available', 0.0):.8f}"
  552. last_signature = str(self.state.get("last_balance_log_signature") or "")
  553. last_logged_at = str(self.state.get("last_balance_log_at") or "")
  554. now_iso = self.state["account_snapshot_updated_at"]
  555. should_log = signature != last_signature or not last_logged_at
  556. if not should_log:
  557. try:
  558. from datetime import datetime as _dt
  559. elapsed = (_dt.fromisoformat(now_iso) - _dt.fromisoformat(last_logged_at)).total_seconds()
  560. should_log = elapsed >= 60
  561. except Exception:
  562. should_log = True
  563. if should_log:
  564. self.state["last_balance_log_signature"] = signature
  565. self.state["last_balance_log_at"] = now_iso
  566. self._log_decision(
  567. "balance snapshot",
  568. base=base,
  569. base_available=f"{self.state.get('base_available', 0.0):.6g}",
  570. quote=quote,
  571. quote_available=f"{self.state.get('counter_available', 0.0):.6g}",
  572. updated_at=now_iso,
  573. )
  574. return True
  575. def _side_allowed(self, side: str) -> bool:
  576. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  577. if selected == "both":
  578. return True
  579. return selected == side
  580. def _desired_sides(self) -> set[str]:
  581. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  582. if selected == "both":
  583. return {"buy", "sell"}
  584. if selected in {"buy", "sell"}:
  585. return {selected}
  586. return {"buy", "sell"}
  587. def _suggest_amount(
  588. self,
  589. side: str,
  590. price: float,
  591. levels: int,
  592. min_notional: float,
  593. *,
  594. available_balances: dict[str, float] | None = None,
  595. ) -> float:
  596. return suggest_quote_sized_amount(
  597. self.context,
  598. side=side,
  599. price=price,
  600. levels=levels,
  601. min_notional=min_notional,
  602. fee_rate=self._live_fee_rate(),
  603. order_notional_quote=float(self.config.get("order_notional_quote") or self.config.get("order_size") or 0.0),
  604. max_order_notional_quote=float(self.config.get("max_order_notional_quote") or self.config.get("max_notional_per_order") or 0.0),
  605. dust_collect=bool(self.config.get("dust_collect", False)),
  606. order_size=0.0,
  607. available_balances=available_balances,
  608. )
  609. def _grid_extreme_price(self, center: float, side: str, levels: int) -> float:
  610. step_profile = self._effective_grid_steps(center)
  611. step = float(step_profile.get(side) or step_profile.get("base") or 0.0)
  612. if center <= 0 or levels <= 0 or step <= 0:
  613. return center
  614. if side == "buy":
  615. return round(center * (1 - (step * levels)), 8)
  616. return round(center * (1 + (step * levels)), 8)
  617. def _resource_total_for_side(self, side: str, base_total: float, quote_total: float) -> float:
  618. if side == "buy":
  619. return max(float(quote_total or 0.0), 0.0)
  620. return max(float(base_total or 0.0), 0.0)
  621. def _resource_cost_for_order(self, side: str, amount: float, price: float, fee_rate: float) -> float:
  622. if side == "buy":
  623. return max(amount, 0.0) * max(price, 0.0) * (1.0 + max(fee_rate, 0.0))
  624. return max(amount, 0.0)
  625. def _inventory_totals_from_live_orders(self, live_orders: list[dict]) -> tuple[float, float]:
  626. reserved_quote = sum(
  627. float(order.get("price") or 0.0) * float(order.get("amount") or 0.0)
  628. for order in live_orders
  629. if isinstance(order, dict) and str(order.get("side") or "").lower() == "buy"
  630. )
  631. reserved_base = sum(
  632. float(order.get("amount") or 0.0)
  633. for order in live_orders
  634. if isinstance(order, dict) and str(order.get("side") or "").lower() == "sell"
  635. )
  636. base_total = max(float(self.state.get("base_available") or 0.0), 0.0) + reserved_base
  637. quote_total = max(float(self.state.get("counter_available") or 0.0), 0.0) + reserved_quote
  638. return base_total, quote_total
  639. def _planned_side_orders(
  640. self,
  641. side: str,
  642. center: float,
  643. expected_levels: int,
  644. min_notional: float,
  645. fee_rate: float,
  646. *,
  647. step: float,
  648. base_total: float,
  649. quote_total: float,
  650. ) -> dict:
  651. empty = {"amount": 0.0, "orders": [], "skipped": [], "valid": True}
  652. if not self._side_allowed(side):
  653. return empty
  654. if expected_levels <= 0 or center <= 0 or step <= 0:
  655. return empty
  656. base_symbol = self._base_symbol()
  657. quote_symbol = str(self.context.counter_currency or "USD").upper()
  658. balances = {
  659. base_symbol: max(float(base_total or 0.0), 0.0),
  660. quote_symbol: max(float(quote_total or 0.0), 0.0),
  661. }
  662. spendable_total = self._resource_total_for_side(side, base_total, quote_total) * 0.995
  663. total_cost = 0.0
  664. planned_orders = []
  665. skipped = []
  666. # Walk the ladder from the inside out and size each level at its own
  667. # price. That lets the planner use the maximum feasible number of
  668. # levels under the current funds and per-order notional constraints.
  669. for level_index in range(1, expected_levels + 1):
  670. price = round(center * (1 - (step * level_index)) if side == "buy" else center * (1 + (step * level_index)), 8)
  671. if price <= 0:
  672. break
  673. amount = self._suggest_amount(
  674. side,
  675. price,
  676. max(expected_levels, 1),
  677. min_notional,
  678. available_balances=balances,
  679. )
  680. if amount <= 0:
  681. break
  682. min_size = (min_notional / price) if min_notional > 0 else 0.0
  683. if amount < min_size:
  684. skipped.append({"level": level_index, "reason": "below minimum size", "price": price})
  685. break
  686. cost = self._resource_cost_for_order(side, amount, price, fee_rate)
  687. if total_cost + cost > spendable_total + 1e-9:
  688. break
  689. total_cost += cost
  690. planned_orders.append({"side": side, "price": price, "amount": amount, "level": level_index})
  691. return {
  692. "amount": planned_orders[0]["amount"] if planned_orders else 0.0,
  693. "orders": planned_orders,
  694. "skipped": skipped,
  695. "valid": True,
  696. }
  697. def _plan_grid(self, center: float, *, base_total: float | None = None, quote_total: float | None = None) -> dict:
  698. center = float(center or 0.0)
  699. levels = int(self.config.get("grid_levels", 6) or 6)
  700. min_notional = float(self.context.minimum_order_value or 0.0)
  701. fee_rate = self._live_fee_rate()
  702. # One planner feeds both seeding and shape checking, so they never
  703. # invent different notions of the "correct" grid.
  704. step_profile = self._effective_grid_steps(center, base_total=base_total, quote_total=quote_total)
  705. buy_step = float(step_profile.get("buy") or step_profile.get("base") or 0.0)
  706. sell_step = float(step_profile.get("sell") or step_profile.get("base") or 0.0)
  707. base_total = max(float(self.state.get("base_available") if base_total is None else base_total) or 0.0, 0.0)
  708. quote_total = max(float(self.state.get("counter_available") if quote_total is None else quote_total) or 0.0, 0.0)
  709. buy_plan = self._planned_side_orders(
  710. "buy",
  711. center,
  712. levels,
  713. min_notional,
  714. fee_rate,
  715. step=buy_step,
  716. base_total=base_total,
  717. quote_total=quote_total,
  718. )
  719. sell_plan = self._planned_side_orders(
  720. "sell",
  721. center,
  722. levels,
  723. min_notional,
  724. fee_rate,
  725. step=sell_step,
  726. base_total=base_total,
  727. quote_total=quote_total,
  728. )
  729. orders = [*buy_plan["orders"], *sell_plan["orders"]]
  730. return {
  731. "center": center,
  732. "buy_orders": buy_plan["orders"],
  733. "sell_orders": sell_plan["orders"],
  734. "orders": orders,
  735. "buy_skipped": buy_plan["skipped"],
  736. "sell_skipped": sell_plan["skipped"],
  737. "counts": {"buy": len(buy_plan["orders"]), "sell": len(sell_plan["orders"])},
  738. }
  739. def _place_grid(self, center: float) -> None:
  740. center = self._maybe_refresh_center(center)
  741. mode = self._mode()
  742. market = self._market_symbol()
  743. orders = []
  744. order_ids = []
  745. def _capture_order_id(result):
  746. if isinstance(result, dict):
  747. return result.get("bitstamp_order_id") or result.get("order_id") or result.get("id") or result.get("client_order_id")
  748. return None
  749. plan = self._plan_grid(center)
  750. for side, skipped in (("buy", plan.get("buy_skipped") or []), ("sell", plan.get("sell_skipped") or [])):
  751. for skipped_level in skipped:
  752. self._log(f"seed level {skipped_level.get('level')} {side} skipped: {skipped_level.get('reason')}")
  753. for planned_order in plan.get("orders") or []:
  754. side = str(planned_order.get("side") or "").lower()
  755. level = int(planned_order.get("level") or 0)
  756. price = float(planned_order.get("price") or 0.0)
  757. amount = float(planned_order.get("amount") or 0.0)
  758. if price <= 0 or amount <= 0:
  759. continue
  760. if mode != "active":
  761. orders.append({"side": side, "price": price, "amount": amount, "result": {"simulated": True}})
  762. self._log(f"plan level {level}: {side} {price} amount {amount:.6g}")
  763. continue
  764. try:
  765. result = self.context.place_order(side=side, order_type="limit", amount=amount, price=price, market=market)
  766. orders.append({"side": side, "price": price, "amount": amount, "result": result})
  767. order_id = _capture_order_id(result)
  768. if order_id is not None:
  769. order_ids.append(str(order_id))
  770. self._log(f"seed level {level}: {side} {price} amount {amount:.6g}")
  771. delay = max(int(self.config.get("order_call_delay_ms", 250) or 0), 0) / 1000.0
  772. if delay > 0:
  773. time.sleep(delay)
  774. self._refresh_balance_snapshot()
  775. except Exception as exc: # best effort for first draft
  776. self.state["last_error"] = str(exc)
  777. self._log(f"seed level {level} {side} failed: {exc}")
  778. self.state["orders"] = orders
  779. self.state["order_ids"] = order_ids
  780. self.state["last_action"] = "seeded grid"
  781. self._set_grid_refresh_pause()
  782. def _current_market_anchor(self, fallback: float = 0.0) -> float:
  783. try:
  784. live_price = float(self._price() or 0.0)
  785. except Exception as exc:
  786. self._log(f"live price refresh failed during rebuild: {exc}")
  787. live_price = 0.0
  788. return live_price if live_price > 0 else fallback
  789. def _recenter_and_rebuild_from_fill(self, fill_price: float, market_price: float = 0.0) -> None:
  790. """Treat a fill as a forced re-anchor and rebuild from the latest market price."""
  791. anchor_price = self._current_market_anchor(market_price or fill_price)
  792. if anchor_price <= 0:
  793. return
  794. self._log(f"fill rebuild anchor resolved: fill={fill_price} market={anchor_price}")
  795. self._recenter_and_rebuild_from_price(anchor_price, "fill rebuild")
  796. def _recenter_and_rebuild_from_price(self, price: float, reason: str) -> None:
  797. if price <= 0:
  798. return
  799. current = float(self.state.get("center_price") or 0.0)
  800. self._log(f"{reason}: recenter from {current} to {price}")
  801. if not self._cancel_all_orders_conclusive(f"{reason} cancel-all failed"):
  802. self.state["last_action"] = f"{reason} cleanup pending"
  803. return
  804. # Give the exchange a moment to release balance before we rebuild.
  805. time.sleep(3.0)
  806. self._refresh_balance_snapshot()
  807. self.state["center_price"] = price
  808. self.state["seeded"] = True
  809. self._place_grid(price)
  810. # Use the freshly placed live orders as the tracked snapshot so the
  811. # next tick compares against the rebuilt grid, not the pre-rebuild set.
  812. self._sync_open_orders_state()
  813. self._refresh_balance_snapshot()
  814. self._set_grid_refresh_pause()
  815. def on_stop(self):
  816. self._log("stopping: cancel all open orders")
  817. if self._cancel_all_orders_conclusive("stop cancel-all failed"):
  818. self.state["orders"] = []
  819. self.state["order_ids"] = []
  820. self.state["open_order_count"] = 0
  821. self.state["last_action"] = "stopped"
  822. else:
  823. self.state["last_action"] = "stop cleanup pending"
  824. def _maybe_refresh_center(self, price: float) -> float:
  825. if price <= 0:
  826. return price
  827. current = float(self.state.get("center_price") or 0.0)
  828. if current <= 0:
  829. self.state["center_price"] = price
  830. return price
  831. deviation = abs(price - current) / current if current else 0.0
  832. threshold = self._recenter_threshold_pct()
  833. if deviation >= threshold:
  834. self._log(f"recenter anchor from {current} to {price} dev={deviation:.4f} threshold={threshold:.4f}")
  835. self.state["center_price"] = price
  836. return price
  837. return current
  838. def _sync_open_orders_state(self) -> list[dict]:
  839. try:
  840. open_orders = self.context.get_open_orders()
  841. except Exception as exc:
  842. self.state["last_error"] = str(exc)
  843. self._log(f"open orders sync failed: {exc}")
  844. return []
  845. if not isinstance(open_orders, list):
  846. open_orders = []
  847. live_orders = [order for order in open_orders if isinstance(order, dict)]
  848. 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]
  849. live_ids = [oid for oid in live_ids if oid]
  850. live_sides = [str(order.get("side") or "").lower() for order in live_orders]
  851. self.state["orders"] = live_orders
  852. self.state["order_ids"] = live_ids
  853. self.state["open_order_count"] = len(live_ids)
  854. self._log(f"sync live orders: count={len(live_ids)} sides={live_sides} ids={live_ids}")
  855. return live_orders
  856. def _cancel_orders(self, order_ids) -> None:
  857. for order_id in order_ids or []:
  858. self._log(f"dropping stale order {order_id} from state")
  859. def _reconcile_after_sync(self, previous_orders: list[dict], live_orders: list[dict], desired_sides: set[str], price: float) -> tuple[list[dict], list[str], int]:
  860. live_ids = list(self.state.get("order_ids") or [])
  861. open_order_count = len(live_ids)
  862. if self._mode() != "active":
  863. return live_orders, live_ids, open_order_count
  864. previous_ids = {
  865. str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  866. for order in previous_orders
  867. if isinstance(order, dict)
  868. }
  869. current_ids = {
  870. str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  871. for order in live_orders
  872. if isinstance(order, dict)
  873. }
  874. vanished_orders = [
  875. order
  876. for order in previous_orders
  877. if isinstance(order, dict)
  878. and str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "") in (previous_ids - current_ids)
  879. ]
  880. if vanished_orders and not self._grid_refresh_paused():
  881. for order in vanished_orders:
  882. order_id = str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  883. if not order_id:
  884. continue
  885. try:
  886. payload = self.context.query_order(order_id)
  887. except Exception as exc:
  888. self._log(f"order status query failed for {order_id}: {exc}")
  889. continue
  890. raw = payload.get("raw") if isinstance(payload, dict) else {}
  891. if not isinstance(raw, dict):
  892. raw = {}
  893. status = str(payload.get("status") or raw.get("status") or order.get("status") or "").strip().lower()
  894. if status in {"finished", "filled", "closed"}:
  895. fill_price = 0.0
  896. for candidate in (raw.get("price"), order.get("price"), price):
  897. try:
  898. fill_price = float(candidate or 0.0)
  899. except Exception:
  900. fill_price = 0.0
  901. if fill_price > 0:
  902. break
  903. if fill_price > 0:
  904. self._log(f"filled order {order_id} detected via exec status={status}, recentering from fill={fill_price} market={price}")
  905. self._recenter_and_rebuild_from_fill(fill_price, price)
  906. live_orders = self._sync_open_orders_state()
  907. live_ids = list(self.state.get("order_ids") or [])
  908. open_order_count = len(live_ids)
  909. return live_orders, live_ids, open_order_count
  910. if status in {"cancelled", "expired", "missing"}:
  911. self._log(f"vanished order {order_id} resolved as {status}")
  912. continue
  913. return live_orders, live_ids, open_order_count
  914. def on_tick(self, tick):
  915. previous_orders = list(self.state.get("orders") or [])
  916. tracked_ids_before_sync = list(self.state.get("order_ids") or [])
  917. rebuild_done = False
  918. self.state["balance_shape_inconclusive"] = False
  919. balance_refresh_ok = self._refresh_balance_snapshot()
  920. price = self._price()
  921. self.state["last_price"] = price
  922. self.state["last_error"] = ""
  923. self._refresh_regimes()
  924. try:
  925. live_orders = self._sync_open_orders_state()
  926. live_ids = list(self.state.get("order_ids") or [])
  927. open_order_count = len(live_ids)
  928. expected_ids = [str(oid) for oid in tracked_ids_before_sync if oid]
  929. stale_ids = []
  930. missing_ids = []
  931. except Exception as exc:
  932. open_order_count = -1
  933. live_orders = []
  934. live_ids = []
  935. expected_ids = []
  936. stale_ids = []
  937. missing_ids = []
  938. self.state["last_error"] = str(exc)
  939. self._log(f"open orders check failed: {exc}")
  940. self.state["open_order_count"] = open_order_count
  941. if not balance_refresh_ok:
  942. self._log("balance refresh unavailable, skipping rebuild checks this tick")
  943. self.state["last_action"] = "hold"
  944. return {"action": "hold", "price": price, "reason": "balance refresh unavailable"}
  945. desired_sides = self._desired_sides()
  946. mode = self._mode()
  947. if mode != "active":
  948. cleanup_pending = False
  949. if open_order_count > 0:
  950. self._log("observe mode: cancel all open orders")
  951. if self._cancel_all_orders_conclusive("observe cancel failed"):
  952. self.state["orders"] = []
  953. self.state["order_ids"] = []
  954. self.state["open_order_count"] = 0
  955. else:
  956. cleanup_pending = True
  957. if not self.state.get("seeded") or not self.state.get("center_price"):
  958. self.state["center_price"] = price
  959. self.state["seeded"] = True
  960. self.state["last_action"] = "observe cleanup pending" if cleanup_pending else "observe monitor"
  961. self._log(f"observe at {price} dev 0.0000")
  962. return {"action": "observe", "price": price, "deviation": 0.0, "cleanup_pending": cleanup_pending}
  963. center = float(self.state.get("center_price") or price)
  964. recenter_pct = float(self.config.get("recenter_pct", 0.05) or 0.05)
  965. deviation = abs(price - center) / center if center else 0.0
  966. if deviation >= recenter_pct:
  967. self.state["center_price"] = price
  968. self.state["last_action"] = "observe cleanup pending" if cleanup_pending else "observe monitor"
  969. self._log(f"observe at {price} dev {deviation:.4f}")
  970. return {"action": "observe", "price": price, "deviation": deviation, "cleanup_pending": cleanup_pending}
  971. self.state["last_action"] = "observe cleanup pending" if cleanup_pending else "observe monitor"
  972. self._log(f"observe at {price} dev {deviation:.4f}")
  973. return {"action": "observe", "price": price, "deviation": deviation, "cleanup_pending": cleanup_pending}
  974. if stale_ids:
  975. self._log(f"stale live orders: {stale_ids}")
  976. self._cancel_orders(stale_ids)
  977. live_ids = [oid for oid in live_ids if oid not in stale_ids]
  978. if missing_ids:
  979. self._log(f"missing tracked orders: {missing_ids}")
  980. self.state["order_ids"] = live_ids
  981. missing_tracked = bool(set(expected_ids) - set(live_ids))
  982. center = self._maybe_refresh_center(float(self.state.get("center_price") or price))
  983. recenter_pct = self._recenter_threshold_pct()
  984. deviation = abs(price - center) / center if center else 0.0
  985. if mode == "active" and deviation >= recenter_pct and not self._grid_refresh_paused():
  986. if rebuild_done:
  987. return {"action": "hold", "price": price}
  988. self._log(f"recenter needed at price={price} center={center} dev={deviation:.4f} threshold={recenter_pct:.4f}")
  989. rebuild_done = True
  990. self._recenter_and_rebuild_from_price(price, "recenter")
  991. live_orders = self._sync_open_orders_state()
  992. live_ids = list(self.state.get("order_ids") or [])
  993. open_order_count = len(live_ids)
  994. self.state["last_action"] = "recentered"
  995. return {"action": "recenter", "price": price, "deviation": deviation}
  996. live_orders, live_ids, open_order_count = self._reconcile_after_sync(previous_orders, live_orders, desired_sides, price)
  997. if self._grid_refresh_paused():
  998. mode = self._mode()
  999. self.state["last_action"] = "hold" if mode == "active" else f"{mode} monitor"
  1000. self._log(f"grid refresh paused, holding at {price} dev {deviation:.4f}")
  1001. return {"action": "hold" if mode == "active" else "plan", "price": price, "deviation": deviation, "refresh_paused": True}
  1002. if desired_sides != {"buy", "sell"}:
  1003. self._log("single-side mode is disabled for this strategy, forcing full-grid rebuilds only")
  1004. current_buy = sum(1 for order in live_orders if isinstance(order, dict) and str(order.get("side") or "").lower() == "buy")
  1005. current_sell = sum(1 for order in live_orders if isinstance(order, dict) and str(order.get("side") or "").lower() == "sell")
  1006. total_base, total_quote = self._inventory_totals_from_live_orders(live_orders)
  1007. planned_grid = self._plan_grid(center, base_total=total_base, quote_total=total_quote)
  1008. target_buy = int((planned_grid.get("counts") or {}).get("buy") or 0)
  1009. target_sell = int((planned_grid.get("counts") or {}).get("sell") or 0)
  1010. balance_shape_inconclusive = bool(self.state.get("balance_shape_inconclusive"))
  1011. # Shape means side counts here. Exact ids are handled by the tracked-order path below.
  1012. grid_not_as_expected = current_buy != target_buy or current_sell != target_sell
  1013. if balance_shape_inconclusive:
  1014. self._log("balance info not conclusive, skipping grid shape rebuild checks this tick")
  1015. elif grid_not_as_expected:
  1016. if rebuild_done:
  1017. return {"action": "hold", "price": price}
  1018. self._log(
  1019. f"grid shape mismatch, rebuilding full grid: live_buy={current_buy} live_sell={current_sell} target_buy={target_buy} target_sell={target_sell}"
  1020. )
  1021. rebuild_done = True
  1022. self.state["center_price"] = price
  1023. self._recenter_and_rebuild_from_price(price, "grid shape rebuild")
  1024. live_orders = self._sync_open_orders_state()
  1025. mode = self._mode()
  1026. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  1027. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  1028. if not balance_shape_inconclusive and self._order_count_mismatch(tracked_ids_before_sync, live_orders):
  1029. if rebuild_done:
  1030. return {"action": "hold", "price": price}
  1031. self._log(f"grid mismatch detected, rebuilding full grid: tracked={len(tracked_ids_before_sync)} live={len(live_orders)}")
  1032. rebuild_done = True
  1033. self.state["center_price"] = price
  1034. self._recenter_and_rebuild_from_price(price, "grid mismatch rebuild")
  1035. live_orders = self._sync_open_orders_state()
  1036. mode = self._mode()
  1037. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  1038. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  1039. if (not self.state.get("seeded") or not self.state.get("center_price")) and not self._grid_refresh_paused():
  1040. self.state["center_price"] = price
  1041. self._place_grid(price)
  1042. live_orders = self._sync_open_orders_state()
  1043. self.state["seeded"] = True
  1044. self._set_grid_refresh_pause()
  1045. mode = self._mode()
  1046. self._log(f"{'seeded' if mode == 'active' else 'planned'} grid at {price}")
  1047. return {"action": "seed" if mode == "active" else "plan", "price": price}
  1048. if not balance_shape_inconclusive and ((open_order_count == 0) or missing_tracked):
  1049. if rebuild_done:
  1050. return {"action": "hold", "price": price}
  1051. self._log("missing tracked order(s), rebuilding full grid")
  1052. rebuild_done = True
  1053. self.state["center_price"] = price
  1054. self._recenter_and_rebuild_from_price(price, "missing order rebuild")
  1055. live_orders = self._sync_open_orders_state()
  1056. mode = self._mode()
  1057. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  1058. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  1059. mode = self._mode()
  1060. self.state["last_action"] = "hold" if mode == "active" else f"{mode} monitor"
  1061. self._log(f"hold at {price} dev {deviation:.4f}")
  1062. return {"action": "hold" if mode == "active" else "plan", "price": price, "deviation": deviation}
  1063. def report(self):
  1064. snapshot = self.context.get_strategy_snapshot() if hasattr(self.context, "get_strategy_snapshot") else {}
  1065. supervision = self._supervision()
  1066. warnings = [w for w in [self._config_warning(), *(supervision.get("concerns") or [])] if w]
  1067. return {
  1068. "identity": snapshot.get("identity", {}),
  1069. "control": snapshot.get("control", {}),
  1070. "fit": dict(getattr(self, "STRATEGY_PROFILE", {}) or {}),
  1071. "position": {
  1072. "balances": {
  1073. "base_available": self.state.get("base_available", 0.0),
  1074. "counter_available": self.state.get("counter_available", 0.0),
  1075. },
  1076. "open_orders": self.state.get("orders") or [],
  1077. "exposure": "grid",
  1078. },
  1079. "state": {
  1080. "center_price": self.state.get("center_price", 0.0),
  1081. "last_price": self.state.get("last_price", 0.0),
  1082. "last_action": self.state.get("last_action", "idle"),
  1083. "open_order_count": self.state.get("open_order_count", 0),
  1084. "grid_step_pct": self.state.get("grid_step_pct", 0.0),
  1085. "grid_step_pct_buy": self.state.get("grid_step_pct_buy", 0.0),
  1086. "grid_step_pct_sell": self.state.get("grid_step_pct_sell", 0.0),
  1087. "inventory_skew_side": self.state.get("inventory_skew_side", "none"),
  1088. "inventory_skew_ratio": self.state.get("inventory_skew_ratio", 0.5),
  1089. "inventory_skew_reduction_pct": self.state.get("inventory_skew_reduction_pct", 0.0),
  1090. "regimes_updated_at": self.state.get("regimes_updated_at", ""),
  1091. },
  1092. "assessment": {
  1093. "confidence": None,
  1094. "uncertainty": None,
  1095. "reason": "structure-based grid management",
  1096. "warnings": warnings,
  1097. "policy": dict(self.config.get("policy") or {}),
  1098. },
  1099. "execution": snapshot.get("execution", {}),
  1100. "supervision": supervision,
  1101. }
  1102. def render(self):
  1103. # Refresh the market-derived display values on render so the dashboard
  1104. # reflects the same inputs the strategy would use on the next tick.
  1105. live_step_pct = float(self.state.get("grid_step_pct") or 0.0)
  1106. live_buy_step_pct = float(self.state.get("grid_step_pct_buy") or 0.0)
  1107. live_sell_step_pct = float(self.state.get("grid_step_pct_sell") or 0.0)
  1108. live_atr_pct = float(self.state.get("atr_percent") or 0.0)
  1109. try:
  1110. self._refresh_balance_snapshot()
  1111. live_step_pct = self._grid_step_pct()
  1112. step_profile = self._effective_grid_steps(float(self.state.get("last_price") or self.state.get("center_price") or 0.0))
  1113. live_buy_step_pct = float(step_profile.get("buy") or live_step_pct)
  1114. live_sell_step_pct = float(step_profile.get("sell") or live_step_pct)
  1115. live_atr_pct = float(self.state.get("atr_percent") or live_atr_pct)
  1116. except Exception as exc:
  1117. self._log(f"render refresh failed: {exc}")
  1118. return {
  1119. "widgets": [
  1120. {"type": "metric", "label": "market", "value": self._market_symbol()},
  1121. {"type": "metric", "label": "center", "value": round(float(self.state.get("center_price") or 0.0), 6)},
  1122. {"type": "metric", "label": "last price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  1123. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  1124. {"type": "metric", "label": "orders", "value": len(self.state.get("orders") or [])},
  1125. {"type": "metric", "label": "open orders", "value": self.state.get("open_order_count", 0)},
  1126. {"type": "metric", "label": f"ATR({self.config.get('volatility_timeframe', '1h')}) %", "value": round(live_atr_pct, 4)},
  1127. {"type": "metric", "label": "grid step %", "value": round(live_step_pct * 100.0, 4)},
  1128. {"type": "metric", "label": "buy step %", "value": round(live_buy_step_pct * 100.0, 4)},
  1129. {"type": "metric", "label": "sell step %", "value": round(live_sell_step_pct * 100.0, 4)},
  1130. {"type": "metric", "label": "rebalance bias", "value": self.state.get("inventory_skew_side", "none")},
  1131. {"type": "metric", "label": "1d", "value": ((self.state.get('regimes') or {}).get('1d') or {}).get('trend', {}).get('state', 'n/a')},
  1132. {"type": "metric", "label": "4h", "value": ((self.state.get('regimes') or {}).get('4h') or {}).get('trend', {}).get('state', 'n/a')},
  1133. {"type": "metric", "label": "1h", "value": ((self.state.get('regimes') or {}).get('1h') or {}).get('trend', {}).get('state', 'n/a')},
  1134. {"type": "metric", "label": "15m", "value": ((self.state.get('regimes') or {}).get('15m') or {}).get('trend', {}).get('state', 'n/a')},
  1135. {"type": "metric", "label": f"{self._base_symbol()} avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  1136. {"type": "metric", "label": f"{self.context.counter_currency or 'USD'} avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  1137. *([
  1138. {"type": "text", "label": "config warning", "value": warning},
  1139. ] if (warning := self._config_warning()) else []),
  1140. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  1141. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  1142. ]
  1143. }