grid_trader.py 59 KB

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