grid_trader.py 46 KB

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