Repository navigation
BotLab v3 Phase 5: strategy templates (executor, position manager, consistency, resolution-rule, copy trading v2) - #2
Merged
Conversation
Resting paper limit orders now rest instead of being refused: every sync of the bot's orders reads the book and fills an open paper limit order when the opposite side is at or through its price, at its own price (maker, fee 0), up to the size shown; partial fills stay open; expiry at the TTL is checked first so a cross seen after the expiry never fills it. Needed to run the forecast executor in paper. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- templates/forecast-executor.ts (spec 9.1): post-only bids on tradeable forecasts and their binary complement (1 - p) where the ask leaves min_edge + fee, Kelly-sized on the bucket allocation, capped by max_per_market_usd and the risk budget, ranked by edge per day; re-quotes every requote_minutes and on events; cancels its bids when a forecast is superseded, withdrawn, untradeable or the edge is gone. - templates/position-manager.ts (spec 9.2, 3.4): exits on convergence, forecast withdrawn / flipped, low edge per day, rules change, ambiguity, exit flags (acknowledged when closed), stop and end of ambiguous markets; post-only first, marketable after escalate_after_minutes. - ctx.portfolio (PortfolioService): granted only to the builtin position-manager script (scripts.builtin_role, set by the seed); exits are risk-exit sells placed as the owning bot through its OrderService and the RiskEngine, recorded with orders.placed_by and audited; the manager cannot buy. Risk-exit sells pass the stage check (retired / demoted bots). - ctx.events: forecast_changed, rules_changed and halt pushed to workers. - Both templates seeded builtin with trust=new (paper first, then the ramp); one running instance per role and mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- Bots page shows the standing role (executor / position manager); Agent page shows exit flags the position manager closed as handled (time, note). - ctx.getOrderBook returns the market's tick_size when the CLOB reports it. - Agent guide: the standing templates, ctx.events, paper resting orders. - README Strategies section; CLAUDE.md; PROGRESS: Phase 5 plan rows, 5a log, decisions R160-R167. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- Executor: own bids left out of the book, kept while at/above the best competing bid (no self-outbidding); skips quotes below min_edge_per_day (shared 0.001 with the manager's min_hold_edge_per_day); reports unfunded demand; skips a stopped token until its forecast is renewed; per-market cap counts paper holdings (paper getPositions returns conditionId). - Position manager: low_edge only when the executor has better unfunded demand (ctx.portfolio.getCapitalDemand). - Agent cannot create, start, restart or reconfigure standing-role bots. - Scripts cannot set riskExit; owner cancels leave the manager's exits. - ctx.polymarket.getOrderHistory; paper resting fills consume book levels; manager exits serialised per owning bot. - Tests for all of the above; PROGRESS R160/R165/R166 amended, R168-R170. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- templates/consistency.ts (spec §9.3): implies / date_ladder / exclusive_sum constraints, baskets of buys priced at the asks plus taker fees per leg (complement NO token instead of shorting), min_gap, post-only legs, unhedged cap and hedge timeout with escalation bounded by max_slippage and break-even, flattening of its own excess, self-retirement. - templates/resolution-rule.ts (spec §9.4): post-only GTD bids up to the target, sized to max_size_usd, never sells; sticky invalidation on rules change, dispute, ambiguity, linked forecast withdrawn / below target, exit flag, market end; exits left to the position manager. - Builtin roles split into standing (executor, position manager) and strategy roles (consistency, resolution-rule): only standing roles are one-per-mode and refused to the agent. - ctx.polymarket.getMarket (market cache: complement token, ambiguity, rules, scope), ctx.risk.getExitFlags, ctx.requestRetire (BotService.retireByBot, audited as the bot). SDK d.ts regenerated. - BotService: agent bots on strategy templates need the strategy in the mandate, a config matching the template's configSchema and marketIds that cover every token in the config (create and config updates). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- Bot page shows the consistency constraint with the current gap after fees, best basket, state and counts, or the resolution-rule thesis, target, size and state (from the bots' consistency / resolution_rule events); the Bots page labels the strategy roles. - Agent guide §4: when and how to use the per-opportunity templates, config shapes, implies / date ladder / exclusive sum examples, exhaustive flag, no shorting => complement token, the server's create checks, new ctx calls. - System prompt v3: step 6 names the templates and the marketIds rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- Position Manager exit policy published by the server (ctx.risk.getExitPolicy, from the PM bots' config); the PM template reads its ambiguity exit score from it. - Consistency: no basket into the PM triggers (exit flag, ambiguity, dispute, rules change, ambiguity 1 inside the PM exit window); a PM sell on a constraint token unhedges the open basket and stops the bot; fills re-read after cancels before escalation; residual imbalances capped across baskets. - Exclusivity: exclusive_sum legs in one event, exhaustive sets must be the whole negRisk event, ladders need end dates — at start and in BotService (ctx.polymarket.getEventMarketIds, market cache event lists). - Resolution rule: invalid after a PM sell, at the PM ambiguity score, or at ambiguity 1 inside the PM exit window; only the linked forecast keeps it valid (checked server-side); holdings re-read after cancels. - Tests for each; PROGRESS R174/R175 amended, R177-R180. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
Copy Trading v2 (spec §9.5): resting limits at leader fill + max_chase with a short TTL (skipped when the book moved), sells mirroring the leader's sold fraction net of open sells, de-dup by tx hash + log index with pagination, TRADE rows only, oldest first, leader filters (min size, trades/day, market making), mandate / near-end / Position Manager / exit-flag filters, state in ctx.storage. Builtin strategy role 'copy', trust new; the seed upgrades the v1 row in place (schema refreshed, bots back to paper). Leader scoring: copy_leaders / copy_trades tables, CopyLeaderService (attribution via LimitOrderOpts.copy, pure round-trip scoring, auto-drop after 20 losing copies, audited + Telegram, human re-activation, digest). New ctx.risk.getMandateSummary and ctx.copy.getLeaders; agent copy bots only when the mandate allows copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
Activity pages de-duplicated by row identity (no double copies when offsets shift), one trade per key per fetch; dropped leaders blocked globally for the agent (copy_leader_blocks, kept after bot deletion, cleared only by the human re-activation), re-adding keeps the drop window; seed lookups builtin-only; a leader's sell unwinds only the bot's copies of that leader. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
The Create Bot form rendered schema number fields with step=0.01, so the
browser refused defaults finer than a cent: the Forecast Executor's
min_edge_per_day default 0.001 made the form unsubmittable ("nearest valid
values are 0 and 0.01"). Use step=any like ConfigSchemaBuilder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Leader fill prices from the activity API are usdcSize / size and come back a few 1e-7 off the tick (0.3699999935 live). The 1e-9 tolerance floored 0.37 + 0.01 to 0.37, losing the whole max_chase (and ceil'd sells a tick high). Snap within 1e-6 instead; tests use the live values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fused (Mac test F2) An escalated marketable risk exit refused by the engine (e.g. top_of_book on a thin book) left the position with no exit order and was retried every cycle. The manager now falls back to a post-only exit at the lowest non-crossing price (one tick above the best bid), keeps it while the marketable attempt is in a 10-minute retry window (state.marketableRefusedAt), follows the bid with it, and only then tries marketable again. A position with an active trigger is never left without an exit order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
…est F1, F3, F4) F1: max_orders_per_hour counts only orders the bot itself submitted (countByBotSince excludes rejected_risk rows and Position Manager exits placed for it). A separate rejection cooldown pauses a bot's own submissions (6 own risk rejections in 10 min => rejection_cooldown until the window drains; recorded and audited, not re-notified, not counted; exits placed by another bot are exempt). ctx.risk.getBudget() reports ordersPerHour / ordersRemainingThisHour. Forecast Executor: bids rest bid_ttl_minutes (default 60, min 3) and are re-placed only when <= min(5 min, ttl/2) remain or price / size must change (a cycle is woken at the earliest refresh time); it quotes no more markets than the hourly rate can sustain and places at most the orders left this hour (best ranked first). F3/F4: new read-only, mode-scoped ctx.risk.getFlaggedTokens() (open exit flags on any bot's position) and ctx.risk.getRecentStops(tokenId?) (latest Position Manager stop per token, last 30 days, any bot). The executor skips forecasts whose token, complement or market is flagged (cancelling its bids there) and tokens stopped out on any bot until the forecast is renewed. Copy trading uses both too, and its market filter now compares MarketDetail.volume24hUsd (new) with min_liquidity_usd, the measure the risk engine uses (F5). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
min_liquidity_usd is compared with Gamma 24h volume by the ledger, the risk engine and (now) copy trading. UI, MCP, agent prompt (v5), guide and config comments now call it 24h volume; order-book liquidity is labelled as such (Markets, Ledger). README and the agent guide note that only a handful of in-mandate markets clear the default $5,000 and that lowering it is the human's call (thresholds unchanged). The guide documents getBudget's order budget, the rejection cooldown and the new mode-wide getFlaggedTokens / getRecentStops calls. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
… test F6) searchGamma without text fetched the global top 100 markets by 24h volume and then filtered by category; on a day dominated by US midterms / sports / crypto that left nothing for economics, politics-non-us or weather-climate (MCP search_markets, the Markets page filter and the agent scan all returned []). With a category and no text it now queries Gamma /events?tag_slug=<tag> (active, open, ordered by 24h volume, up to 3 pages of 50 per tag) for every tags / when_tags entry of the category's rules in categories.yaml, flattens, dedupes, re-categorizes and ranks the merged hits by 24h volume. A single failing tag is skipped; a 429 or every tag failing throws (MarketService keeps its 60 s cache and backoff). The Gamma tag_slug / order parameters on /events are marked VERIFY. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
…Mac test leftover) Setting forced rights back to auto only cleared the flag: a forced trading bucket kept trading with its allocation, and since the rules never demote a healthy trading bucket it could stay there indefinitely. Now auto resets a forced trading bucket to shadow (allocation 0, audited as a rights change by the human) and runs evaluateRights for that bucket only; a bucket whose record qualifies is promoted again straight away. Other forced states just lose the force and are evaluated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
Log entry, morning-summary note (min_liquidity_usd is 24h volume and few in-mandate markets clear $5,000; the user may want to lower it; VERIFY the Gamma tag search), new decisions R193-R199 and amendments to R1, R57, R160, R165, R170, R173, R187. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
- Rejection cooldown gated at the entry of placeLimit / placeMarketable / placeBinance (before order sync and book reads); one stored refusal and one audit entry per cooldown episode; system-wide refusals (clock, live off, market data, state, global halt) do not count. - Category market search: cache key without limit (fetch once, slice), shared in-flight fetch, 15 s fan-out deadline with partial results, 2 pages per tag, category fan-outs weighted in the per-principal search limit. - Executor: effective bid TTL = min(bid_ttl_minutes, resting_order_ttl_minutes) via getBudget().maxRestingTtlMinutes; refreshAt from the placement's expiresAt. - getFlaggedTokens filtered by mode in SQL; indexes for recentStops and the cooldown; Position Manager never rests a crossing exit at 0.99 nor retries a refused exit every cycle; un-forcing short re-evaluates medium, and a medium bucket qualified only on the relaxation drops back. - PROGRESS: R200-R204, amended R193-R196, R198, R199. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QjwENrgG4j59smeu31MTHW
markb-1
marked this pull request as ready for review
October 31, 2026 21:10
markb-1
added a commit
that referenced
this pull request
Nov 1, 2026
Brings in PRs #2 and #3. Their README edits now live in the guides: "Hosting on a VPS" in docs/guide/install.md, the min_liquidity_usd note in operations.md, the executor / position manager / copy-trading changes in strategies.md, and check-polymarket in development.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Phase 5 of
docs/SPEC.md(§9): the strategy templates that turn the ledger and the agent's research into orders. It builds on Phases 1–4 (#1). Every order still goes throughOrderService→RiskEngine.Draft until tested on macOS.
What's in it
min_edgeafter fees and enough edge per day. Bids are sized at a quarter of the Kelly amount, capped by budget and per-market limits, and ranked by edge per day. It re-quotes on forecast changes, never outbids itself, and doesn't buy back after a stop until the forecast is renewed.builtin_role) getsctx.portfolio.implies,date_ladderandexclusive_sumconstraints. Prices that contradict each other are traded by buying the complement token, since there is no shorting. It caps unhedged exposure, escalates or flattens partially filled baskets, and requires same-event ornegRisklegs for exclusive or exhaustive sets.max_chaseand never chase; trades are de-duplicated across pages.Agent rules
How it was built
Each chunk was implemented, independently reviewed, and every finding fixed:
1,167 tests pass. CI passed on macOS, Windows and Ubuntu for every chunk; the run for the final commit is in progress. Decisions R160–R192 are in
docs/PROGRESS.md; README has a "Strategies" section.Notes
new, so their bots start in paper and go through the ramp.logIndex, itstype=TRADEfilter and time-based paging. Fallbacks are in place.Generated by Claude Code