grid_trader.py 46 KB

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