grid_trader.py 54 KB

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