grid_trader.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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 not None or quote_total is not None:
  325. # Shape planning should see the whole wallet, not only the free slice.
  326. base_value = max(float(base_total if base_total is not None else self.state.get("base_available") or 0.0), 0.0) * ratio_price
  327. counter_value = max(float(quote_total if quote_total is not None else self.state.get("counter_available") or 0.0), 0.0)
  328. total = base_value + counter_value
  329. ratio = base_value / total if total > 0 else 0.5
  330. else:
  331. ratio = self._inventory_ratio(ratio_price if ratio_price > 0 else 1.0)
  332. imbalance = min(abs(ratio - 0.5) * 2.0, 1.0)
  333. factor = float(self.config.get("inventory_rebalance_step_factor", 0.15) or 0.0)
  334. factor = min(max(factor, 0.0), 0.9)
  335. favored_side = "sell" if ratio > 0.5 else "buy" if ratio < 0.5 else "none"
  336. reduction = factor * imbalance if favored_side in {"buy", "sell"} else 0.0
  337. self.state["inventory_skew_side"] = favored_side
  338. self.state["inventory_skew_ratio"] = ratio
  339. self.state["inventory_skew_imbalance"] = imbalance
  340. self.state["inventory_skew_reduction_pct"] = reduction
  341. return {
  342. "ratio": ratio,
  343. "imbalance": imbalance,
  344. "favored_side": favored_side,
  345. "reduction": reduction,
  346. }
  347. def _effective_grid_steps(
  348. self,
  349. price: float,
  350. *,
  351. base_total: float | None = None,
  352. quote_total: float | None = None,
  353. ) -> dict[str, float | str]:
  354. base_step = float(self.state.get("grid_step_pct") or self._grid_step_pct())
  355. min_step = float(self.config.get("grid_step_min_pct", 0.005) or 0.0)
  356. profile = self._inventory_rebalance_profile(price, base_total=base_total, quote_total=quote_total)
  357. favored_side = str(profile.get("favored_side") or "none")
  358. reduction = float(profile.get("reduction") or 0.0)
  359. buy_step = base_step
  360. sell_step = base_step
  361. if favored_side == "buy":
  362. buy_step = max(base_step * (1.0 - reduction), min_step)
  363. elif favored_side == "sell":
  364. sell_step = max(base_step * (1.0 - reduction), min_step)
  365. self.state["grid_step_pct_buy"] = buy_step
  366. self.state["grid_step_pct_sell"] = sell_step
  367. return {
  368. "base": base_step,
  369. "buy": buy_step,
  370. "sell": sell_step,
  371. "favored_side": favored_side,
  372. "reduction": reduction,
  373. "ratio": float(profile.get("ratio") or 0.5),
  374. "imbalance": float(profile.get("imbalance") or 0.0),
  375. }
  376. def _config_warning(self) -> str | None:
  377. recenter_pct = float(self.state.get("recenter_pct_live") or self._recenter_threshold_pct())
  378. steps = self._effective_grid_steps(float(self.state.get("last_price") or self.state.get("center_price") or 0.0))
  379. grid_step_pct = min(float(steps.get("buy") or 0.0), float(steps.get("sell") or 0.0))
  380. if grid_step_pct <= 0:
  381. return None
  382. ratio = recenter_pct / grid_step_pct
  383. # If the recenter threshold is too close to the first step, the grid
  384. # can keep rebuilding before it has a fair chance to trade.
  385. if ratio <= 1.0:
  386. return f"warning: recenter threshold ({recenter_pct:.4f}) is <= grid step ({grid_step_pct:.4f}), it may recenter before trading"
  387. if ratio < 1.5:
  388. return f"warning: recenter threshold ({recenter_pct:.4f}) is only {ratio:.2f}x the grid step ({grid_step_pct:.4f}), consider widening it"
  389. return None
  390. def _inventory_ratio(self, price: float) -> float:
  391. base_value = float(self.state.get("base_available") or 0.0) * price
  392. counter_value = float(self.state.get("counter_available") or 0.0)
  393. total = base_value + counter_value
  394. if total <= 0:
  395. return 0.5
  396. return base_value / total
  397. def _supervision(self) -> dict:
  398. price = float(self.state.get("last_price") or 0.0)
  399. ratio = self._inventory_ratio(price if price > 0 else 1.0)
  400. step_profile = self._effective_grid_steps(price)
  401. last_error = str(self.state.get("last_error") or "")
  402. config_warning = self._config_warning()
  403. regime_1h = (((self.state.get("regimes") or {}).get("1h") or {}).get("trend") or {}).get("state")
  404. center_price = float(self.state.get("center_price") or self.state.get("last_price") or 0.0)
  405. if ratio >= 0.88:
  406. pressure = "base_side_depleted"
  407. elif ratio <= 0.12:
  408. pressure = "quote_side_depleted"
  409. elif ratio >= 0.65:
  410. pressure = "base_heavy"
  411. elif ratio <= 0.35:
  412. pressure = "quote_heavy"
  413. else:
  414. pressure = "balanced"
  415. if price > 0 and center_price > 0:
  416. if price > center_price:
  417. market_bias = "bullish"
  418. adverse_side = "sell"
  419. elif price < center_price:
  420. market_bias = "bearish"
  421. adverse_side = "buy"
  422. else:
  423. market_bias = "flat"
  424. adverse_side = "unknown"
  425. else:
  426. market_bias = "unknown"
  427. adverse_side = "unknown"
  428. open_orders = self.state.get("orders") or []
  429. order_distribution = {"buy": {"count": 0, "notional_quote": 0.0}, "sell": {"count": 0, "notional_quote": 0.0}}
  430. adverse_side_nearest_distance_pct = None
  431. for order in open_orders:
  432. if not isinstance(order, dict):
  433. continue
  434. side = str(order.get("side") or "").lower()
  435. if side not in order_distribution:
  436. continue
  437. try:
  438. order_price = float(order.get("price") or 0.0)
  439. amount = float(order.get("amount") or order.get("amount_remaining") or 0.0)
  440. except Exception:
  441. continue
  442. if order_price <= 0 or amount <= 0:
  443. continue
  444. order_distribution[side]["count"] += 1
  445. order_distribution[side]["notional_quote"] += amount * order_price
  446. if side == adverse_side and price > 0:
  447. distance_pct = abs(order_price - price) / price * 100.0
  448. if adverse_side_nearest_distance_pct is None or distance_pct < adverse_side_nearest_distance_pct:
  449. adverse_side_nearest_distance_pct = distance_pct
  450. adverse_count = int(order_distribution.get(adverse_side, {}).get("count") or 0) if adverse_side in order_distribution else 0
  451. adverse_notional = float(order_distribution.get(adverse_side, {}).get("notional_quote") or 0.0) if adverse_side in order_distribution else 0.0
  452. concerns = []
  453. if adverse_side in {"buy", "sell"} and adverse_count > 0:
  454. concerns.append(f"{adverse_side} ladder exposed to {market_bias} drift")
  455. if pressure in {"base_side_depleted", "quote_side_depleted"}:
  456. concerns.append(f"inventory pressure={pressure}")
  457. if config_warning:
  458. concerns.append(config_warning)
  459. side_capacity = {
  460. "buy": pressure not in {"quote_side_depleted"},
  461. "sell": pressure not in {"base_side_depleted"},
  462. }
  463. return {
  464. "health": "degraded" if last_error or config_warning else "healthy",
  465. "degraded": bool(last_error or config_warning),
  466. "inventory_pressure": pressure,
  467. "inventory_ratio": round(ratio, 4),
  468. "inventory_rebalance_side": step_profile.get("favored_side", "none"),
  469. "inventory_rebalance_reduction_pct": round(float(step_profile.get("reduction") or 0.0) * 100.0, 4),
  470. "grid_step_pct": {
  471. "base": round(float(step_profile.get("base") or 0.0), 6),
  472. "buy": round(float(step_profile.get("buy") or 0.0), 6),
  473. "sell": round(float(step_profile.get("sell") or 0.0), 6),
  474. },
  475. "capacity_available": pressure == "balanced",
  476. "side_capacity": side_capacity,
  477. "market_bias": market_bias,
  478. "adverse_side": adverse_side,
  479. "adverse_side_open_order_count": adverse_count,
  480. "adverse_side_open_order_notional_quote": round(adverse_notional, 4),
  481. "adverse_side_nearest_distance_pct": round(adverse_side_nearest_distance_pct, 4) if adverse_side_nearest_distance_pct is not None else None,
  482. "open_order_distribution": order_distribution,
  483. "concerns": concerns,
  484. "last_reason": last_error or config_warning or f"base_ratio={ratio:.3f}, trend_1h={regime_1h or 'unknown'}",
  485. }
  486. def _available_balance(self, asset_code: str) -> float:
  487. try:
  488. info = self.context.get_account_info()
  489. except Exception as exc:
  490. self._log(f"account info failed: {exc}")
  491. # A failed balance read makes this tick unsuitable for shape decisions.
  492. self.state["balance_shape_inconclusive"] = True
  493. return 0.0
  494. balances = info.get("balances") if isinstance(info, dict) else []
  495. if not isinstance(balances, list):
  496. self.state["balance_shape_inconclusive"] = True
  497. return 0.0
  498. wanted = str(asset_code or "").upper()
  499. for balance in balances:
  500. if not isinstance(balance, dict):
  501. continue
  502. if str(balance.get("asset_code") or "").upper() != wanted:
  503. continue
  504. try:
  505. return float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  506. except Exception:
  507. self.state["balance_shape_inconclusive"] = True
  508. return 0.0
  509. self.state["balance_shape_inconclusive"] = True
  510. return 0.0
  511. def _refresh_balance_snapshot(self) -> bool:
  512. try:
  513. info = self.context.get_account_info()
  514. except Exception as exc:
  515. self._log(f"balance refresh failed: {exc}")
  516. self.state["balance_shape_inconclusive"] = True
  517. return False
  518. balances = info.get("balances") if isinstance(info, dict) else []
  519. if not isinstance(balances, list):
  520. self.state["balance_shape_inconclusive"] = True
  521. return False
  522. base = self._base_symbol()
  523. quote = self.context.counter_currency or "USD"
  524. for balance in balances:
  525. if not isinstance(balance, dict):
  526. continue
  527. asset = str(balance.get("asset_code") or "").upper()
  528. try:
  529. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  530. except Exception:
  531. self.state["balance_shape_inconclusive"] = True
  532. continue
  533. if asset == base:
  534. self.state["base_available"] = available
  535. if asset == str(quote).upper():
  536. self.state["counter_available"] = available
  537. self.state["account_snapshot_updated_at"] = datetime.now(timezone.utc).isoformat()
  538. signature = f"{base}:{self.state.get('base_available', 0.0):.8f}|{quote}:{self.state.get('counter_available', 0.0):.8f}"
  539. last_signature = str(self.state.get("last_balance_log_signature") or "")
  540. last_logged_at = str(self.state.get("last_balance_log_at") or "")
  541. now_iso = self.state["account_snapshot_updated_at"]
  542. should_log = signature != last_signature or not last_logged_at
  543. if not should_log:
  544. try:
  545. from datetime import datetime as _dt
  546. elapsed = (_dt.fromisoformat(now_iso) - _dt.fromisoformat(last_logged_at)).total_seconds()
  547. should_log = elapsed >= 60
  548. except Exception:
  549. should_log = True
  550. if should_log:
  551. self.state["last_balance_log_signature"] = signature
  552. self.state["last_balance_log_at"] = now_iso
  553. self._log_decision(
  554. "balance snapshot",
  555. base=base,
  556. base_available=f"{self.state.get('base_available', 0.0):.6g}",
  557. quote=quote,
  558. quote_available=f"{self.state.get('counter_available', 0.0):.6g}",
  559. updated_at=now_iso,
  560. )
  561. return True
  562. def _side_allowed(self, side: str) -> bool:
  563. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  564. if selected == "both":
  565. return True
  566. return selected == side
  567. def _desired_sides(self) -> set[str]:
  568. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  569. if selected == "both":
  570. return {"buy", "sell"}
  571. if selected in {"buy", "sell"}:
  572. return {selected}
  573. return {"buy", "sell"}
  574. def _suggest_amount(
  575. self,
  576. side: str,
  577. price: float,
  578. levels: int,
  579. min_notional: float,
  580. *,
  581. available_balances: dict[str, float] | None = None,
  582. ) -> float:
  583. return suggest_quote_sized_amount(
  584. self.context,
  585. side=side,
  586. price=price,
  587. levels=levels,
  588. min_notional=min_notional,
  589. fee_rate=self._live_fee_rate(),
  590. order_notional_quote=float(self.config.get("order_notional_quote") or self.config.get("order_size") or 0.0),
  591. max_order_notional_quote=float(self.config.get("max_order_notional_quote") or self.config.get("max_notional_per_order") or 0.0),
  592. dust_collect=bool(self.config.get("dust_collect", False)),
  593. order_size=0.0,
  594. available_balances=available_balances,
  595. )
  596. def _grid_extreme_price(self, center: float, side: str, levels: int) -> float:
  597. step_profile = self._effective_grid_steps(center)
  598. step = float(step_profile.get(side) or step_profile.get("base") or 0.0)
  599. if center <= 0 or levels <= 0 or step <= 0:
  600. return center
  601. if side == "buy":
  602. return round(center * (1 - (step * levels)), 8)
  603. return round(center * (1 + (step * levels)), 8)
  604. def _resource_total_for_side(self, side: str, base_total: float, quote_total: float) -> float:
  605. if side == "buy":
  606. return max(float(quote_total or 0.0), 0.0)
  607. return max(float(base_total or 0.0), 0.0)
  608. def _resource_cost_for_order(self, side: str, amount: float, price: float, fee_rate: float) -> float:
  609. if side == "buy":
  610. return max(amount, 0.0) * max(price, 0.0) * (1.0 + max(fee_rate, 0.0))
  611. return max(amount, 0.0)
  612. def _inventory_totals_from_live_orders(self, live_orders: list[dict]) -> tuple[float, float]:
  613. reserved_quote = sum(
  614. float(order.get("price") or 0.0) * float(order.get("amount") or 0.0)
  615. for order in live_orders
  616. if isinstance(order, dict) and str(order.get("side") or "").lower() == "buy"
  617. )
  618. reserved_base = sum(
  619. float(order.get("amount") or 0.0)
  620. for order in live_orders
  621. if isinstance(order, dict) and str(order.get("side") or "").lower() == "sell"
  622. )
  623. base_total = max(float(self.state.get("base_available") or 0.0), 0.0) + reserved_base
  624. quote_total = max(float(self.state.get("counter_available") or 0.0), 0.0) + reserved_quote
  625. return base_total, quote_total
  626. def _planned_side_orders(
  627. self,
  628. side: str,
  629. center: float,
  630. expected_levels: int,
  631. min_notional: float,
  632. fee_rate: float,
  633. *,
  634. step: float,
  635. base_total: float,
  636. quote_total: float,
  637. ) -> dict:
  638. empty = {"amount": 0.0, "orders": [], "skipped": []}
  639. if not self._side_allowed(side):
  640. return empty
  641. if expected_levels <= 0 or center <= 0 or step <= 0:
  642. return empty
  643. base_symbol = self._base_symbol()
  644. quote_symbol = str(self.context.counter_currency or "USD").upper()
  645. balances = {
  646. base_symbol: max(float(base_total or 0.0), 0.0),
  647. quote_symbol: max(float(quote_total or 0.0), 0.0),
  648. }
  649. # Ask the shared sizing layer for a venue-valid amount once, then
  650. # walk the ladder outward until we either fill the target or run out.
  651. reference_price = round(center * (1 - (step * expected_levels)) if side == "buy" else center * (1 + (step * expected_levels)), 8)
  652. amount = self._suggest_amount(
  653. side,
  654. reference_price,
  655. max(expected_levels, 1),
  656. min_notional,
  657. available_balances=balances,
  658. )
  659. if amount <= 0:
  660. return empty
  661. spendable_total = self._resource_total_for_side(side, base_total, quote_total) * 0.995
  662. total_cost = 0.0
  663. planned_orders = []
  664. skipped = []
  665. max_index = max(expected_levels * 4, expected_levels + 8, 12)
  666. for level_index in range(1, max_index + 1):
  667. # Skip inner levels that fail min-size, but keep pushing outward.
  668. price = round(center * (1 - (step * level_index)) if side == "buy" else center * (1 + (step * level_index)), 8)
  669. if price <= 0:
  670. break
  671. min_size = (min_notional / price) if min_notional > 0 else 0.0
  672. if amount < min_size:
  673. skipped.append({"level": level_index, "reason": "below minimum size", "price": price})
  674. if side == "buy":
  675. break
  676. continue
  677. cost = self._resource_cost_for_order(side, amount, price, fee_rate)
  678. if total_cost + cost > spendable_total + 1e-9:
  679. break
  680. total_cost += cost
  681. planned_orders.append({"side": side, "price": price, "amount": amount, "level": level_index})
  682. if len(planned_orders) >= expected_levels:
  683. break
  684. return {"amount": amount, "orders": planned_orders, "skipped": skipped}
  685. def _plan_grid(self, center: float, *, base_total: float | None = None, quote_total: float | None = None) -> dict:
  686. center = float(center or 0.0)
  687. levels = int(self.config.get("grid_levels", 6) or 6)
  688. min_notional = float(self.context.minimum_order_value or 0.0)
  689. fee_rate = self._live_fee_rate()
  690. # One planner feeds both seeding and shape checking, so they never
  691. # invent different notions of the "correct" grid.
  692. step_profile = self._effective_grid_steps(center, base_total=base_total, quote_total=quote_total)
  693. buy_step = float(step_profile.get("buy") or step_profile.get("base") or 0.0)
  694. sell_step = float(step_profile.get("sell") or step_profile.get("base") or 0.0)
  695. base_total = max(float(self.state.get("base_available") if base_total is None else base_total) or 0.0, 0.0)
  696. quote_total = max(float(self.state.get("counter_available") if quote_total is None else quote_total) or 0.0, 0.0)
  697. buy_plan = self._planned_side_orders(
  698. "buy",
  699. center,
  700. levels,
  701. min_notional,
  702. fee_rate,
  703. step=buy_step,
  704. base_total=base_total,
  705. quote_total=quote_total,
  706. )
  707. sell_plan = self._planned_side_orders(
  708. "sell",
  709. center,
  710. levels,
  711. min_notional,
  712. fee_rate,
  713. step=sell_step,
  714. base_total=base_total,
  715. quote_total=quote_total,
  716. )
  717. orders = [*buy_plan["orders"], *sell_plan["orders"]]
  718. return {
  719. "center": center,
  720. "buy_orders": buy_plan["orders"],
  721. "sell_orders": sell_plan["orders"],
  722. "orders": orders,
  723. "buy_skipped": buy_plan["skipped"],
  724. "sell_skipped": sell_plan["skipped"],
  725. "counts": {"buy": len(buy_plan["orders"]), "sell": len(sell_plan["orders"])},
  726. }
  727. def _place_grid(self, center: float) -> None:
  728. center = self._maybe_refresh_center(center)
  729. mode = self._mode()
  730. market = self._market_symbol()
  731. orders = []
  732. order_ids = []
  733. def _capture_order_id(result):
  734. if isinstance(result, dict):
  735. return result.get("bitstamp_order_id") or result.get("order_id") or result.get("id") or result.get("client_order_id")
  736. return None
  737. plan = self._plan_grid(center)
  738. for side, skipped in (("buy", plan.get("buy_skipped") or []), ("sell", plan.get("sell_skipped") or [])):
  739. for skipped_level in skipped:
  740. self._log(f"seed level {skipped_level.get('level')} {side} skipped: {skipped_level.get('reason')}")
  741. for planned_order in plan.get("orders") or []:
  742. side = str(planned_order.get("side") or "").lower()
  743. level = int(planned_order.get("level") or 0)
  744. price = float(planned_order.get("price") or 0.0)
  745. amount = float(planned_order.get("amount") or 0.0)
  746. if price <= 0 or amount <= 0:
  747. continue
  748. if mode != "active":
  749. orders.append({"side": side, "price": price, "amount": amount, "result": {"simulated": True}})
  750. self._log(f"plan level {level}: {side} {price} amount {amount:.6g}")
  751. continue
  752. try:
  753. result = self.context.place_order(side=side, order_type="limit", amount=amount, price=price, market=market)
  754. orders.append({"side": side, "price": price, "amount": amount, "result": result})
  755. order_id = _capture_order_id(result)
  756. if order_id is not None:
  757. order_ids.append(str(order_id))
  758. self._log(f"seed level {level}: {side} {price} amount {amount:.6g}")
  759. delay = max(int(self.config.get("order_call_delay_ms", 250) or 0), 0) / 1000.0
  760. if delay > 0:
  761. time.sleep(delay)
  762. self._refresh_balance_snapshot()
  763. except Exception as exc: # best effort for first draft
  764. self.state["last_error"] = str(exc)
  765. self._log(f"seed level {level} {side} failed: {exc}")
  766. self.state["orders"] = orders
  767. self.state["order_ids"] = order_ids
  768. self.state["last_action"] = "seeded grid"
  769. self._set_grid_refresh_pause()
  770. def _current_market_anchor(self, fallback: float = 0.0) -> float:
  771. try:
  772. live_price = float(self._price() or 0.0)
  773. except Exception as exc:
  774. self._log(f"live price refresh failed during rebuild: {exc}")
  775. live_price = 0.0
  776. return live_price if live_price > 0 else fallback
  777. def _recenter_and_rebuild_from_fill(self, fill_price: float, market_price: float = 0.0) -> None:
  778. """Treat a fill as a forced re-anchor and rebuild from the latest market price."""
  779. anchor_price = self._current_market_anchor(market_price or fill_price)
  780. if anchor_price <= 0:
  781. return
  782. self._log(f"fill rebuild anchor resolved: fill={fill_price} market={anchor_price}")
  783. self._recenter_and_rebuild_from_price(anchor_price, "fill rebuild")
  784. def _recenter_and_rebuild_from_price(self, price: float, reason: str) -> None:
  785. if price <= 0:
  786. return
  787. current = float(self.state.get("center_price") or 0.0)
  788. self._log(f"{reason}: recenter from {current} to {price}")
  789. if not self._cancel_all_orders_conclusive(f"{reason} cancel-all failed"):
  790. self.state["last_action"] = f"{reason} cleanup pending"
  791. return
  792. # Give the exchange a moment to release balance before we rebuild.
  793. time.sleep(3.0)
  794. self._refresh_balance_snapshot()
  795. self.state["center_price"] = price
  796. self.state["seeded"] = True
  797. self._place_grid(price)
  798. # Use the freshly placed live orders as the tracked snapshot so the
  799. # next tick compares against the rebuilt grid, not the pre-rebuild set.
  800. self._sync_open_orders_state()
  801. self._refresh_balance_snapshot()
  802. self._set_grid_refresh_pause()
  803. def on_stop(self):
  804. self._log("stopping: cancel all open orders")
  805. if self._cancel_all_orders_conclusive("stop cancel-all failed"):
  806. self.state["orders"] = []
  807. self.state["order_ids"] = []
  808. self.state["open_order_count"] = 0
  809. self.state["last_action"] = "stopped"
  810. else:
  811. self.state["last_action"] = "stop cleanup pending"
  812. def _maybe_refresh_center(self, price: float) -> float:
  813. if price <= 0:
  814. return price
  815. current = float(self.state.get("center_price") or 0.0)
  816. if current <= 0:
  817. self.state["center_price"] = price
  818. return price
  819. deviation = abs(price - current) / current if current else 0.0
  820. threshold = self._recenter_threshold_pct()
  821. if deviation >= threshold:
  822. self._log(f"recenter anchor from {current} to {price} dev={deviation:.4f} threshold={threshold:.4f}")
  823. self.state["center_price"] = price
  824. return price
  825. return current
  826. def _sync_open_orders_state(self) -> list[dict]:
  827. try:
  828. open_orders = self.context.get_open_orders()
  829. except Exception as exc:
  830. self.state["last_error"] = str(exc)
  831. self._log(f"open orders sync failed: {exc}")
  832. return []
  833. if not isinstance(open_orders, list):
  834. open_orders = []
  835. live_orders = [order for order in open_orders if isinstance(order, dict)]
  836. 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]
  837. live_ids = [oid for oid in live_ids if oid]
  838. live_sides = [str(order.get("side") or "").lower() for order in live_orders]
  839. self.state["orders"] = live_orders
  840. self.state["order_ids"] = live_ids
  841. self.state["open_order_count"] = len(live_ids)
  842. self._log(f"sync live orders: count={len(live_ids)} sides={live_sides} ids={live_ids}")
  843. return live_orders
  844. def _cancel_orders(self, order_ids) -> None:
  845. for order_id in order_ids or []:
  846. self._log(f"dropping stale order {order_id} from state")
  847. 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]:
  848. live_ids = list(self.state.get("order_ids") or [])
  849. open_order_count = len(live_ids)
  850. if self._mode() != "active":
  851. return live_orders, live_ids, open_order_count
  852. previous_ids = {
  853. str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  854. for order in previous_orders
  855. if isinstance(order, dict)
  856. }
  857. current_ids = {
  858. str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  859. for order in live_orders
  860. if isinstance(order, dict)
  861. }
  862. vanished_orders = [
  863. order
  864. for order in previous_orders
  865. if isinstance(order, dict)
  866. 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)
  867. ]
  868. if vanished_orders and not self._grid_refresh_paused():
  869. for order in vanished_orders:
  870. order_id = str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  871. if not order_id:
  872. continue
  873. try:
  874. payload = self.context.query_order(order_id)
  875. except Exception as exc:
  876. self._log(f"order status query failed for {order_id}: {exc}")
  877. continue
  878. raw = payload.get("raw") if isinstance(payload, dict) else {}
  879. if not isinstance(raw, dict):
  880. raw = {}
  881. status = str(payload.get("status") or raw.get("status") or order.get("status") or "").strip().lower()
  882. if status in {"finished", "filled", "closed"}:
  883. fill_price = 0.0
  884. for candidate in (raw.get("price"), order.get("price"), price):
  885. try:
  886. fill_price = float(candidate or 0.0)
  887. except Exception:
  888. fill_price = 0.0
  889. if fill_price > 0:
  890. break
  891. if fill_price > 0:
  892. self._log(f"filled order {order_id} detected via exec status={status}, recentering from fill={fill_price} market={price}")
  893. self._recenter_and_rebuild_from_fill(fill_price, price)
  894. live_orders = self._sync_open_orders_state()
  895. live_ids = list(self.state.get("order_ids") or [])
  896. open_order_count = len(live_ids)
  897. return live_orders, live_ids, open_order_count
  898. if status in {"cancelled", "expired", "missing"}:
  899. self._log(f"vanished order {order_id} resolved as {status}")
  900. continue
  901. return live_orders, live_ids, open_order_count
  902. def on_tick(self, tick):
  903. previous_orders = list(self.state.get("orders") or [])
  904. tracked_ids_before_sync = list(self.state.get("order_ids") or [])
  905. rebuild_done = False
  906. self.state["balance_shape_inconclusive"] = False
  907. balance_refresh_ok = self._refresh_balance_snapshot()
  908. price = self._price()
  909. self.state["last_price"] = price
  910. self.state["last_error"] = ""
  911. self._refresh_regimes()
  912. try:
  913. live_orders = self._sync_open_orders_state()
  914. live_ids = list(self.state.get("order_ids") or [])
  915. open_order_count = len(live_ids)
  916. expected_ids = [str(oid) for oid in tracked_ids_before_sync if oid]
  917. stale_ids = []
  918. missing_ids = []
  919. except Exception as exc:
  920. open_order_count = -1
  921. live_orders = []
  922. live_ids = []
  923. expected_ids = []
  924. stale_ids = []
  925. missing_ids = []
  926. self.state["last_error"] = str(exc)
  927. self._log(f"open orders check failed: {exc}")
  928. self.state["open_order_count"] = open_order_count
  929. if not balance_refresh_ok:
  930. self._log("balance refresh unavailable, skipping rebuild checks this tick")
  931. self.state["last_action"] = "hold"
  932. return {"action": "hold", "price": price, "reason": "balance refresh unavailable"}
  933. desired_sides = self._desired_sides()
  934. mode = self._mode()
  935. if mode != "active":
  936. cleanup_pending = False
  937. if open_order_count > 0:
  938. self._log("observe mode: cancel all open orders")
  939. if self._cancel_all_orders_conclusive("observe cancel failed"):
  940. self.state["orders"] = []
  941. self.state["order_ids"] = []
  942. self.state["open_order_count"] = 0
  943. else:
  944. cleanup_pending = True
  945. if not self.state.get("seeded") or not self.state.get("center_price"):
  946. self.state["center_price"] = price
  947. self.state["seeded"] = True
  948. self.state["last_action"] = "observe cleanup pending" if cleanup_pending else "observe monitor"
  949. self._log(f"observe at {price} dev 0.0000")
  950. return {"action": "observe", "price": price, "deviation": 0.0, "cleanup_pending": cleanup_pending}
  951. center = float(self.state.get("center_price") or price)
  952. recenter_pct = float(self.config.get("recenter_pct", 0.05) or 0.05)
  953. deviation = abs(price - center) / center if center else 0.0
  954. if deviation >= recenter_pct:
  955. self.state["center_price"] = price
  956. self.state["last_action"] = "observe cleanup pending" if cleanup_pending else "observe monitor"
  957. self._log(f"observe at {price} dev {deviation:.4f}")
  958. return {"action": "observe", "price": price, "deviation": deviation, "cleanup_pending": cleanup_pending}
  959. self.state["last_action"] = "observe cleanup pending" if cleanup_pending else "observe monitor"
  960. self._log(f"observe at {price} dev {deviation:.4f}")
  961. return {"action": "observe", "price": price, "deviation": deviation, "cleanup_pending": cleanup_pending}
  962. if stale_ids:
  963. self._log(f"stale live orders: {stale_ids}")
  964. self._cancel_orders(stale_ids)
  965. live_ids = [oid for oid in live_ids if oid not in stale_ids]
  966. if missing_ids:
  967. self._log(f"missing tracked orders: {missing_ids}")
  968. self.state["order_ids"] = live_ids
  969. missing_tracked = bool(set(expected_ids) - set(live_ids))
  970. center = self._maybe_refresh_center(float(self.state.get("center_price") or price))
  971. recenter_pct = self._recenter_threshold_pct()
  972. deviation = abs(price - center) / center if center else 0.0
  973. if mode == "active" and deviation >= recenter_pct and not self._grid_refresh_paused():
  974. if rebuild_done:
  975. return {"action": "hold", "price": price}
  976. self._log(f"recenter needed at price={price} center={center} dev={deviation:.4f} threshold={recenter_pct:.4f}")
  977. rebuild_done = True
  978. self._recenter_and_rebuild_from_price(price, "recenter")
  979. live_orders = self._sync_open_orders_state()
  980. live_ids = list(self.state.get("order_ids") or [])
  981. open_order_count = len(live_ids)
  982. self.state["last_action"] = "recentered"
  983. return {"action": "recenter", "price": price, "deviation": deviation}
  984. live_orders, live_ids, open_order_count = self._reconcile_after_sync(previous_orders, live_orders, desired_sides, price)
  985. if self._grid_refresh_paused():
  986. mode = self._mode()
  987. self.state["last_action"] = "hold" if mode == "active" else f"{mode} monitor"
  988. self._log(f"grid refresh paused, holding at {price} dev {deviation:.4f}")
  989. return {"action": "hold" if mode == "active" else "plan", "price": price, "deviation": deviation, "refresh_paused": True}
  990. if desired_sides != {"buy", "sell"}:
  991. self._log("single-side mode is disabled for this strategy, forcing full-grid rebuilds only")
  992. current_buy = sum(1 for order in live_orders if isinstance(order, dict) and str(order.get("side") or "").lower() == "buy")
  993. current_sell = sum(1 for order in live_orders if isinstance(order, dict) and str(order.get("side") or "").lower() == "sell")
  994. total_base, total_quote = self._inventory_totals_from_live_orders(live_orders)
  995. planned_grid = self._plan_grid(center, base_total=total_base, quote_total=total_quote)
  996. target_buy = int((planned_grid.get("counts") or {}).get("buy") or 0)
  997. target_sell = int((planned_grid.get("counts") or {}).get("sell") or 0)
  998. balance_shape_inconclusive = bool(self.state.get("balance_shape_inconclusive"))
  999. # Shape means side counts here. Exact ids are handled by the tracked-order path below.
  1000. grid_not_as_expected = current_buy != target_buy or current_sell != target_sell
  1001. if balance_shape_inconclusive:
  1002. self._log("balance info not conclusive, skipping grid shape rebuild checks this tick")
  1003. elif grid_not_as_expected:
  1004. if rebuild_done:
  1005. return {"action": "hold", "price": price}
  1006. self._log(
  1007. f"grid shape mismatch, rebuilding full grid: live_buy={current_buy} live_sell={current_sell} target_buy={target_buy} target_sell={target_sell}"
  1008. )
  1009. rebuild_done = True
  1010. self.state["center_price"] = price
  1011. self._recenter_and_rebuild_from_price(price, "grid shape rebuild")
  1012. live_orders = self._sync_open_orders_state()
  1013. mode = self._mode()
  1014. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  1015. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  1016. if not balance_shape_inconclusive and self._order_count_mismatch(tracked_ids_before_sync, live_orders):
  1017. if rebuild_done:
  1018. return {"action": "hold", "price": price}
  1019. self._log(f"grid mismatch detected, rebuilding full grid: tracked={len(tracked_ids_before_sync)} live={len(live_orders)}")
  1020. rebuild_done = True
  1021. self.state["center_price"] = price
  1022. self._recenter_and_rebuild_from_price(price, "grid mismatch rebuild")
  1023. live_orders = self._sync_open_orders_state()
  1024. mode = self._mode()
  1025. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  1026. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  1027. if (not self.state.get("seeded") or not self.state.get("center_price")) and not self._grid_refresh_paused():
  1028. self.state["center_price"] = price
  1029. self._place_grid(price)
  1030. live_orders = self._sync_open_orders_state()
  1031. self.state["seeded"] = True
  1032. self._set_grid_refresh_pause()
  1033. mode = self._mode()
  1034. self._log(f"{'seeded' if mode == 'active' else 'planned'} grid at {price}")
  1035. return {"action": "seed" if mode == "active" else "plan", "price": price}
  1036. if not balance_shape_inconclusive and ((open_order_count == 0) or missing_tracked):
  1037. if rebuild_done:
  1038. return {"action": "hold", "price": price}
  1039. self._log("missing tracked order(s), rebuilding full grid")
  1040. rebuild_done = True
  1041. self.state["center_price"] = price
  1042. self._recenter_and_rebuild_from_price(price, "missing order rebuild")
  1043. live_orders = self._sync_open_orders_state()
  1044. mode = self._mode()
  1045. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  1046. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  1047. mode = self._mode()
  1048. self.state["last_action"] = "hold" if mode == "active" else f"{mode} monitor"
  1049. self._log(f"hold at {price} dev {deviation:.4f}")
  1050. return {"action": "hold" if mode == "active" else "plan", "price": price, "deviation": deviation}
  1051. def report(self):
  1052. snapshot = self.context.get_strategy_snapshot() if hasattr(self.context, "get_strategy_snapshot") else {}
  1053. supervision = self._supervision()
  1054. warnings = [w for w in [self._config_warning(), *(supervision.get("concerns") or [])] if w]
  1055. return {
  1056. "identity": snapshot.get("identity", {}),
  1057. "control": snapshot.get("control", {}),
  1058. "fit": dict(getattr(self, "STRATEGY_PROFILE", {}) or {}),
  1059. "position": {
  1060. "balances": {
  1061. "base_available": self.state.get("base_available", 0.0),
  1062. "counter_available": self.state.get("counter_available", 0.0),
  1063. },
  1064. "open_orders": self.state.get("orders") or [],
  1065. "exposure": "grid",
  1066. },
  1067. "state": {
  1068. "center_price": self.state.get("center_price", 0.0),
  1069. "last_price": self.state.get("last_price", 0.0),
  1070. "last_action": self.state.get("last_action", "idle"),
  1071. "open_order_count": self.state.get("open_order_count", 0),
  1072. "grid_step_pct": self.state.get("grid_step_pct", 0.0),
  1073. "grid_step_pct_buy": self.state.get("grid_step_pct_buy", 0.0),
  1074. "grid_step_pct_sell": self.state.get("grid_step_pct_sell", 0.0),
  1075. "inventory_skew_side": self.state.get("inventory_skew_side", "none"),
  1076. "inventory_skew_ratio": self.state.get("inventory_skew_ratio", 0.5),
  1077. "inventory_skew_reduction_pct": self.state.get("inventory_skew_reduction_pct", 0.0),
  1078. "regimes_updated_at": self.state.get("regimes_updated_at", ""),
  1079. },
  1080. "assessment": {
  1081. "confidence": None,
  1082. "uncertainty": None,
  1083. "reason": "structure-based grid management",
  1084. "warnings": warnings,
  1085. "policy": dict(self.config.get("policy") or {}),
  1086. },
  1087. "execution": snapshot.get("execution", {}),
  1088. "supervision": supervision,
  1089. }
  1090. def render(self):
  1091. # Refresh the market-derived display values on render so the dashboard
  1092. # reflects the same inputs the strategy would use on the next tick.
  1093. live_step_pct = float(self.state.get("grid_step_pct") or 0.0)
  1094. live_buy_step_pct = float(self.state.get("grid_step_pct_buy") or 0.0)
  1095. live_sell_step_pct = float(self.state.get("grid_step_pct_sell") or 0.0)
  1096. live_atr_pct = float(self.state.get("atr_percent") or 0.0)
  1097. try:
  1098. self._refresh_balance_snapshot()
  1099. live_step_pct = self._grid_step_pct()
  1100. step_profile = self._effective_grid_steps(float(self.state.get("last_price") or self.state.get("center_price") or 0.0))
  1101. live_buy_step_pct = float(step_profile.get("buy") or live_step_pct)
  1102. live_sell_step_pct = float(step_profile.get("sell") or live_step_pct)
  1103. live_atr_pct = float(self.state.get("atr_percent") or live_atr_pct)
  1104. except Exception as exc:
  1105. self._log(f"render refresh failed: {exc}")
  1106. return {
  1107. "widgets": [
  1108. {"type": "metric", "label": "market", "value": self._market_symbol()},
  1109. {"type": "metric", "label": "center", "value": round(float(self.state.get("center_price") or 0.0), 6)},
  1110. {"type": "metric", "label": "last price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  1111. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  1112. {"type": "metric", "label": "orders", "value": len(self.state.get("orders") or [])},
  1113. {"type": "metric", "label": "open orders", "value": self.state.get("open_order_count", 0)},
  1114. {"type": "metric", "label": f"ATR({self.config.get('volatility_timeframe', '1h')}) %", "value": round(live_atr_pct, 4)},
  1115. {"type": "metric", "label": "grid step %", "value": round(live_step_pct * 100.0, 4)},
  1116. {"type": "metric", "label": "buy step %", "value": round(live_buy_step_pct * 100.0, 4)},
  1117. {"type": "metric", "label": "sell step %", "value": round(live_sell_step_pct * 100.0, 4)},
  1118. {"type": "metric", "label": "rebalance bias", "value": self.state.get("inventory_skew_side", "none")},
  1119. {"type": "metric", "label": "1d", "value": ((self.state.get('regimes') or {}).get('1d') or {}).get('trend', {}).get('state', 'n/a')},
  1120. {"type": "metric", "label": "4h", "value": ((self.state.get('regimes') or {}).get('4h') or {}).get('trend', {}).get('state', 'n/a')},
  1121. {"type": "metric", "label": "1h", "value": ((self.state.get('regimes') or {}).get('1h') or {}).get('trend', {}).get('state', 'n/a')},
  1122. {"type": "metric", "label": "15m", "value": ((self.state.get('regimes') or {}).get('15m') or {}).get('trend', {}).get('state', 'n/a')},
  1123. {"type": "metric", "label": f"{self._base_symbol()} avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  1124. {"type": "metric", "label": f"{self.context.counter_currency or 'USD'} avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  1125. *([
  1126. {"type": "text", "label": "config warning", "value": warning},
  1127. ] if (warning := self._config_warning()) else []),
  1128. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  1129. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  1130. ]
  1131. }