grid_trader.py 62 KB

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