release 23 (b87de0fde0)
Browse filesFiles changed (22)
- CHANGELOG.md+84
- console/src/components/Layout.tsx+30-1
- console/src/context.tsx+8
- console/src/pages/Overview.tsx+16-12
- fly_trader/agent/crash_exit.py+3-1
- fly_trader/agent/fly_live.py+34-8
- fly_trader/agent/fly_session.py+21-8
- fly_trader/agent/paper_trading.py+100-15
- fly_trader/agent/sizing.py+12-8
- fly_trader/config.py+17
- fly_trader/execution/broker_paper.py+5-3
- fly_trader/execution/ledger.py+6-4
- fly_trader/execution/worker.py+8-3
- fly_trader/rh/accounting.py+31-4
- fly_trader/rh/exec.py+5-2
- fly_trader/rh/live.py+30-5
- fly_trader/ui/api/meta.py+71-3
- fly_trader/ui/api/overview.py+39-15
- fly_trader/ui/api/safety.py+2-1
- fly_trader/ui/api/ticker.py+7-5
- fly_trader/ui/api/trades.py+6-5
- fly_trader/ui/static/console/assets/index-fghN0RdQ.jsDeleted
2 unmodified lines3456782 unmodified linesReleases are identified by date. The Docker distribution (branch `distribution`, Hugging Face `bryceweiner/fly-trader`)ships signed releases built from this development line.## 2026-11-14, release 22: A self-updated trader starts again after a restart### Upgrading2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091922 unmodified linesReleases are identified by date. The Docker distribution (branch `distribution`, Hugging Face `bryceweiner/fly-trader`)ships signed releases built from this development line.## 2026-11-18, release 23: A held coin the model picks again under its entry is bought once more, and a crash-sold coin waits an hour### Upgrading- **Nothing to do on a Docker install:** its updater installs this release within the hour, as usual. The models arerelease 19's (selector and fly of 2026-10-26).- **On by default:** the re-pick add and the crash cooldown. `REPICK_ADD_DIP=0` and `CRASH_REBUY_COOLDOWN_MIN=0` turnthem off; Robinhood Chain sizes as before unless `RH_KELLY_FRACTION` is set.### Both chains- **A held coin the model picks again 10 % or more under its entry is bought once more.** The selector re-picks coins italready holds every minute, and those picks were simply skipped. On the real logged re-picks a buy there made money:10-17..11-18, +8.6 % a trade on Solana (paper_fly, 99 adds) and +11.5 % on RH; the archived books of 09-20..10-16, +5to +7 % on Solana and about +30 % on RH; every book of both periods positive. A plain dipwithout the re-pick did less on Solana in 4 of 5 books, so the model's pick matters.- **One add per position,** at the first re-pick 5 or more minutes after the entry at or under 90 % of the entry price(`REPICK_ADD_DIP`, `REPICK_ADD_MIN_S`, `REPICK_ADD_CHAINS`; `REPICK_ADD_DIP=0` turns it off).- **It joins the position:** the add's tokens and cost go into the open position, its entry price is the average, andthe position is then held its hold from the add (it was held 240 minutes from the add in the study). Sized as thepick is, with the position's cost counted against the bankroll cap, the label size and the creator-heavy cap, so aposition never grows past them.- **The wallet adds only to its own position of the same entry,** never while an order of the token is queued or inflight, never to a plain v4 coin while `RH_V4_WALLET` is off, and never tries a failed add again. A decision of kind`fly_add` (`fly_rh_add` on RH); the ticker shows it as a buy, "added".- **The live-vs-paper gap check leaves out a trade paper added to:** the wallet's add may have been sized out orskipped, and the two are then no longer the same trade.### Solana- **A coin sold in a crash exit is not bought again for an hour.** Since the crash exit went live on 2026-11-07 thewallet bought crashed coins back within the hour 29 times: 25 lost, −0.586 SOL by its own fills, and every Solana bookshows the same. The crash sale alone was about even. `CRASH_REBUY_COOLDOWN_MIN` (60; 0 buys back at once, as before);the skipped pick's rail is `crashed`. A book counts its own crash sales; the fly's book, which the wallet mirrors, alsothe wallet's. Read in the same query as the take-profit cooldown, so the minute's live entries wait on nothing new.### Robinhood Chain- **Robinhood Chain can size at its own Kelly fraction.** `RH_KELLY_FRACTION` sizes Robinhood Chain's buys (its paperbooks and the wallet); unset, it is `KELLY_FRACTION`, so an install sizes exactly as before until it is set. Over2026-10-17..11-18 the RH wallet here grew 19 % to Solana's 4.6 %, and its real fills cost about 2.7 % a side whateverthe size at today's stakes (0.05..0.3 % of a pool): twice the stake added about 0.1..0.3 points a trade. The Safetypage shows both fractions when they differ.### Fly- **The selector's would-be trades keep their features after they resolve.** The fly scores every eligible coin eachminute and dropped each row's feature vector once its outcome was known, so no live pick could ever train or test abad-coin veto (0 of 5,739 resolved picks kept it, 2026-11-18). A row the selector would trade keeps its features andoutcome for a year (about 240 a day, about 26 MB a year); every other row loses them as before and goes after 35 days.### Platform- **The stream relay can keep graduated coins' token transfers.** Split wallets gathering supply before a dump (7rTNgVdQ,Saturween, 519AMD) never show in the swaps, and the relay dropped every transfer. With `RELAY_TRANSFERS_DIR` set itwrites each transfer of a coin it has seen trade on PumpSwap, whole, to a gzipped file per UTC day, on its own thread,within a daily size cap and a free-disk floor, and deletes files after 14 days. Nothing more is forwarded: the clients'stream is unchanged. `stream_relay/pull_transfers.sh` copies the files to `data/corpus/transfers/`. Off until thesetting is made on the relay server.### Console- **The model at work is the selector the fly buys on: #791, not "#154, switching to #791".** The Selector tile, theOverview's description, its open positions' hold and the Model page took the newest selector session marked running.After the handover the selector book has no session, and three that died unclosed were still marked running, thenewest from 10-17 on #154 with a 120-minute hold. They now read the fly's gate, else the selector book's own report.The tile no longer says "switching to" while a model is pinned.- **Without live money, the Overview and the Trades page show the paper book that trades: the fly's after itshandover.** They showed the selector book, which stops at the handover, so a paper-only install's pages stayed at 5.42 SOLwith no trade since 2026-11-04 while its fly traded every day (5.30 SOL by 11-11). The money's numbers, the openpositions, the wealth chart and the Trades page's default book now follow the seat. A machine with live money showsthe wallet as before, and one with no handover the selector's book.- **The Overview's setups chart counts the book that trades: the fly's after its handover.** It counted the selectorbook alone, which stops at the handover, so a paper-only install's chart showed no setups from 2026-11-04 while its fly tradedevery day (19 paper trades by 11-08). The selector's picks count until the handover and the fly's from then on, andthe chart says which. A machine with no handover, like the Mac, shows the selector's as before.- **The code, selector and fly in use show along the top of every page,** so two installs can be compared at a glance.- **Code:** the git commit the console started from, marked when tracked files had uncommitted changes. A Docker installshows its release number and commit, and a deploy can set its own label with `FLY_CODE_VERSION`.- **Models:** each chain's fly and the selector its buys need (the one it follows, which the selector book also trades;after a handover the selector book stops and only the fly's gate is current), by the first 8 characters of theirfile's sha256. The same model shows the same hash on every machine. Hovering shows the model's number in this install and its file name. The two chains show asone pair while they run the same models.## 2026-11-14, release 22: A self-updated trader starts again after a restart### Upgrading
1 unmodified line2345678105 unmodified lines1141151161171181193 unmodified lines1231241251261271281 unmodified line// groups, an off-canvas panel on phones), the status strip under it on every page, and the footer.import { useEffect, useState, type ReactNode } from 'react'import { NavLink, useLocation } from 'react-router'import { useApp } from '../context'import { InspectorDrawer } from '../fly/Inspector'import { LiveToasts } from '../fly/Ticker'import { useConn } from '../lib/hooks'105 unmodified lines)}function TopBar({ onMenu }: { onMenu: () => void }) {const conn = useConn()return (3 unmodified lines<div className="topbar-logo-header d-none d-lg-flex"><Logo /></div><div className="mobile-toggle-menu d-block d-lg-none" role="button" aria-label="Menu" onClick={onMenu}><i className="bx bx-menu" style={{ fontSize: 26 }} /></div><div className="search-bar flex-grow-1"><SearchBox /></div><div className="top-menu ms-auto"><ul className="navbar-nav align-items-center gap-1"><li className="nav-item d-flex align-items-center" title={conn === 'open' ? 'Live: the console pushes changes as they happen' : 'Reconnecting to the console…'}>1 unmodified line2345678105 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461473 unmodified lines1511521531541551561571 unmodified line// groups, an off-canvas panel on phones), the status strip under it on every page, and the footer.import { useEffect, useState, type ReactNode } from 'react'import { NavLink, useLocation } from 'react-router'import { useApp, type ModelVersion } from '../context'import { InspectorDrawer } from '../fly/Inspector'import { LiveToasts } from '../fly/Ticker'import { useConn } from '../lib/hooks'105 unmodified lines)}const CHAIN = { sol: 'SOL', rh: 'RH' } as constfunction modelTip(kind: string, m: ModelVersion | null): string {return m ? `${kind} #${m.id}${m.file ? ` · ${m.file}` : ''}${m.sha ? ` · sha256 ${m.sha}…` : ''}` : `${kind}: not reported yet`}/** Code, selector and fly along the top: the models by their file's sha256 (the same on every machine running the same model). */function VersionStrip() {const { meta } = useApp()const v = meta?.versionsif (!v) return nullconst key = (m: ModelVersion | null) => m?.sha ?? (m ? `#${m.id}` : '—')const same = v.models.every((x) => key(x.selector) === key(v.models[0]?.selector) && key(x.fly) === key(v.models[0]?.fly))const groups = same && v.models.length ? [{ label: '', m: v.models[0] }] : v.models.map((m) => ({ label: CHAIN[m.chain], m }))return (<div className="d-none d-lg-flex align-items-center gap-3 version-strip" style={{ fontSize: 12, color: 'var(--fly-muted)', whiteSpace: 'nowrap' }}><span title={v.code.detail}>code <b className="font-monospace" style={{ color: v.code.changed ? 'var(--bs-warning)' : 'inherit' }}>{v.code.label}</b></span>{groups.map(({ label, m }) => (<span key={label || 'all'} className="d-flex gap-2">{label && <span>{label}</span>}<span title={modelTip('selector', m.selector)}>selector <b className="font-monospace">{key(m.selector)}</b></span><span title={modelTip('fly', m.fly)}>fly <b className="font-monospace">{key(m.fly)}</b></span></span>))}</div>)}function TopBar({ onMenu }: { onMenu: () => void }) {const conn = useConn()return (3 unmodified lines<div className="topbar-logo-header d-none d-lg-flex"><Logo /></div><div className="mobile-toggle-menu d-block d-lg-none" role="button" aria-label="Menu" onClick={onMenu}><i className="bx bx-menu" style={{ fontSize: 26 }} /></div><div className="search-bar flex-grow-1"><SearchBox /></div><VersionStrip /><div className="top-menu ms-auto"><ul className="navbar-nav align-items-center gap-1"><li className="nav-item d-flex align-items-center" title={conn === 'open' ? 'Live: the console pushes changes as they happen' : 'Reconnecting to the console…'}>
12 unmodified lines13141516171812 unmodified linesmarkets: Market[]kalshi_books: Record<string, string>version: string}/** What the inspector opens: a memecoin token on a chain, or a Kalshi market ticker. */12 unmodified lines131415161718192021222324252612 unmodified linesmarkets: Market[]kalshi_books: Record<string, string>version: stringversions?: Versions}/** What this console runs: its code (read when it started) and each chain's selector and fly (the `meta` topic). */export type ModelVersion = { id: number; sha: string | null; file: string | null }export type Versions = {code: { label: string; commit: string | null; release: number | null; changed: boolean; source: string; detail: string }models: { chain: 'sol' | 'rh'; selector: ModelVersion | null; fly: ModelVersion | null }[]}/** What the inspector opens: a memecoin token on a chain, or a Kalshi market ticker. */
123427 unmodified lines32333435363745 unmodified lines8384858687888920 unmodified lines110111112113114115116190 unmodified lines3073083093103113123133143153163173183193203213223233241 unmodified line3263273283293303313323333343353363373383393403413423436 unmodified lines350351352353354355356// Overview, laid out like Dashtreme's index: the selector book's KPI widgets, what the system is doing in plain words// beside the win rate, the money's book (its wealth and open positions), the fly's brain, this minute's scoring with the top// scores, the race between the selector and the plastic fly, the rising + clean test and its go-live, the selector's setups// per day, and the live ticker (ui/api/overview.py; the brain ui/api/brain.py).27 unmodified linesdd_spark: number[]wealth_help: stringlive: booleanlabel: string}type Top = { mint: string; token: string; score: number }45 unmodified linesreturn <button type="button" className="link-btn" title={mint} onClick={() => openInspector({ kind: 'token', chain, mint })}>{token}</button>}/** The selector book's KPI row, then the narrative beside the win rate. */function SummaryPanel() {const { chain } = useApp()const s = useTopic<Summary>('overview.summary', { chain })20 unmodified lines<Card title="In plain words" icon="bx-message-square-detail" className="flex-fill"><Md text={d.narrative} /></Card></div><div className="col-12 col-xl-4 d-flex"><Card title="Win rate" icon="target" sub={d.live ? 'closed live trades that made money' : 'closed trades of the selector book that made money'} className="flex-fill" bodyClass="pb-0"><RadialGauge value={winRate} label="winners" display={winRate === null ? '—' : `${Math.round(winRate * 100)}%`} height={210} /><RowGroup items={[{ label: 'closed', value: int(d.closed) }, { label: 'winners', value: int(d.wins) }, { label: `realized ${u}`, value: num(d.pnl ?? 0, 3, true) }]} /></Card>190 unmodified lines}type SetupDay = { day: string; setups: number | null; trades: number | null; live: number; ran: number }type SetupChain = { chain: string; name: string; setups: number; trades: number; live: number; days: SetupDay[] }type Setups = { tz: string; n_days: number; gap_min: number; chains: SetupChain[] }const dayLabel = (iso: string) => new Date(`${iso}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })const PARTIAL = 0.9 // a day the selector book ran less of than this is flagged/** The selector's setups per UTC day over 30 days, beside the trades it took: one chart per chain, Solana on the left,* Robinhood Chain on the right. Fewer setups is a quieter market; setups without trades are vetoes. */function SetupsPanel() {const s = useTopic<Setups>('overview.setups')return (<Card title={`Setups · ${s.data?.n_days ?? 30} days`} icon="target"sub="the buying chances the selector found each UTC day, and the trades it took · fewer setups is a quieter market, not a blocked bot"><Loaded state={s} height={300}>{(d) => (<div className="row g-4">1 unmodified lineconst last = c.days.length - 1const partial = c.days.filter((x, i) => i < last && x.setups !== null && x.ran < PARTIAL)const off = c.days.filter((x) => x.setups === null).lengthreturn (<div key={c.chain} className={`col-12 ${d.chains.length > 1 ? 'col-xl-6' : ''}`}><div className="d-flex align-items-baseline gap-2 mb-1"><h6 className="m-0" style={{ color: '#fff' }}>{c.name}</h6><span className="caption m-0">{int(c.setups)} setups · {int(c.trades)} selector trades · {int(c.live)} live</span></div><BarChart categories={c.days.map((x, i) => (i === last ? 'today' : dayLabel(x.day)))} height={260}series={[{ name: 'setups', data: c.days.map((x) => x.setups) }, { name: 'selector trades', data: c.days.map((x) => x.trades) }]}yFormat={(v) => (Number.isInteger(v) ? int(v) : '')} />{(partial.length > 0 || off > 0) && (<Caption>{off > 0 && `${off} day${off > 1 ? 's' : ''} without a bar: the selector book was not running. `}{partial.length > 0 && `Ran only part of ${partial.slice(-6).map((x) => `${dayLabel(x.day)} (${Math.round(x.ran * 100)}%)`).join(', ')}`}{partial.length > 6 && ` and ${partial.length - 6} earlier day${partial.length > 7 ? 's' : ''}`}{partial.length > 0 && ': fewer setups there say nothing of the market.'}6 unmodified lines)}</Loaded><Caption>A setup is a token the selector picked while not holding it; its picks less than {s.data?.gap_min ?? 30} minutes apart count once. A setup itdid not trade was vetoed (dump veto, win filter). Days are UTC.</Caption></Card>123427 unmodified lines3233343536373845 unmodified lines8485868788899020 unmodified lines111112113114115116117190 unmodified lines3083093103113123133143153163173183193203213223233243253261 unmodified line3283293303313323333343353363373383393403413423433443453463476 unmodified lines354355356357358359360// Overview, laid out like Dashtreme's index: the money book's KPI widgets (live, else the paper book in the seat), what the system is doing in plain words// beside the win rate, the money's book (its wealth and open positions), the fly's brain, this minute's scoring with the top// scores, the race between the selector and the plastic fly, the rising + clean test and its go-live, the selector's setups// per day, and the live ticker (ui/api/overview.py; the brain ui/api/brain.py).27 unmodified linesdd_spark: number[]wealth_help: stringlive: booleanbook?: stringlabel: string}type Top = { mint: string; token: string; score: number }45 unmodified linesreturn <button type="button" className="link-btn" title={mint} onClick={() => openInspector({ kind: 'token', chain, mint })}>{token}</button>}/** The money book's KPI row (live, else the paper book in the seat), then the narrative beside the win rate. */function SummaryPanel() {const { chain } = useApp()const s = useTopic<Summary>('overview.summary', { chain })20 unmodified lines<Card title="In plain words" icon="bx-message-square-detail" className="flex-fill"><Md text={d.narrative} /></Card></div><div className="col-12 col-xl-4 d-flex"><Card title="Win rate" icon="target" sub={d.live ? 'closed live trades that made money' : `closed trades of ${d.book?.endsWith('fly') ? "the fly's paper book" : 'the selector book'} that made money`} className="flex-fill" bodyClass="pb-0"><RadialGauge value={winRate} label="winners" display={winRate === null ? '—' : `${Math.round(winRate * 100)}%`} height={210} /><RowGroup items={[{ label: 'closed', value: int(d.closed) }, { label: 'winners', value: int(d.wins) }, { label: `realized ${u}`, value: num(d.pnl ?? 0, 3, true) }]} /></Card>190 unmodified lines}type SetupDay = { day: string; setups: number | null; trades: number | null; live: number; ran: number }type SetupChain = { chain: string; name: string; setups: number; trades: number; live: number; days: SetupDay[]; seat?: { book: 'selector' | 'fly'; since: string | null } }type Setups = { tz: string; n_days: number; gap_min: number; chains: SetupChain[] }const dayLabel = (iso: string) => new Date(`${iso}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })const PARTIAL = 0.9 // a day the trading book ran less of than this is flagged/** The trading book's setups per UTC day over 30 days, beside the trades it took: the selector's until the chain's handover,* the fly's from then on. One chart per chain, Solana on the left, Robinhood Chain on the right. Fewer setups is a quieter* market; setups without trades are vetoes. */function SetupsPanel() {const s = useTopic<Setups>('overview.setups')return (<Card title={`Setups · ${s.data?.n_days ?? 30} days`} icon="target"sub="the buying chances the trading book found each UTC day, and the trades it took · fewer setups is a quieter market, not a blocked bot"><Loaded state={s} height={300}>{(d) => (<div className="row g-4">1 unmodified lineconst last = c.days.length - 1const partial = c.days.filter((x, i) => i < last && x.setups !== null && x.ran < PARTIAL)const off = c.days.filter((x) => x.setups === null).lengthconst who = c.seat?.book === 'fly' ? 'fly' : 'selector'return (<div key={c.chain} className={`col-12 ${d.chains.length > 1 ? 'col-xl-6' : ''}`}><div className="d-flex align-items-baseline gap-2 mb-1"><h6 className="m-0" style={{ color: '#fff' }}>{c.name}</h6><span className="caption m-0">{int(c.setups)} setups · {int(c.trades)} {who} trades · {int(c.live)} live</span></div><BarChart categories={c.days.map((x, i) => (i === last ? 'today' : dayLabel(x.day)))} height={260}series={[{ name: 'setups', data: c.days.map((x) => x.setups) }, { name: `${who} trades`, data: c.days.map((x) => x.trades) }]}yFormat={(v) => (Number.isInteger(v) ? int(v) : '')} />{c.seat?.since && <Caption>The fly took the selector's seat on {dayLabel(c.seat.since.slice(0, 10))}: from then on the bars are the fly's picks and trades.</Caption>}{(partial.length > 0 || off > 0) && (<Caption>{off > 0 && `${off} day${off > 1 ? 's' : ''} without a bar: the trading book was not running. `}{partial.length > 0 && `Ran only part of ${partial.slice(-6).map((x) => `${dayLabel(x.day)} (${Math.round(x.ran * 100)}%)`).join(', ')}`}{partial.length > 6 && ` and ${partial.length - 6} earlier day${partial.length > 7 ? 's' : ''}`}{partial.length > 0 && ': fewer setups there say nothing of the market.'}6 unmodified lines)}</Loaded><Caption>A setup is a token the trading book picked while not holding it; its picks less than {s.data?.gap_min ?? 30} minutes apart count once. A setup itdid not trade was vetoed (dump veto, win filter). Days are UTC.</Caption></Card>
16 unmodified lines1718192021222316 unmodified linesbookkeeping, as forced 'crash' exits, at the first price the stream saw ``FILL_DELAY_S`` or more after the crash(about when the wallet's sale lands; the crash's own price until one comes): a paper fill at the crash's very pricewould beat the wallet's on every crash and read as an execution gap (agent/fly_live.LiveMirror.gap).- A crashed coin may be bought again whenever it passes the bar again.- The held coins are re-read every ``REFRESH_S`` (a new position is watched within seconds of its entry)."""from __future__ import annotations16 unmodified lines17181920212223242516 unmodified linesbookkeeping, as forced 'crash' exits, at the first price the stream saw ``FILL_DELAY_S`` or more after the crash(about when the wallet's sale lands; the crash's own price until one comes): a paper fill at the crash's very pricewould beat the wallet's on every crash and read as an execution gap (agent/fly_live.LiveMirror.gap).- A crashed coin is not bought again by a book that sold it in a crash for ``config.CRASH_REBUY_COOLDOWN_MIN`` (60 min;agent/paper_trading.cooling, rail 'crashed'), then whenever it passes the bar again: from 11-07 to 11-18 thewallet's rebuys within an hour of a crash sale lost 25 of 29 times, -0.586 SOL (data/scratch/bear_20261118).- The held coins are re-read every ``REFRESH_S`` (a new position is watched within seconds of its entry)."""from __future__ import annotations
20 unmodified lines212223242526272881 unmodified lines1101111121131141151161177 unmodified lines125126127128129130131117 unmodified lines24925025125225325425517 unmodified lines2732742752762772788 unmodified lines287288289290291292293137 unmodified lines43143243343443543643743843944020 unmodified linesagain this minute), never more than ``MAX_ENTRY_CHASE`` above its paper fill price, unless the kill switch, thecircuit breaker (until ``CIRCUIT_COOLDOWN_S`` after its last failure) or paused entries block. A buy that failedwithout moving anything is sent again, re-sized, on the next minutes while its paper position is open, up to``ENTRY_RETRY_MIN`` after its decision. Every paper entry the wallet did not take is a decisions row of this book(kind 'blocked', the reason as its rail, ``of_decision`` the paper entry);- bookkeeping (``after``: once every chain's live orders are out): ``DEAD_BAG_S`` past the hold a position that couldnot be sold is written off (dead-bag: closed at 0, so it leaves wealth); the gap: over the last ``GAP_TRADES`` closedlive trades, the mean return per trade trailing the paper mirror's same decisions by more than ``GAP_MAX`` pauses81 unmodified linesif f is None or r.ok:returnrail = "price ran" if (r.error or "").startswith("price ran") else "entry failed"self._blocked(conn, ctx, run_id, beat_id, f["e"], rail, (r.error or "failed")[:300], r.request.size_sol, attempt=f["tries"], retry=bool(r.retryable))if r.retryable:self.failed[did] = {**f, "error": r.error}def _retry_over(self, conn, ctx, did: int, f: dict) -> str | None:7 unmodified linesdef _buy(self, e: dict, size: float, retry: int = 0) -> bool:return self.worker.submit(ExecRequest(decision_id=e["decision_id"], mint=e["mint"], pool=e["info"]["pool"], side="buy", amount_in=int(size * config.LAMPORTS_PER_SOL),slippage_bps=config.SLIPPAGE_ENTRY_BPS, max_slippage_bps=config.MAX_SLIPPAGE_ENTRY_BPS, decimals=int(e["info"]["decimals"] or 6),size_sol=size, hold_s=e.get("hold_s"), strategy=e.get("strategy"), ref_price=e.get("ref_price"), retry=retry))def read_balance(self) -> int:"""The wallet's SOL (lamports); started beside the minute's scoring by live_first.prefetch."""117 unmodified linesheld_mints = {p["mint"] for p in opens if p["mint"] not in selling} | (inflight - selling)c = rails.load_circuit(conn)blocked = "kill switch" if c.kill_switch else "circuit tripped" if rails.breaker_blocks(c) else "paused" if c.entries_paused else Nonen_enter = n_retry = 0; skipped = []if self.failed or entries:sol_free = live_first.take_balance(self, ctx.m1_epoch) / config.LAMPORTS_PER_SOL; self.wallet_sol = sol_free# sized on the whole book (not a dead-bag ``after`` writes off this minute), spent only from the wallet's SOL (cash)17 unmodified linesself.failed.pop(did); self.sent[did] = {**f, "e": e, "tries": f["tries"] + 1}n_enter += 1; n_retry += 1; cash -= size; held_mints.add(e["mint"])for e in entries:if e["mint"] in held_mints:skipped.append((e["mint"], "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "the wallet holds this token or has an order of it queued"); continuesize, why = sizing.size_position(e["score"], e.get("threshold", line), e.get("table") or table or [], bankroll, cash, e["info"]["resq"],8 unmodified lineselse:skipped.append((e["mint"], "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "an order of this token is queued or in flight", size)self.due_mark = self.mark_ctx = (ctx, beat_id)return {"stage": "trading live", "wallet_sol": self.wallet_sol, "entered": n_enter, "retried": n_retry, "exited": ex["exited"], "liquidated": ex["liquidated"],"in_flight": len(inflight), "blocked": blocked, "skipped": skipped[:10], "failed_orders": sum(1 for r in drained if not r.ok),"awaiting_retry": len(self.failed)}137 unmodified linesdef gap(self, conn) -> dict:"""Live vs its paper mirror on the same decisions; pauses entries when live trails by more than ``GAP_MAX`` per trade.An operator's Sell Now (forced 'operator') is the operator's choice, not an execution gap: left out."""rows = conn.execute(f"""SELECT l.realized_sol / NULLIF(l.cost_sol, 0) AS rl, p.realized_sol / NULLIF(p.cost_sol, 0) AS rpFROM positions l JOIN positions p ON p.entry_decision_id = l.entry_decision_id AND p.book = '{MIRROR}' AND p.status = 'closed'WHERE l.book = '{BOOK}' AND l.status = 'closed' AND l.entry_decision_id IS NOT NULL AND COALESCE(l.forced_exit_kind, '') <> 'operator'ORDER BY l.closed_at DESC LIMIT %s""", (GAP_TRADES,)).fetchall()rl = np.array([r["rl"] for r in rows if r["rl"] is not None and r["rp"] is not None], dtype=np.float64)rp = np.array([r["rp"] for r in rows if r["rl"] is not None and r["rp"] is not None], dtype=np.float64)20 unmodified lines212223242526272829303181 unmodified lines1131141151161171181191201217 unmodified lines129130131132133134135136117 unmodified lines25425525625725825926017 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003018 unmodified lines310311312313314315316137 unmodified lines45445545645745845946046146246346446546620 unmodified linesagain this minute), never more than ``MAX_ENTRY_CHASE`` above its paper fill price, unless the kill switch, thecircuit breaker (until ``CIRCUIT_COOLDOWN_S`` after its last failure) or paused entries block. A buy that failedwithout moving anything is sent again, re-sized, on the next minutes while its paper position is open, up to``ENTRY_RETRY_MIN`` after its decision. A paper re-pick add (``of_entry``, agent/paper_trading.plan_minute) buys into thewallet's open position of that same entry decision, sized from the wallet with that position's cost against the caps,never while an order of the token is queued or in flight, never retried; the position is then held its new hold. Everypaper entry the wallet did not take is a decisions row of this book (kind 'blocked', the reason as its rail,``of_decision`` the paper entry);- bookkeeping (``after``: once every chain's live orders are out): ``DEAD_BAG_S`` past the hold a position that couldnot be sold is written off (dead-bag: closed at 0, so it leaves wealth); the gap: over the last ``GAP_TRADES`` closedlive trades, the mean return per trade trailing the paper mirror's same decisions by more than ``GAP_MAX`` pauses81 unmodified linesif f is None or r.ok:returnrail = "price ran" if (r.error or "").startswith("price ran") else "entry failed"add = f["e"].get("of_entry") is not None # a re-pick add is not tried againself._blocked(conn, ctx, run_id, beat_id, f["e"], rail, (r.error or "failed")[:300], r.request.size_sol, attempt=f["tries"], retry=bool(r.retryable) and not add)if r.retryable and not add:self.failed[did] = {**f, "error": r.error}def _retry_over(self, conn, ctx, did: int, f: dict) -> str | None:7 unmodified linesdef _buy(self, e: dict, size: float, retry: int = 0) -> bool:return self.worker.submit(ExecRequest(decision_id=e["decision_id"], mint=e["mint"], pool=e["info"]["pool"], side="buy", amount_in=int(size * config.LAMPORTS_PER_SOL),slippage_bps=config.SLIPPAGE_ENTRY_BPS, max_slippage_bps=config.MAX_SLIPPAGE_ENTRY_BPS, decimals=int(e["info"]["decimals"] or 6),size_sol=size, hold_s=e.get("hold_s"), strategy=e.get("strategy"), ref_price=e.get("ref_price"), retry=retry,add=e.get("of_entry") is not None))def read_balance(self) -> int:"""The wallet's SOL (lamports); started beside the minute's scoring by live_first.prefetch."""117 unmodified linesheld_mints = {p["mint"] for p in opens if p["mint"] not in selling} | (inflight - selling)c = rails.load_circuit(conn)blocked = "kill switch" if c.kill_switch else "circuit tripped" if rails.breaker_blocks(c) else "paused" if c.entries_paused else Nonen_enter = n_retry = n_add = 0; skipped = []if self.failed or entries:sol_free = live_first.take_balance(self, ctx.m1_epoch) / config.LAMPORTS_PER_SOL; self.wallet_sol = sol_free# sized on the whole book (not a dead-bag ``after`` writes off this minute), spent only from the wallet's SOL (cash)17 unmodified linesself.failed.pop(did); self.sent[did] = {**f, "e": e, "tries": f["tries"] + 1}n_enter += 1; n_retry += 1; cash -= size; held_mints.add(e["mint"])for e in entries:if e.get("of_entry") is not None: # a paper re-pick add: into the wallet's position of the same entry decisionp = next((q for q in opens if q["mint"] == e["mint"]), None)rail = blocked or ("add: no such position" if p is None or p.get("entry_decision_id") != e["of_entry"] else None) \or ("held" if e["mint"] in inflight else None)size, why = (0.0, "") if rail else sizing.size_position(e["score"], e.get("threshold", line), e.get("table") or table or [], bankroll, cash, e["info"]["resq"],flat=config.FLY_SIZING == "flat", margin=e.get("size_margin"),creator_heavy=bool(e["info"].get("creator_heavy")), stake_x=e.get("stake_x", 1.0),held_cost=float(p["cost_sol"]))if rail or size <= 0:why = {"held": "an order of this token is queued or in flight", "add: no such position": "the wallet holds no position of this add's entry"}.get(rail, rail or why)skipped.append((e["mint"], rail or why)); self._blocked(conn, ctx, run_id, beat_id, e, rail or "sizing", why, size, add=True); continueif self._buy(e, size):n_add += 1; cash -= size; self.sent[e["decision_id"]] = {"e": e, "ts": m1, "tries": 1}conn.execute("UPDATE decisions SET book_targets = array_append(COALESCE(book_targets, '{}'), 'live'), detail = detail || %s::jsonb WHERE id = %s",(json.dumps({"live_stake_x": e["stake_x"]} if "stake_x" in e else {}), e["decision_id"]))else:skipped.append((e["mint"], "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "an order of this token is queued or in flight", size, add=True)continueif e["mint"] in held_mints:skipped.append((e["mint"], "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "the wallet holds this token or has an order of it queued"); continuesize, why = sizing.size_position(e["score"], e.get("threshold", line), e.get("table") or table or [], bankroll, cash, e["info"]["resq"],8 unmodified lineselse:skipped.append((e["mint"], "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "an order of this token is queued or in flight", size)self.due_mark = self.mark_ctx = (ctx, beat_id)return {"stage": "trading live", "wallet_sol": self.wallet_sol, "entered": n_enter, "retried": n_retry, "added": n_add, "exited": ex["exited"], "liquidated": ex["liquidated"],"in_flight": len(inflight), "blocked": blocked, "skipped": skipped[:10], "failed_orders": sum(1 for r in drained if not r.ok),"awaiting_retry": len(self.failed)}137 unmodified linesdef gap(self, conn) -> dict:"""Live vs its paper mirror on the same decisions; pauses entries when live trails by more than ``GAP_MAX`` per trade.An operator's Sell Now (forced 'operator') is the operator's choice, not an execution gap: left out; so is a trade paperadded to on a re-pick (agent/paper_trading.plan_minute): the wallet's add may have been sized out or skipped, and thetwo are then no longer the same trade."""rows = conn.execute(f"""SELECT l.realized_sol / NULLIF(l.cost_sol, 0) AS rl, p.realized_sol / NULLIF(p.cost_sol, 0) AS rpFROM positions l JOIN positions p ON p.entry_decision_id = l.entry_decision_id AND p.book = '{MIRROR}' AND p.status = 'closed'WHERE l.book = '{BOOK}' AND l.status = 'closed' AND l.entry_decision_id IS NOT NULL AND COALESCE(l.forced_exit_kind, '') <> 'operator'AND NOT EXISTS (SELECT 1 FROM decisions a WHERE a.kind = 'fly_add' AND (a.detail->>'of_entry')::bigint = l.entry_decision_id)ORDER BY l.closed_at DESC LIMIT %s""", (GAP_TRADES,)).fetchall()rl = np.array([r["rl"] for r in rows if r["rl"] is not None and r["rp"] is not None], dtype=np.float64)rp = np.array([r["rp"] for r in rows if r["rl"] is not None and r["rp"] is not None], dtype=np.float64)
16 unmodified lines1718192021222349 unmodified lines737475767778333 unmodified lines412413414415416417418138 unmodified lines55755855956056156256312 unmodified lines576577578579580581582583584585586587553 unmodified lines114111421143114411451146114716 unmodified linesseat; before that (LIVE_WITHOUT_HANDOVER) the selector's -- the fly's learned veto binds only its paper book, which iswhat its race measures;4. after the live orders (``after_minute``): the scored rows stored (``fly_scored``: pending rows keep the featurevector, so tags survive restarts), the paper trades booked, then outcomes: tags whose exit minute has now been seenteach the mushroom body's outcome pathway what the row made -- the book's realized return when it traded the row,else its label (``resolve_label``, exactly as ``train/decisions.build`` labels a row); a row the wallet bought toothen teaches the fill pathway what the real fills added (live realized − outcome) once its live position has closed49 unmodified linesFILL_IC_DAYS, FILL_IC_MIN = 7, 30 # the fill pathway's check: its predictions against the fills it learnedROLLBACK_PAUSE_S, ROLLBACK_LIMIT, ROLLBACK_WINDOW_S, ROLLBACK_MIN_AGE_S = 86400.0, 3, 7 * 86400.0, 86400.0SNAP_HOURLY_DAYS, SCORED_KEEP_DAYS = 7, 35COMMAND_KEY = "fly_command"COMMAND_MAX_AGE_S = 600.0 # an operator command older than this (queued while the engine was down) is dropped333 unmodified linesif r["x"] is None or r["outcome"] is None or r["ts"].timestamp() + self.holds[r["strategy"]] + FILL_WAIT_S <= now]if applied or expired:with conn.cursor() as cur:cur.executemany("UPDATE fly_scored SET state = 'resolved', resolved_at = now(), x = NULL WHERE ts = %s AND mint = %s AND strategy = %s", applied + expired)gone = set(expired)todo = [r for r in rows if r["ts"].timestamp() + self.holds[r["strategy"]] + LABEL_LAG_S > self.applied_through and r["x"] is not None]fills = [r for r in waiting if (r["ts"], r["mint"], r["strategy"]) not in gone]138 unmodified lines"drift": max(drift.values()) if drift else 0.0, "drift_by_strategy": drift, "pending": len(self.pending), "learned": learned,"learning_frozen": (self.brain or self).learning_frozen, "frozen_strategies": (self.brain or self).frozen, "channels": self.cfg,"holds_min": {k: v / 60.0 for k, v in self.holds.items()},"bootstrap": self.boot_id,"device": str(self.fly.net.dev), "timing": ph.get("timing")}if st is not None:out.update({k: v for k, v in st.items() if k != "entries"}); out["stage"] = "trading"12 unmodified linesself._write_state()if learned.get("keys"): # a row still waiting for its live fill keeps its features (tags survive restarts)with conn.cursor() as cur:cur.executemany("UPDATE fly_scored SET label = %s, state = %s, outcome = %s, resolved_at = now(), x = CASE WHEN %s = 'awaiting_fill' THEN x END ""WHERE ts = %s AND mint = %s AND strategy = %s", [(lb, st_, oc, st_, ts_, m, s_) for lb, st_, oc, ts_, m, s_ in learned.pop("keys")])if learned.get("fill_keys"):with conn.cursor() as cur:cur.executemany("UPDATE fly_scored SET fill = %s, state = 'resolved', resolved_at = now(), x = NULL WHERE ts = %s AND mint = %s AND strategy = %s",learned.pop("fill_keys"))learned.pop("keys", None); learned.pop("fill_keys", None)out["checks"] = self.last_checks; out["updated_at"] = datetime.now(timezone.utc).isoformat()out["race_started_at"] = self.race_started_at # the console's "racing for N days" (the race outlives a paper reset)553 unmodified linesPath(r["path"]).unlink(missing_ok=True)except OSError:passconn.execute("DELETE FROM fly_scored WHERE state <> 'pending' AND ts < %s", (datetime.fromtimestamp(now - SCORED_KEEP_DAYS * 86400.0, timezone.utc),))def _handover_check(self, conn, now: float) -> None:"""The fly takes the selector's seat once it has raced ``config.HANDOVER_DAYS`` (0: no minimum, the window is the16 unmodified lines17181920212223242549 unmodified lines75767778798081828384858687888990919293333 unmodified lines427428429430431432433138 unmodified lines57257357457557657757812 unmodified lines591592593594595596597598599600553 unmodified lines115411551156115711581159116016 unmodified linesseat; before that (LIVE_WITHOUT_HANDOVER) the selector's -- the fly's learned veto binds only its paper book, which iswhat its race measures;4. after the live orders (``after_minute``): the scored rows stored (``fly_scored``: pending rows keep the featurevector, so tags survive restarts; a row the selector would trade keeps it after it resolves too, with its outcome,for ``PICKS_KEEP_DAYS``: the examples a bad-coin veto learns and is judged on), the paper trades booked, then outcomes:tags whose exit minute has now been seenteach the mushroom body's outcome pathway what the row made -- the book's realized return when it traded the row,else its label (``resolve_label``, exactly as ``train/decisions.build`` labels a row); a row the wallet bought toothen teaches the fill pathway what the real fills added (live realized − outcome) once its live position has closed49 unmodified linesFILL_IC_DAYS, FILL_IC_MIN = 7, 30 # the fill pathway's check: its predictions against the fills it learnedROLLBACK_PAUSE_S, ROLLBACK_LIMIT, ROLLBACK_WINDOW_S, ROLLBACK_MIN_AGE_S = 86400.0, 3, 7 * 86400.0, 86400.0SNAP_HOURLY_DAYS, SCORED_KEEP_DAYS = 7, 35PICKS_KEEP_DAYS = 365 # a row the selector would trade (teacher_allow) keeps its features and outcome this long: a bad-coin veto trains on them# resolving a scored row: its features go, unless the selector would trade it (or it still waits for its live fill)RESOLVE_SQL = "UPDATE fly_scored SET state = 'resolved', resolved_at = now(), x = CASE WHEN teacher_allow THEN x END WHERE ts = %s AND mint = %s AND strategy = %s"LABEL_SQL = ("UPDATE fly_scored SET label = %s, state = %s, outcome = %s, resolved_at = now(), x = CASE WHEN %s = 'awaiting_fill' OR teacher_allow THEN x END ""WHERE ts = %s AND mint = %s AND strategy = %s")FILL_SQL = "UPDATE fly_scored SET fill = %s, state = 'resolved', resolved_at = now(), x = CASE WHEN teacher_allow THEN x END WHERE ts = %s AND mint = %s AND strategy = %s"def prune_scored(conn, now: float) -> None:"""Resolved scored rows older than ``SCORED_KEEP_DAYS`` go; the selector's would-be trades (teacher_allow) stay for``PICKS_KEEP_DAYS`` with their features and outcomes."""keep = datetime.fromtimestamp(now - SCORED_KEEP_DAYS * 86400.0, timezone.utc); picks = datetime.fromtimestamp(now - PICKS_KEEP_DAYS * 86400.0, timezone.utc)conn.execute("DELETE FROM fly_scored WHERE state <> 'pending' AND ts < %s AND (NOT COALESCE(teacher_allow, false) OR ts < %s)", (keep, picks))COMMAND_KEY = "fly_command"COMMAND_MAX_AGE_S = 600.0 # an operator command older than this (queued while the engine was down) is dropped333 unmodified linesif r["x"] is None or r["outcome"] is None or r["ts"].timestamp() + self.holds[r["strategy"]] + FILL_WAIT_S <= now]if applied or expired:with conn.cursor() as cur:cur.executemany(RESOLVE_SQL, applied + expired)gone = set(expired)todo = [r for r in rows if r["ts"].timestamp() + self.holds[r["strategy"]] + LABEL_LAG_S > self.applied_through and r["x"] is not None]fills = [r for r in waiting if (r["ts"], r["mint"], r["strategy"]) not in gone]138 unmodified lines"drift": max(drift.values()) if drift else 0.0, "drift_by_strategy": drift, "pending": len(self.pending), "learned": learned,"learning_frozen": (self.brain or self).learning_frozen, "frozen_strategies": (self.brain or self).frozen, "channels": self.cfg,"holds_min": {k: v / 60.0 for k, v in self.holds.items()},"bootstrap": self.boot_id, "gate": self.gate_sid, # the selector every buy of this book needs (``_follow_deployed``)"device": str(self.fly.net.dev), "timing": ph.get("timing")}if st is not None:out.update({k: v for k, v in st.items() if k != "entries"}); out["stage"] = "trading"12 unmodified linesself._write_state()if learned.get("keys"): # a row still waiting for its live fill keeps its features (tags survive restarts)with conn.cursor() as cur:cur.executemany(LABEL_SQL, [(lb, st_, oc, st_, ts_, m, s_) for lb, st_, oc, ts_, m, s_ in learned.pop("keys")])if learned.get("fill_keys"):with conn.cursor() as cur:cur.executemany(FILL_SQL, learned.pop("fill_keys"))learned.pop("keys", None); learned.pop("fill_keys", None)out["checks"] = self.last_checks; out["updated_at"] = datetime.now(timezone.utc).isoformat()out["race_started_at"] = self.race_started_at # the console's "racing for N days" (the race outlives a paper reset)553 unmodified linesPath(r["path"]).unlink(missing_ok=True)except OSError:passprune_scored(conn, now)def _handover_check(self, conn, now: float) -> None:"""The fly takes the selector's seat once it has raced ``config.HANDOVER_DAYS`` (0: no minimum, the window is the
3 unmodified lines4567891011121359 unmodified lines73747576777817 unmodified lines9697989910010110213 unmodified lines11611711811912012112212312419 unmodified lines1441451461471481491501511521531544 unmodified lines15916016116216316416520 unmodified lines18618718818919019119219319419519619719810 unmodified lines20921021121221321421521610 unmodified lines2272282292302312322333 unmodified linesprice (or the last traded price: the training label's exit), and earlier a position whose minute closed at itstake-profit line (``take_profit_x``: a buy of a coin trading far below its high since graduation is sold once it doubles,config.TAKE_PROFIT_X / TAKE_PROFIT_DIP; its token is not bought again before its hold would have ended), and a Solanaposition whose coin fell 25 % under its 5-minute high after its entry at that crash's price (agent/crash_exit.py);entries: scores at or above the book's line open a position sized from the book's certainty bands(``agent/sizing.py``), one position per token, unless blocked (global kill switch, paused entries, the book's owndrawdown halt, a minute traded more than ``ENTRY_MAX_LAG_S`` after its end, or the caller's ``block``); marks and wealthper minute (positions net of exit cost, exposure at cost, drawdown ≥ 0); the book's drawdown halt is checked on its ownpeak (``rails.check_book_drawdown``). Every score, entry, exit and blocked pick is a ``decisions`` row.59 unmodified linesreturn {r["mint"] for r in rows}def plan_minute(ctx, *, book: str, run_id: str, beat_no: int, broker, kind: str, mints: list, infos: list, scores, threshold,table: list | None, horizon_s: float, block: str | None = None, holds=None, strategies=None, allow=None, reasons=None,tables: list | None = None, flat: bool = False, live_allow=None, size_margins=None, correctness=None, marks: list | None = None) -> dict:17 unmodified linesstrategy's correctness sizes a row, its band is read at that margin instead of score − line; every decision, entry andrebuy carries both (``size_margin``, ``correctness``: the console's correctness %), so a live mirror sizes it the same.``marks`` (per row, a dict): carried the same way; its ``stake_x`` multiplies the row's stake (agent/rising_clean.py)."""conn, m1 = ctx.conn, ctx.m1beat = conn.execute("INSERT INTO beats (run_id, ts, beat_no, n_slots_active, notes) VALUES (%s,%s,%s,%s,%s) RETURNING id",(run_id, m1, beat_no, len(mints), json.dumps({"minute": m1.isoformat(), "mints_traded": len(ctx.agg), "book": book}))).fetchone()["id"]13 unmodified linesexits.append((p, held, kw, broker.quote_sell(position=p, **kw), "crash" if crash else "take_profit" if tp else None))leaving = {int(p["id"]) for p, *_ in exits}opens_now = [p for p in opens_before if int(p["id"]) not in leaving]; open_mints = {p["mint"] for p in opens_now}paid = {p["mint"]: float(p["cost_sol"]) for p in opens_now}; rebuy = {} # a token it keeps: what it paid, this minute's verdict on buying it againcash = ledger.paper_cash(conn, book) + sum(q for _, _, _, q, _ in exits); n_enter = 0; picks = []; entries = []; buys = []tp_held = None # tokens it took profit on, not bought again yet (read at the minute's first pick)bankroll = cash + sum(float(p["cost_sol"]) for p in opens_now) # wealth at cost: the sizing base (agent/sizing.py)from ..markets import for_bookmarket = for_book(book) # the book's market: its circuit, money settings and sizes19 unmodified linessize, why = sizing.size_position(float(sc), thr_k, tab_k or [], bankroll, cash, i["resq"], flat=flat, market=market, margin=mg,creator_heavy=bool(i.get("creator_heavy")), stake_x=cx.get("stake_x", 1.0))denied = allow is not None and not bool(allow[k])if tp_held is None: # this minute's own take-profits are not booked yettp_held = took_profit(conn, book, m1, horizon_s) | {p["mint"] for p, _, _, _, why in exits if why == "take_profit"}cooled = m in tp_held and m not in open_mintsif m in open_mints or cooled or blocked or denied or size <= 0:rail = blocked or ("held" if m in open_mints else "took profit" if cooled else (str(reasons[k]) if denied and reasons is not None else "filtered") if denied else "sizing")conn.execute("INSERT INTO decisions (beat_id, run_id, ts, mint, pool, kind, m_hat, size_sol, forced, rail, reason, detail) VALUES (%s,%s,%s,%s,%s,'blocked',%s,%s,false,%s,%s,%s)",(beat, run_id, m1, m, i["pool"], float(sc), size, rail, why if rail == "sizing" else f"{kind} pick not taken",json.dumps({"book": book, "score": float(sc), "threshold": thr_k, "sizing": why, **cx,4 unmodified linesrebuy[m] = {"score": float(sc), "threshold": thr_k, **cx,**({"table": tab_k, "ref_price": paid[m] / (q.token_delta / 10 ** int(i["decimals"]))} if q is not None and q.okelse {"why": blocked or (q.reason if q is not None else str(reasons[k]) if reasons is not None else "filtered")})}if denied and live_allow is not None and bool(live_allow[k]) and not blocked and m not in open_mints and not cooled and size > 0:hold_k = float(holds[k]) if holds is not None else None # the wallet's buy alone: this book stays as it istp_k = take_profit_x(ctx, market, m, i["price"])did = conn.execute("INSERT INTO decisions (beat_id, run_id, ts, mint, pool, kind, m_hat, size_sol, forced, reason, book_targets, detail) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,false,%s,%s,%s) RETURNING id",20 unmodified linesprogram_label=ctx.cost_label(m, i["program_label"]), pool_fee=ctx.fee(m))q = broker.quote_buy(**args)if q.ok:n_enter += 1; open_mints.add(m); cash -= size; buys.append((did, m, i, args, hold_k, strat_k))entries.append({"mint": m, "decision_id": did, "score": float(sc), "size_sol": size, "info": i, "threshold": thr_k, "table": tab_k, "hold_s": hold_k, "strategy": strat_k,"take_profit_x": tp_k, **cx, "ref_price": size / (q.token_delta / 10 ** int(i["decimals"]))})else:conn.execute("UPDATE decisions SET rail = %s, reason = %s WHERE id = %s", ("paper_fill", q.reason, did))return {"book": book, "run_id": run_id, "kind": kind, "broker": broker, "beat_id": beat, "exits": exits, "buys": buys, "entries": entries,"entered": n_enter, "picks": picks, "blocked": blocked, "market": market, "rebuy": rebuy}def book_minute(ctx, plan: dict) -> dict:10 unmodified lines(beat, plan["run_id"], m1, p["mint"], p["pool"], f"{plan['kind']}_exit", float(p["cost_sol"]), reason, json.dumps({"book": book}))).fetchone()["id"]broker.sell(conn, position=p, decision_id=did, forced_kind=why, ts=m1, **kw)n_exit += 1for did, m, i, args, hold_k, strat_k in plan["buys"]:fill = broker.buy(conn, decision_id=did, mint=m, pool=i["pool"], ts=m1, hold_s=hold_k, strategy=strat_k, **args)if not fill.ok: # its own quote planned it: only a changed broker could refuse it nowconn.execute("UPDATE decisions SET rail = %s, reason = %s WHERE id = %s", ("paper_fill", fill.reason, did))ledger.mark_positions(conn, book, ctx.prices, {}, m1)10 unmodified lines(beat, book, m1, cash, positions_net, exit_cost, wealth, peak, (1.0 - wealth / peak) if peak > 0 else 0.0, exposure, len(opens)))rails.check_book_drawdown(conn, book, wealth, peak, drawdown=market.kill_drawdown(), unit=market.unit) # the book's own kill switchpicks = plan["picks"]return {"beat_id": beat, "entries": plan["entries"], "entered": plan["entered"], "exited": n_exit, "open": len(opens), "cash": cash, "wealth": wealth,"picks": len(picks), "blocked": plan["blocked"], "top_scores": sorted(picks, key=lambda x: -x[1])[:5], "open_mints": sorted({p["mint"] for p in opens})}3 unmodified lines456789101112131415161759 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611717 unmodified lines13513613713813914014114214314414513 unmodified lines15916016116216316416516616716816919 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372384 unmodified lines24324424524624724824920 unmodified lines27027127227327427527627727827928028128210 unmodified lines29329429529629729829930030110 unmodified lines3123133143153163173183 unmodified linesprice (or the last traded price: the training label's exit), and earlier a position whose minute closed at itstake-profit line (``take_profit_x``: a buy of a coin trading far below its high since graduation is sold once it doubles,config.TAKE_PROFIT_X / TAKE_PROFIT_DIP; its token is not bought again before its hold would have ended), and a Solanaposition whose coin fell 25 % under its 5-minute high after its entry at that crash's price (agent/crash_exit.py; itstoken is not bought again for ``CRASH_REBUY_COOLDOWN_MIN``, rail 'crashed');entries: scores at or above the book's line open a position sized from the book's certainty bands(``agent/sizing.py``), one position per token, unless blocked (global kill switch, paused entries, the book's owndrawdown halt, a minute traded more than ``ENTRY_MAX_LAG_S`` after its end, or the caller's ``block``); a pick of a tokenthe book holds is an add (``REPICK_ADD_*``, kind '<kind>_add') once per position when it comes ``REPICK_ADD_MIN_S`` ormore after the entry at or below ``1 - REPICK_ADD_DIP`` of the entry price: bought into the same position, sized as thepick with the position's cost counted against the caps, and the position then held its hold from the add; marks and wealthper minute (positions net of exit cost, exposure at cost, drawdown ≥ 0); the book's drawdown halt is checked on its ownpeak (``rails.check_book_drawdown``). Every score, entry, exit and blocked pick is a ``decisions`` row.59 unmodified linesreturn {r["mint"] for r in rows}def cooling(conn, book: str, market, m1, horizon_s: float) -> tuple[set, set]:"""(tokens ``book`` took profit on whose hold has not ended -- ``took_profit`` --, tokens it sold in a crash exit within``CRASH_REBUY_COOLDOWN_MIN`` of ``m1``): neither is bought again yet. The wallet's rebuys within an hour of a crash salelost 25 of 29 times (2026-11-07..18). The fly's book, which the wallet mirrors, also counts the wallet's own crash sales;the race books only their own. One query, the one ``took_profit`` was: the minute's live entries wait on it."""cool = float(config.CRASH_REBUY_COOLDOWN_MIN) * 60.0books = [book] + ([market.live_book] if cool > 0 and book == market.fly_book else [])rows = conn.execute("""SELECT p.mint, p.forced_exit_kind AS k FROM positions p LEFT JOIN decisions d ON d.id = p.entry_decision_idWHERE p.book = ANY(%(books)s) AND p.status = 'closed' AND p.forced_exit_kind IN ('take_profit', 'crash') AND p.closed_at > %(m1)s - interval '1 day'AND ((p.forced_exit_kind = 'take_profit' AND p.book = %(book)sAND p.opened_at + make_interval(secs => COALESCE(p.hold_s, (d.detail->>'hold_s')::float, %(h)s)) > %(m1)s)OR (p.forced_exit_kind = 'crash' AND %(cool)s > 0 AND p.closed_at > %(m1)s - make_interval(secs => %(cool)s)))""",{"books": books, "book": book, "m1": m1, "h": horizon_s, "cool": cool}).fetchall()return {r["mint"] for r in rows if r["k"] == "take_profit"}, {r["mint"] for r in rows if r["k"] == "crash"}def added_to(conn, kind: str, position_ids: list) -> set:"""Open positions (of ``position_ids``) that already had their one re-pick add: an add decision of ``kind``('<kind>_add') whose paper fill went through (no rail)."""if not position_ids:return set()rows = conn.execute("""SELECT DISTINCT (detail->>'add_to')::bigint AS pid FROM decisions WHERE kind = %s AND rail IS NULLAND (detail->>'add_to')::bigint = ANY(%s)""", (kind, list(position_ids))).fetchall()return {int(r["pid"]) for r in rows}def add_due(market, p: dict | None, m1, price: float | None) -> bool:"""Whether a pick of open position ``p``'s token at ``price`` is a re-pick add (before the one-per-position check): addson on the chain, ``REPICK_ADD_MIN_S`` past its entry, at or below ``1 - REPICK_ADD_DIP`` of its entry price."""if p is None or config.REPICK_ADD_DIP <= 0 or market.chain not in config.REPICK_ADD_CHAINS or not price:return Falseentry = float(p.get("entry_price") or 0.0)return entry > 0 and (m1 - p["opened_at"]).total_seconds() >= config.REPICK_ADD_MIN_S and price <= entry * (1.0 - config.REPICK_ADD_DIP)def plan_minute(ctx, *, book: str, run_id: str, beat_no: int, broker, kind: str, mints: list, infos: list, scores, threshold,table: list | None, horizon_s: float, block: str | None = None, holds=None, strategies=None, allow=None, reasons=None,tables: list | None = None, flat: bool = False, live_allow=None, size_margins=None, correctness=None, marks: list | None = None) -> dict:17 unmodified linesstrategy's correctness sizes a row, its band is read at that margin instead of score − line; every decision, entry andrebuy carries both (``size_margin``, ``correctness``: the console's correctness %), so a live mirror sizes it the same.``marks`` (per row, a dict): carried the same way; its ``stake_x`` multiplies the row's stake (agent/rising_clean.py).A re-pick add (``add_due``, once per position) is an entry too, of kind '<kind>_add', carrying ``add_to`` (the paperposition), ``of_entry`` (its entry decision: a live mirror adds only to the position of that decision) and ``hold_s``(the position's new hold, from that entry decision's minute)."""conn, m1 = ctx.conn, ctx.m1beat = conn.execute("INSERT INTO beats (run_id, ts, beat_no, n_slots_active, notes) VALUES (%s,%s,%s,%s,%s) RETURNING id",(run_id, m1, beat_no, len(mints), json.dumps({"minute": m1.isoformat(), "mints_traded": len(ctx.agg), "book": book}))).fetchone()["id"]13 unmodified linesexits.append((p, held, kw, broker.quote_sell(position=p, **kw), "crash" if crash else "take_profit" if tp else None))leaving = {int(p["id"]) for p, *_ in exits}opens_now = [p for p in opens_before if int(p["id"]) not in leaving]; open_mints = {p["mint"] for p in opens_now}open_by_mint = {p["mint"]: p for p in opens_now}paid = {p["mint"]: float(p["cost_sol"]) for p in opens_now}; rebuy = {} # a token it keeps: what it paid, this minute's verdict on buying it againcash = ledger.paper_cash(conn, book) + sum(q for _, _, _, q, _ in exits); n_enter = n_add = 0; picks = []; entries = []; buys = []tp_held = crash_held = None # tokens it took profit on / sold in a crash, not bought again yet (read at the minute's first pick)added = None # positions that had their re-pick add (read at the minute's first add)bankroll = cash + sum(float(p["cost_sol"]) for p in opens_now) # wealth at cost: the sizing base (agent/sizing.py)from ..markets import for_bookmarket = for_book(book) # the book's market: its circuit, money settings and sizes19 unmodified linessize, why = sizing.size_position(float(sc), thr_k, tab_k or [], bankroll, cash, i["resq"], flat=flat, market=market, margin=mg,creator_heavy=bool(i.get("creator_heavy")), stake_x=cx.get("stake_x", 1.0))denied = allow is not None and not bool(allow[k])if tp_held is None: # this minute's own take-profits and crash sales are not booked yettp_held, crash_held = cooling(conn, book, market, m1, horizon_s)tp_held |= {p["mint"] for p, _, _, _, why in exits if why == "take_profit"}if config.CRASH_REBUY_COOLDOWN_MIN > 0:crash_held |= {p["mint"] for p, _, _, _, why in exits if why == "crash"}cooled = m in tp_held and m not in open_mintscrashed = not cooled and m in crash_held and m not in open_mintspk = open_by_mint.get(m)if not (blocked or denied) and add_due(market, pk, m1, i["price"]): # a re-pick of a held token under its entry: an add, onceif added is None:added = added_to(conn, f"{kind}_add", [int(p["id"]) for p in opens_now])if int(pk["id"]) not in added:size_a, why = sizing.size_position(float(sc), thr_k, tab_k or [], bankroll, cash, i["resq"], flat=flat, market=market, margin=mg,creator_heavy=bool(i.get("creator_heavy")), stake_x=cx.get("stake_x", 1.0), held_cost=float(pk["cost_sol"]))if size_a > 0:hk = float(holds[k]) if holds is not None and holds[k] is not None else float("nan")add_hold = hk if np.isfinite(hk) and hk > 0 else float(horizon_s)start = pk.get("decision_ts") or pk["opened_at"] # the position's hold counts from its entry decision (paper and live)new_hold = max(float(pk.get("hold_s") or horizon_s), (m1 - start).total_seconds() + add_hold)dip = float(i["price"]) / float(pk["entry_price"]) - 1.0did = conn.execute("INSERT INTO decisions (beat_id, run_id, ts, mint, pool, kind, m_hat, size_sol, forced, reason, book_targets, detail) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,false,%s,%s,%s) RETURNING id",(beat, run_id, m1, m, i["pool"], f"{kind}_add", float(sc), size_a,f"add on a re-pick {dip:+.0%} from its entry: {strat_k + ': ' if strat_k else ''}score {sc:.3f} ≥ {thr_k:.3f}; {why}", [book],json.dumps({"book": book, "add_to": int(pk["id"]), "of_entry": pk.get("entry_decision_id"), "dip": dip, "score": float(sc),"threshold": thr_k, "size_sol": size_a, "sizing": why, "resq": i["resq"], "age_h": i["age_h"], "price": i["price"],"strategy": strat_k, "hold_s": new_hold, "add_hold_s": add_hold, **cx}))).fetchone()["id"]args = dict(size_sol=size_a, price=i["price"], res_quote_sol=i["resq"], mcap_sol=i["mcap"], decimals=i["decimals"],program_label=ctx.cost_label(m, i["program_label"]), pool_fee=ctx.fee(m))q = broker.quote_buy(**args)if q.ok:n_add += 1; cash -= size_a; added.add(int(pk["id"])); buys.append((did, m, i, args, new_hold, strat_k, True))entries.append({"mint": m, "decision_id": did, "score": float(sc), "size_sol": size_a, "info": i, "threshold": thr_k, "table": tab_k,"hold_s": new_hold, "strategy": strat_k, "add_to": int(pk["id"]), "of_entry": pk.get("entry_decision_id"), **cx,"ref_price": size_a / (q.token_delta / 10 ** int(i["decimals"]))})else:conn.execute("UPDATE decisions SET rail = %s, reason = %s WHERE id = %s", ("paper_fill", q.reason, did))qr = broker.quote_buy(size_sol=paid[m], price=i["price"], res_quote_sol=i["resq"], mcap_sol=i["mcap"], decimals=i["decimals"],program_label=ctx.cost_label(m, i["program_label"]), pool_fee=ctx.fee(m))rebuy[m] = {"score": float(sc), "threshold": thr_k, **cx, # a live retry of its first buy still reads this minute's verdict**({"table": tab_k, "ref_price": paid[m] / (qr.token_delta / 10 ** int(i["decimals"]))} if qr.ok else {"why": qr.reason})}continueif m in open_mints or cooled or crashed or blocked or denied or size <= 0:rail = blocked or ("held" if m in open_mints else "took profit" if cooled else "crashed" if crashedelse (str(reasons[k]) if denied and reasons is not None else "filtered") if denied else "sizing")conn.execute("INSERT INTO decisions (beat_id, run_id, ts, mint, pool, kind, m_hat, size_sol, forced, rail, reason, detail) VALUES (%s,%s,%s,%s,%s,'blocked',%s,%s,false,%s,%s,%s)",(beat, run_id, m1, m, i["pool"], float(sc), size, rail, why if rail == "sizing" else f"{kind} pick not taken",json.dumps({"book": book, "score": float(sc), "threshold": thr_k, "sizing": why, **cx,4 unmodified linesrebuy[m] = {"score": float(sc), "threshold": thr_k, **cx,**({"table": tab_k, "ref_price": paid[m] / (q.token_delta / 10 ** int(i["decimals"]))} if q is not None and q.okelse {"why": blocked or (q.reason if q is not None else str(reasons[k]) if reasons is not None else "filtered")})}if denied and live_allow is not None and bool(live_allow[k]) and not blocked and m not in open_mints and not cooled and not crashed and size > 0:hold_k = float(holds[k]) if holds is not None else None # the wallet's buy alone: this book stays as it istp_k = take_profit_x(ctx, market, m, i["price"])did = conn.execute("INSERT INTO decisions (beat_id, run_id, ts, mint, pool, kind, m_hat, size_sol, forced, reason, book_targets, detail) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,false,%s,%s,%s) RETURNING id",20 unmodified linesprogram_label=ctx.cost_label(m, i["program_label"]), pool_fee=ctx.fee(m))q = broker.quote_buy(**args)if q.ok:n_enter += 1; open_mints.add(m); cash -= size; buys.append((did, m, i, args, hold_k, strat_k, False))entries.append({"mint": m, "decision_id": did, "score": float(sc), "size_sol": size, "info": i, "threshold": thr_k, "table": tab_k, "hold_s": hold_k, "strategy": strat_k,"take_profit_x": tp_k, **cx, "ref_price": size / (q.token_delta / 10 ** int(i["decimals"]))})else:conn.execute("UPDATE decisions SET rail = %s, reason = %s WHERE id = %s", ("paper_fill", q.reason, did))return {"book": book, "run_id": run_id, "kind": kind, "broker": broker, "beat_id": beat, "exits": exits, "buys": buys, "entries": entries,"entered": n_enter, "added": n_add, "picks": picks, "blocked": blocked, "market": market, "rebuy": rebuy}def book_minute(ctx, plan: dict) -> dict:10 unmodified lines(beat, plan["run_id"], m1, p["mint"], p["pool"], f"{plan['kind']}_exit", float(p["cost_sol"]), reason, json.dumps({"book": book}))).fetchone()["id"]broker.sell(conn, position=p, decision_id=did, forced_kind=why, ts=m1, **kw)n_exit += 1for did, m, i, args, hold_k, strat_k, add in plan["buys"]: # an add: into the open position, held ``hold_k`` from its entry decisionfill = broker.buy(conn, decision_id=did, mint=m, pool=i["pool"], ts=m1, hold_s=None if add else hold_k, strategy=strat_k,add_hold_s=hold_k if add else None, **args)if not fill.ok: # its own quote planned it: only a changed broker could refuse it nowconn.execute("UPDATE decisions SET rail = %s, reason = %s WHERE id = %s", ("paper_fill", fill.reason, did))ledger.mark_positions(conn, book, ctx.prices, {}, m1)10 unmodified lines(beat, book, m1, cash, positions_net, exit_cost, wealth, peak, (1.0 - wealth / peak) if peak > 0 else 0.0, exposure, len(opens)))rails.check_book_drawdown(conn, book, wealth, peak, drawdown=market.kill_drawdown(), unit=market.unit) # the book's own kill switchpicks = plan["picks"]return {"beat_id": beat, "entries": plan["entries"], "entered": plan["entered"], "added": plan.get("added", 0), "exited": n_exit, "open": len(opens), "cash": cash, "wealth": wealth,"picks": len(picks), "blocked": plan["blocked"], "top_scores": sorted(picks, key=lambda x: -x[1])[:5], "open_mints": sorted({p["mint"] for p in opens})}
3 unmodified lines456789101 unmodified line1213141516171845 unmodified lines6465666768697071727374757677786 unmodified lines85868788899091929394959697983 unmodified linesscore cleared the buy line (``build_table``: equal-count bands of ``score − threshold``). For each band the growth-optimal(Kelly) fraction is found on the band's actual net returns — the bet f that maximises the average of log(1 + f·r), so therare −100 % rugs count in full; a band with no edge gets 0. Live (``size_position``): the current score's band →``KELLY_FRACTION`` of that fraction of the deployable bankroll (wealth at cost minus the gas reserve); ``flat`` (thefly, ``config.FLY_SIZING``): ``MAX_POSITION_FRACTION`` of it on every buy that cleared the line, no bands. Either waycapped at ``MAX_POSITION_FRACTION`` of the deployable bankroll, the free cash above the reserve, and the label size(``market/exit_cost.label_size``: ``LABEL_SIZE_SOL`` or ``MAX_POOL_SHARE`` of the pool) -- the size every edge was1 unmodified lineit only runs out of cash later. A coin whose creator bought most of its supply at launch stakes at most``CREATOR_HEAVY_CAP_FRACTION`` of the bankroll, 0.1 SOL of 5 (they rug often; train/selector.py). Below ``MIN_POSITION_SOL`` the buy is skipped. A model without a table (trainedbefore sizing) trades the fixed ``MAX_POSITION_SOL``, under the same caps. ``stake_x`` multiplies the stake before the caps(agent/rising_clean.py: a rising market and a clean launch)."""from __future__ import annotations45 unmodified linesdef size_position(score: float, threshold: float, table: list[dict] | None, bankroll_sol: float, cash_sol: float,res_quote_sol: float | None, flat: bool = False, market=None, margin: float | None = None,creator_heavy: bool = False, stake_x: float = 1.0) -> tuple[float, str]:"""(size in the book's unit, why). Size 0 means skip the buy. ``flat``: ``MAX_POSITION_FRACTION`` of the deployablebankroll on every buy that cleared the line (the fly); otherwise the Kelly band of ``table``. ``market``(fly_trader/markets; default Solana): the gas reserve, minimum position and label size of the book's own market.``margin``: where the strategy's correctness sizes the row (train/strategies.decide's ``size_margin``), the margin itscorrectness bands are read at, P(clean) − the bands' p0, instead of score − threshold. ``creator_heavy``: the coin'screator bought most of its supply at launch (train/selector.creator_heavy) -- at most ``CREATOR_HEAVY_CAP_FRACTION`` ofthe bankroll. ``stake_x``: a multiple of the stake, under the same caps."""rh = market is not None and market.chain != "sol"; unit = market.unit if rh else "SOL"reserve = market.gas_reserve() if rh else config.GAS_RESERVE_SOL; free = cash_sol - reservemin_pos = market.min_position() if rh else config.MIN_POSITION_SOLdeployable = max(0.0, bankroll_sol - reserve)6 unmodified linesb = band_for(table, float(margin) if by_c else score - threshold)if b is None or b["kelly"] <= 0:return 0.0, "no edge in this correctness band" if by_c else "no edge in this score band"size = config.KELLY_FRACTION * b["kelly"] * deployablewhy = (f"correctness band from +{b['lo']:.3f}" if by_c else f"band from +{b['lo']:.3f} over the line") + f": Kelly {b['kelly']:.2f} × {config.KELLY_FRACTION:g} of {deployable:.2f} {unit}"if stake_x != 1.0:size *= stake_x; why += f" × {stake_x:g}"# the label size is the largest buy any backtest measured: past it the edge is an extrapolation that impact eatscaps = {"bankroll cap": config.MAX_POSITION_FRACTION * deployable, "free cash": free, "label size": label_size(res_quote_sol, market if rh else None)}if creator_heavy:caps["creator-heavy cap"] = config.CREATOR_HEAVY_CAP_FRACTION * bankroll_sol # a share, so in the book's unit (ETH on RH)limit = min(caps, key=caps.get)if caps[limit] < size:size = caps[limit]; why += f", capped by {limit}"3 unmodified lines456789101 unmodified line121314151617181945 unmodified lines65666768697071727374757677787980816 unmodified lines8889909192939495969798991001011023 unmodified linesscore cleared the buy line (``build_table``: equal-count bands of ``score − threshold``). For each band the growth-optimal(Kelly) fraction is found on the band's actual net returns — the bet f that maximises the average of log(1 + f·r), so therare −100 % rugs count in full; a band with no edge gets 0. Live (``size_position``): the current score's band →``KELLY_FRACTION`` (Robinhood Chain: ``RH_KELLY_FRACTION``) of that fraction of the deployable bankroll (wealth at cost minus the gas reserve); ``flat`` (thefly, ``config.FLY_SIZING``): ``MAX_POSITION_FRACTION`` of it on every buy that cleared the line, no bands. Either waycapped at ``MAX_POSITION_FRACTION`` of the deployable bankroll, the free cash above the reserve, and the label size(``market/exit_cost.label_size``: ``LABEL_SIZE_SOL`` or ``MAX_POOL_SHARE`` of the pool) -- the size every edge was1 unmodified lineit only runs out of cash later. A coin whose creator bought most of its supply at launch stakes at most``CREATOR_HEAVY_CAP_FRACTION`` of the bankroll, 0.1 SOL of 5 (they rug often; train/selector.py). Below ``MIN_POSITION_SOL`` the buy is skipped. A model without a table (trainedbefore sizing) trades the fixed ``MAX_POSITION_SOL``, under the same caps. ``stake_x`` multiplies the stake before the caps(agent/rising_clean.py: a rising market and a clean launch). ``held_cost``: a re-pick's add to a position that cost thatmuch (agent/paper_trading.plan_minute): the bankroll, label-size and creator-heavy caps hold for the whole position."""from __future__ import annotations45 unmodified linesdef size_position(score: float, threshold: float, table: list[dict] | None, bankroll_sol: float, cash_sol: float,res_quote_sol: float | None, flat: bool = False, market=None, margin: float | None = None,creator_heavy: bool = False, stake_x: float = 1.0, held_cost: float = 0.0) -> tuple[float, str]:"""(size in the book's unit, why). Size 0 means skip the buy. ``flat``: ``MAX_POSITION_FRACTION`` of the deployablebankroll on every buy that cleared the line (the fly); otherwise the Kelly band of ``table``. ``market``(fly_trader/markets; default Solana): the gas reserve, minimum position and label size of the book's own market.``margin``: where the strategy's correctness sizes the row (train/strategies.decide's ``size_margin``), the margin itscorrectness bands are read at, P(clean) − the bands' p0, instead of score − threshold. ``creator_heavy``: the coin'screator bought most of its supply at launch (train/selector.creator_heavy) -- at most ``CREATOR_HEAVY_CAP_FRACTION`` ofthe bankroll. ``stake_x``: a multiple of the stake, under the same caps. ``held_cost``: what the position this buy addsto already cost; the bankroll cap, the label size and the creator-heavy cap bound the position, so they shrink by it."""rh = market is not None and market.chain != "sol"; unit = market.unit if rh else "SOL"kf = config.RH_KELLY_FRACTION if rh else config.KELLY_FRACTIONreserve = market.gas_reserve() if rh else config.GAS_RESERVE_SOL; free = cash_sol - reservemin_pos = market.min_position() if rh else config.MIN_POSITION_SOLdeployable = max(0.0, bankroll_sol - reserve)6 unmodified linesb = band_for(table, float(margin) if by_c else score - threshold)if b is None or b["kelly"] <= 0:return 0.0, "no edge in this correctness band" if by_c else "no edge in this score band"size = kf * b["kelly"] * deployablewhy = (f"correctness band from +{b['lo']:.3f}" if by_c else f"band from +{b['lo']:.3f} over the line") + f": Kelly {b['kelly']:.2f} × {kf:g} of {deployable:.2f} {unit}"if stake_x != 1.0:size *= stake_x; why += f" × {stake_x:g}"# the label size is the largest buy any backtest measured: past it the edge is an extrapolation that impact eatscaps = {"bankroll cap": config.MAX_POSITION_FRACTION * deployable - held_cost, "free cash": free,"label size": label_size(res_quote_sol, market if rh else None) - held_cost}if creator_heavy:caps["creator-heavy cap"] = config.CREATOR_HEAVY_CAP_FRACTION * bankroll_sol - held_cost # a share, so in the book's unit (ETH on RH)limit = min(caps, key=caps.get)if caps[limit] < size:size = caps[limit]; why += f", capped by {limit}"
73 unmodified lines74757677787924 unmodified lines10410510610710810973 unmodified linesGAS_RESERVE_SOL = env_float("GAS_RESERVE_SOL", 0.30)# position sizing (agent/sizing.py): a fraction of the growth-optimal (Kelly) bet measured per score band in the backtestKELLY_FRACTION = env_float("KELLY_FRACTION", 0.25) # quarter Kelly: the band estimates are noisyMAX_POSITION_FRACTION = env_float("MAX_POSITION_FRACTION", 0.10) # of the deployable bankroll (wealth minus the gas reserve)MAX_POOL_SHARE = env_float("MAX_POOL_SHARE", 0.02) # of the pool's quote reserve (bounds price impact)CREATOR_HEAVY_CAP_FRACTION = env_float("CREATOR_HEAVY_CAP_FRACTION", 0.02) # of the bankroll, most a buy of a creator-heavy coin stakes, 0.1 SOL of 5 (train/selector.CREATOR_HEAVY_SHARE): they rug often24 unmodified linesTAKE_PROFIT_X = env_float("TAKE_PROFIT_X", 2.0) # 0: no take-profit on new buysTAKE_PROFIT_DIP = env_float("TAKE_PROFIT_DIP", 0.5)TAKE_PROFIT_CHAINS = env_list("TAKE_PROFIT_CHAINS", ["sol", "rh"])EXECUTABILITY_MAX_IMPACT = env_float("EXECUTABILITY_MAX_IMPACT", 0.30)SLIPPAGE_ENTRY_BPS = env_int("SLIPPAGE_ENTRY_BPS", 150)SLIPPAGE_EXIT_BPS = env_int("SLIPPAGE_EXIT_BPS", 300)73 unmodified lines7475767778798081828324 unmodified lines10810911011111211311411511611711811912012112212312412512673 unmodified linesGAS_RESERVE_SOL = env_float("GAS_RESERVE_SOL", 0.30)# position sizing (agent/sizing.py): a fraction of the growth-optimal (Kelly) bet measured per score band in the backtestKELLY_FRACTION = env_float("KELLY_FRACTION", 0.25) # quarter Kelly: the band estimates are noisy# Robinhood Chain's own fraction (agent/sizing.py; its paper books and the live_rh wallet), KELLY_FRACTION unless set. On# 2026-11-18 (data/scratch/bear_20261118) RH earned about 4x Solana's return on capital and its real fills cost ~2.7 %# a side almost regardless of size at today's 0.05-0.3 % pool shares: twice the stake added ~0.1-0.3 pts a trade.RH_KELLY_FRACTION = env_float("RH_KELLY_FRACTION", KELLY_FRACTION)MAX_POSITION_FRACTION = env_float("MAX_POSITION_FRACTION", 0.10) # of the deployable bankroll (wealth minus the gas reserve)MAX_POOL_SHARE = env_float("MAX_POOL_SHARE", 0.02) # of the pool's quote reserve (bounds price impact)CREATOR_HEAVY_CAP_FRACTION = env_float("CREATOR_HEAVY_CAP_FRACTION", 0.02) # of the bankroll, most a buy of a creator-heavy coin stakes, 0.1 SOL of 5 (train/selector.CREATOR_HEAVY_SHARE): they rug often24 unmodified linesTAKE_PROFIT_X = env_float("TAKE_PROFIT_X", 2.0) # 0: no take-profit on new buysTAKE_PROFIT_DIP = env_float("TAKE_PROFIT_DIP", 0.5)TAKE_PROFIT_CHAINS = env_list("TAKE_PROFIT_CHAINS", ["sol", "rh"])# Re-pick add (agent/paper_trading.plan_minute): a held position whose coin the book picks again at least REPICK_ADD_MIN_S# after its entry, at or below (1 - REPICK_ADD_DIP) x its entry price, is bought once more (one add per position, the# pick's own sizing, the position's total under the bankroll and label-size caps) and then held REPICK_ADD's hold from the# add -- paper and live alike, on the chains in REPICK_ADD_CHAINS. On the real logged re-picks of 10-17..11-18 and of the# archived 09-20..10-16 books (data/scratch/bear_20261118 s2_repick, v1_repick): +5..+10 %/trade on Solana in every book,# +10..+12 % on RH; a dip without the model's re-pick did less on Solana in 4 of 5 books.REPICK_ADD_DIP = env_float("REPICK_ADD_DIP", 0.10) # 0: no addsREPICK_ADD_MIN_S = env_float("REPICK_ADD_MIN_S", 300.0)REPICK_ADD_CHAINS = env_list("REPICK_ADD_CHAINS", ["sol", "rh"])# A coin a book sold in a crash exit (agent/crash_exit.py) is not bought again by it for this many minutes. Since the crash# exit went live (2026-11-07) the wallet's rebuys within 60 minutes of one lost -0.586 SOL on 29 buys, 4 winners, the same# in every Solana book (data/scratch/bear_20261118 v2_crash). 0: rebuys at once, as before.CRASH_REBUY_COOLDOWN_MIN = env_float("CRASH_REBUY_COOLDOWN_MIN", 60.0)EXECUTABILITY_MAX_IMPACT = env_float("EXECUTABILITY_MAX_IMPACT", 0.30)SLIPPAGE_ENTRY_BPS = env_int("SLIPPAGE_ENTRY_BPS", 150)SLIPPAGE_EXIT_BPS = env_int("SLIPPAGE_EXIT_BPS", 300)
59 unmodified lines6061626364656667681 unmodified line7071727374757659 unmodified linesdef buy(self, conn, *, decision_id: int | None, mint: str, pool: str | None, size_sol: float, price: float | None,res_quote_sol: float | None, mcap_sol: float | None, decimals: int, program_label: str | None, pool_fee: float | None = None,ts: datetime | None = None, hold_s: float | None = None, strategy: str | None = None) -> PaperFill:"""Fill at ``price`` pushed up by the constant-product impact, paying the real fees (market/exit_cost.py): the poolfee the stream reports (``pool_fee``) or the schedule's rate for ``mcap_sol``, Jupiter's platform fee, the network fee."""ts = ts or datetime.now(timezone.utc)q = self.quote_buy(size_sol=size_sol, price=price, res_quote_sol=res_quote_sol, mcap_sol=mcap_sol, decimals=decimals,program_label=program_label, pool_fee=pool_fee)1 unmodified linereturn qeff_price, qty_raw, fee_sol = q.price, q.token_delta, q.fee_solpid = ledger.open_position(conn, book=self.book, mint=mint, pool=pool, qty_raw=qty_raw, cost_sol=size_sol,entry_price=eff_price, decision_id=decision_id, fees_sol=fee_sol, ts=ts, hold_s=hold_s, strategy=strategy)fid = ledger.record_fill(conn, order_id=None, book=self.book, mint=mint, side="buy", token_delta=qty_raw,sol_delta_lamports=-int(size_sol * config.LAMPORTS_PER_SOL), price_sol=eff_price,fee_lamports=int(fee_sol * config.LAMPORTS_PER_SOL), verified_by="model", ts=ts)59 unmodified lines606162636465666768691 unmodified line717273747576777859 unmodified linesdef buy(self, conn, *, decision_id: int | None, mint: str, pool: str | None, size_sol: float, price: float | None,res_quote_sol: float | None, mcap_sol: float | None, decimals: int, program_label: str | None, pool_fee: float | None = None,ts: datetime | None = None, hold_s: float | None = None, strategy: str | None = None, add_hold_s: float | None = None) -> PaperFill:"""Fill at ``price`` pushed up by the constant-product impact, paying the real fees (market/exit_cost.py): the poolfee the stream reports (``pool_fee``) or the schedule's rate for ``mcap_sol``, Jupiter's platform fee, the network fee.``add_hold_s``: a re-pick's add into the open position of ``mint``, its new hold (execution/ledger.open_position)."""ts = ts or datetime.now(timezone.utc)q = self.quote_buy(size_sol=size_sol, price=price, res_quote_sol=res_quote_sol, mcap_sol=mcap_sol, decimals=decimals,program_label=program_label, pool_fee=pool_fee)1 unmodified linereturn qeff_price, qty_raw, fee_sol = q.price, q.token_delta, q.fee_solpid = ledger.open_position(conn, book=self.book, mint=mint, pool=pool, qty_raw=qty_raw, cost_sol=size_sol,entry_price=eff_price, decision_id=decision_id, fees_sol=fee_sol, ts=ts, hold_s=hold_s, strategy=strategy,add_hold_s=add_hold_s)fid = ledger.record_fill(conn, order_id=None, book=self.book, mint=mint, side="buy", token_delta=qty_raw,sol_delta_lamports=-int(size_sol * config.LAMPORTS_PER_SOL), price_sol=eff_price,fee_lamports=int(fee_sol * config.LAMPORTS_PER_SOL), verified_by="model", ts=ts)
68 unmodified lines6970717273747576772 unmodified lines808182838485868768 unmodified linesdef open_position(conn, *, book: str, mint: str, pool: str | None, qty_raw: int, cost_sol: float,entry_price: float, decision_id: int | None, fees_sol: float, ts: datetime | None = None,hold_s: float | None = None, strategy: str | None = None, deposit_sol: float = 0.0) -> int:"""``deposit_sol``: what the buy put into the mint's token account (its rent, a first live buy), kept apart from``cost_sol``: the account's close returns it (``refund_deposits``)."""ts = ts or datetime.now(timezone.utc)existing = conn.execute("SELECT id, qty, cost_sol, entry_price FROM positions WHERE book=%s AND mint=%s AND status='open'",(book, mint)).fetchone()2 unmodified linesq1, c1 = q0 + qty_raw, c0 + cost_solp1 = (float(existing["entry_price"] or entry_price) * q0 + entry_price * qty_raw) / max(q1, 1)conn.execute("UPDATE positions SET qty=%s, cost_sol=%s, entry_price=%s, fees_sol=fees_sol+%s, last_mark_price=%s, last_mark_ts=%s, ""deposit_sol = NULLIF(COALESCE(deposit_sol, 0) + %s, 0) WHERE id=%s",(q1, c1, p1, fees_sol, entry_price, ts, deposit_sol, existing["id"]))return int(existing["id"])row = conn.execute("""INSERT INTO positions (book, mint, pool, opened_at, entry_decision_id, qty, cost_sol, entry_price, peak_price,68 unmodified lines69707172737475767778792 unmodified lines828384858687888968 unmodified linesdef open_position(conn, *, book: str, mint: str, pool: str | None, qty_raw: int, cost_sol: float,entry_price: float, decision_id: int | None, fees_sol: float, ts: datetime | None = None,hold_s: float | None = None, strategy: str | None = None, deposit_sol: float = 0.0,add_hold_s: float | None = None) -> int:"""``deposit_sol``: what the buy put into the mint's token account (its rent, a first live buy), kept apart from``cost_sol``: the account's close returns it (``refund_deposits``). ``add_hold_s``: a re-pick's add to the openposition (agent/paper_trading.plan_minute): its new hold, counted from the position's entry decision as before."""ts = ts or datetime.now(timezone.utc)existing = conn.execute("SELECT id, qty, cost_sol, entry_price FROM positions WHERE book=%s AND mint=%s AND status='open'",(book, mint)).fetchone()2 unmodified linesq1, c1 = q0 + qty_raw, c0 + cost_solp1 = (float(existing["entry_price"] or entry_price) * q0 + entry_price * qty_raw) / max(q1, 1)conn.execute("UPDATE positions SET qty=%s, cost_sol=%s, entry_price=%s, fees_sol=fees_sol+%s, last_mark_price=%s, last_mark_ts=%s, ""deposit_sol = NULLIF(COALESCE(deposit_sol, 0) + %s, 0), hold_s = COALESCE(%s, hold_s) WHERE id=%s",(q1, c1, p1, fees_sol, entry_price, ts, deposit_sol, add_hold_s, existing["id"]))return int(existing["id"])row = conn.execute("""INSERT INTO positions (book, mint, pool, opened_at, entry_decision_id, qty, cost_sol, entry_price, peak_price,
48 unmodified lines495051525354156 unmodified lines21121221321421521621721812 unmodified lines23123223323423523623723848 unmodified linesstrategy: str | None = Noneref_price: float | None = None # buy: its decision's paper fill price (SOL per token): a quote above it by more than MAX_ENTRY_CHASE is refusedretry: int = 0 # a buy sent again after a failure (agent/fly_live.py): its failure was counted on the circuit the first timeenqueued_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))156 unmodified linesdef _execute(self, req: ExecRequest) -> ExecResult:try:with transaction() as conn:if req.side == "buy" and conn.execute("SELECT 1 FROM positions WHERE book = 'live' AND mint = %s AND status = 'open'", (req.mint,)).fetchone():return ExecResult(req, False, error="held: the live book still holds this token (the sale before this buy did not close it)", retryable=True)fr = self.broker.swap(conn, decision_id=req.decision_id, book="live", side=req.side, mint=req.mint,amount_in=req.amount_in, slippage_bps=req.slippage_bps,max_slippage_bps=req.max_slippage_bps, step_bps=config.SLIPPAGE_STEP_BPS,12 unmodified linesprice = fr.price_sol or (cost / max(fr.token_delta / (10 ** req.decimals), 1e-12))pid = ledger.open_position(conn, book="live", mint=req.mint, pool=req.pool, qty_raw=fr.token_delta,cost_sol=cost, entry_price=price, decision_id=req.decision_id,fees_sol=0.0, ts=ts, hold_s=req.hold_s, strategy=req.strategy,deposit_sol=max(fr.deposit_lamports, 0) / config.LAMPORTS_PER_SOL)rails.record_notional(conn, cost, "entry")return ExecResult(req, True, fr.fill_id, fr.signature, fr.token_delta, fr.lamports_delta, price, position_id=pid)else:48 unmodified lines49505152535455156 unmodified lines21221321421521621721821922022122212 unmodified lines23523623723823924024124224348 unmodified linesstrategy: str | None = Noneref_price: float | None = None # buy: its decision's paper fill price (SOL per token): a quote above it by more than MAX_ENTRY_CHASE is refusedretry: int = 0 # a buy sent again after a failure (agent/fly_live.py): its failure was counted on the circuit the first timeadd: bool = False # buy: a re-pick's add into the open position of its token, ``hold_s`` that position's new holdenqueued_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))156 unmodified linesdef _execute(self, req: ExecRequest) -> ExecResult:try:with transaction() as conn:held = req.side == "buy" and conn.execute("SELECT 1 FROM positions WHERE book = 'live' AND mint = %s AND status = 'open'", (req.mint,)).fetchone()if held and not req.add:return ExecResult(req, False, error="held: the live book still holds this token (the sale before this buy did not close it)", retryable=True)if req.add and not held: # sold since the add was decided: nothing to add toreturn ExecResult(req, False, error="held: the position this add was for is closed", retryable=False)fr = self.broker.swap(conn, decision_id=req.decision_id, book="live", side=req.side, mint=req.mint,amount_in=req.amount_in, slippage_bps=req.slippage_bps,max_slippage_bps=req.max_slippage_bps, step_bps=config.SLIPPAGE_STEP_BPS,12 unmodified linesprice = fr.price_sol or (cost / max(fr.token_delta / (10 ** req.decimals), 1e-12))pid = ledger.open_position(conn, book="live", mint=req.mint, pool=req.pool, qty_raw=fr.token_delta,cost_sol=cost, entry_price=price, decision_id=req.decision_id,fees_sol=0.0, ts=ts, hold_s=None if req.add else req.hold_s, strategy=req.strategy,deposit_sol=max(fr.deposit_lamports, 0) / config.LAMPORTS_PER_SOL,add_hold_s=req.hold_s if req.add else None)rails.record_notional(conn, cost, "entry")return ExecResult(req, True, fr.fill_id, fr.signature, fr.token_delta, fr.lamports_delta, price, position_id=pid)else:
73 unmodified lines747576777879808182838485862 unmodified lines899091929394959652 unmodified lines14915015115215315473 unmodified lines# ---- positionsdef book_buy(conn, *, intent_id: int, token: str, pool: str | None, quote_asset: str, eth_spent_wei: int, tokens_raw: int, decision_id: int | None,ts: datetime, hold_s: float | None, strategy: str | None, lot_basis_eth: float = 0.0, decimals: int = 18) -> tuple[int, float]:"""Book a finished buy intent. Returns (position id, realized) — realized is 0 for an opened position and −cost for anaborted one (no tokens)."""gas = intent_gas_wei(conn, intent_id)spent = eth_spent_wei / WEI + lot_basis_ethcost = spent + gas / WEIif tokens_raw <= 0: # nothing bought: the gas and any base loss are the losspid = ledger.open_position(conn, book=BOOK, mint=token, pool=pool, qty_raw=0, cost_sol=cost, entry_price=0.0, decision_id=decision_id,fees_sol=gas / WEI, ts=ts, hold_s=hold_s, strategy=strategy)2 unmodified linesreturn pid, float(realized or -cost)price = spent / (tokens_raw / 10 ** decimals)pid = ledger.open_position(conn, book=BOOK, mint=token, pool=pool, qty_raw=tokens_raw, cost_sol=cost, entry_price=price, decision_id=decision_id,fees_sol=gas / WEI, ts=ts, hold_s=hold_s, strategy=strategy)conn.execute("UPDATE positions SET quote_asset = %s, gas_q = %s WHERE id = %s", (quote_asset, gas / WEI, pid))conn.execute("UPDATE rh_intents SET position_id = %s WHERE id = %s", (pid, intent_id))conn.execute("UPDATE rh_legs SET position_id = %s WHERE intent_id = %s", (pid, intent_id))return pid, 0.052 unmodified linesconn.execute("UPDATE rh_intents SET position_id = %s WHERE id = %s", (dead, intent_id))return gasnow = datetime.now(timezone.utc)pid = ledger.open_position(conn, book=BOOK, mint=it["token"] or "gas", pool=None, qty_raw=0, cost_sol=gas, entry_price=0.0, decision_id=None,fees_sol=gas, ts=now)conn.execute("UPDATE positions SET gas_q = %s WHERE id = %s", (gas, pid))73 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051062 unmodified lines10911011111211311411511611711811952 unmodified lines17217317417517617717817918018173 unmodified lines# ---- positionsdef aborted_beside(conn, *, intent_id: int, token: str, pool: str | None, quote_asset: str | None, cost: float, gas: float, ts: datetime,decision_id: int | None, strategy: str | None) -> int:"""A re-pick add that bought nothing (``book_buy``, ``charge_gas``): an aborted position of its own, closed at once withits cost as the loss and linked to its intent. Written directly: ledger.open_position would merge it into the openposition of the same token, and closing it would close that one. Returns its id."""r = conn.execute("""INSERT INTO positions (book, mint, pool, opened_at, closed_at, entry_decision_id, qty, cost_sol, entry_price, exit_price, realized_sol,fees_sol, status, forced_exit_kind, strategy, chain, quote_asset, gas_q)VALUES (%s,%s,%s,%s,%s,%s,0,%s,0,0,%s,%s,'closed','aborted',%s,'rh',%s,%s) RETURNING id""",(BOOK, token, pool, ts, ts, decision_id, cost, -cost, gas, strategy, quote_asset, gas)).fetchone()conn.execute("UPDATE rh_intents SET position_id = %s WHERE id = %s", (int(r["id"]), intent_id))conn.execute("UPDATE rh_legs SET position_id = %s WHERE intent_id = %s", (int(r["id"]), intent_id))return int(r["id"])def book_buy(conn, *, intent_id: int, token: str, pool: str | None, quote_asset: str, eth_spent_wei: int, tokens_raw: int, decision_id: int | None,ts: datetime, hold_s: float | None, strategy: str | None, lot_basis_eth: float = 0.0, decimals: int = 18,add: bool = False) -> tuple[int, float]:"""Book a finished buy intent. Returns (position id, realized) — realized is 0 for an opened position and −cost for anaborted one (no tokens). ``add``: a re-pick's add into the open position of ``token`` (rh/live.py): its tokens and costjoin that position, ``hold_s`` becomes its hold and its gas adds to the position's; an add that bought nothing is anaborted position of its own, closed at once, the open one untouched."""gas = intent_gas_wei(conn, intent_id)spent = eth_spent_wei / WEI + lot_basis_ethcost = spent + gas / WEIif tokens_raw <= 0 and add: # an add that bought nothing: its own aborted row, never merged into the open positionreturn aborted_beside(conn, intent_id=intent_id, token=token, pool=pool, quote_asset=quote_asset, cost=cost, gas=gas / WEI, ts=ts,decision_id=decision_id, strategy=strategy), -costif tokens_raw <= 0: # nothing bought: the gas and any base loss are the losspid = ledger.open_position(conn, book=BOOK, mint=token, pool=pool, qty_raw=0, cost_sol=cost, entry_price=0.0, decision_id=decision_id,fees_sol=gas / WEI, ts=ts, hold_s=hold_s, strategy=strategy)2 unmodified linesreturn pid, float(realized or -cost)price = spent / (tokens_raw / 10 ** decimals)pid = ledger.open_position(conn, book=BOOK, mint=token, pool=pool, qty_raw=tokens_raw, cost_sol=cost, entry_price=price, decision_id=decision_id,fees_sol=gas / WEI, ts=ts, hold_s=None if add else hold_s, strategy=strategy, add_hold_s=hold_s if add else None)if add:conn.execute("UPDATE positions SET gas_q = COALESCE(gas_q, 0) + %s WHERE id = %s", (gas / WEI, pid))else:conn.execute("UPDATE positions SET quote_asset = %s, gas_q = %s WHERE id = %s", (quote_asset, gas / WEI, pid))conn.execute("UPDATE rh_intents SET position_id = %s WHERE id = %s", (pid, intent_id))conn.execute("UPDATE rh_legs SET position_id = %s WHERE intent_id = %s", (pid, intent_id))return pid, 0.052 unmodified linesconn.execute("UPDATE rh_intents SET position_id = %s WHERE id = %s", (dead, intent_id))return gasnow = datetime.now(timezone.utc)if it["token"] and conn.execute("SELECT 1 FROM positions WHERE book = %s AND mint = %s AND status = 'open'", (BOOK, it["token"])).fetchone():# a failed buy of a held token can only be a re-pick add (rh/exec.py refuses every other buy of one before its intent opens)aborted_beside(conn, intent_id=intent_id, token=it["token"], pool=None, quote_asset=None, cost=gas, gas=gas, ts=now, decision_id=it["decision_id"], strategy=None)return gaspid = ledger.open_position(conn, book=BOOK, mint=it["token"] or "gas", pool=None, qty_raw=0, cost_sol=gas, entry_price=0.0, decision_id=None,fees_sol=gas, ts=now)conn.execute("UPDATE positions SET gas_q = %s WHERE id = %s", (gas, pid))
87 unmodified lines888990919293138 unmodified lines232233234235236237238239191 unmodified lines43143243343443543643787 unmodified linesdecimals: int = 18ref_price: float | None = None # a buy: its decision's paper fill price (ETH per token), the most it may chase by MAX_ENTRY_CHASEretry: int = 0 # a buy sent again after a failure (rh/live.py): its n-th retry@dataclass138 unmodified linesif req.kind == "buy":with transaction() as conn:held = conn.execute("SELECT 1 FROM positions WHERE book = %s AND mint = %s AND status = 'open'", (A.BOOK, req.token.lower())).fetchone()if held: # the sale queued before it did not close the positionreturn RhResult(req, False, "held: the live book still holds this token (the sale before this buy did not close it)", retryable=True)iid = self._open_intent(req)if iid is None:return RhResult(req, False, DUPLICATE)191 unmodified linesA.open_lot(conn, asset=base, qty_raw=base_left, basis_eth=left_eth, source="stray", intent_id=iid)pid, realized = A.book_buy(conn, intent_id=iid, token=tok, pool=(req.pool or {}).get("pool_id"), quote_asset=(req.quote_asset or ZERO).lower(),eth_spent_wei=int(spent - left_eth * A.WEI), tokens_raw=max(tok_delta, 0), decision_id=req.decision_id, ts=now,hold_s=req.hold_s, strategy=req.strategy, decimals=req.decimals)else:sold = -tok_deltaA.add_leg(conn, intent_id=iid, tx_id=tx_id, position_id=req.position_id, leg_no=1, asset_in=tok, asset_out=A.NATIVE, amount_in=max(sold, 0),87 unmodified lines88899091929394138 unmodified lines233234235236237238239240241242191 unmodified lines43443543643743843944087 unmodified linesdecimals: int = 18ref_price: float | None = None # a buy: its decision's paper fill price (ETH per token), the most it may chase by MAX_ENTRY_CHASEretry: int = 0 # a buy sent again after a failure (rh/live.py): its n-th retryadd: bool = False # a buy: a re-pick's add into the open position of its token, ``hold_s`` that position's new hold@dataclass138 unmodified linesif req.kind == "buy":with transaction() as conn:held = conn.execute("SELECT 1 FROM positions WHERE book = %s AND mint = %s AND status = 'open'", (A.BOOK, req.token.lower())).fetchone()if held and not req.add: # the sale queued before it did not close the positionreturn RhResult(req, False, "held: the live book still holds this token (the sale before this buy did not close it)", retryable=True)if req.add and not held: # sold since the add was decided: nothing to add toreturn RhResult(req, False, "held: the position this add was for is closed", retryable=False)iid = self._open_intent(req)if iid is None:return RhResult(req, False, DUPLICATE)191 unmodified linesA.open_lot(conn, asset=base, qty_raw=base_left, basis_eth=left_eth, source="stray", intent_id=iid)pid, realized = A.book_buy(conn, intent_id=iid, token=tok, pool=(req.pool or {}).get("pool_id"), quote_asset=(req.quote_asset or ZERO).lower(),eth_spent_wei=int(spent - left_eth * A.WEI), tokens_raw=max(tok_delta, 0), decision_id=req.decision_id, ts=now,hold_s=req.hold_s, strategy=req.strategy, decimals=req.decimals, add=req.add)else:sold = -tok_deltaA.add_leg(conn, intent_id=iid, tx_id=tx_id, position_id=req.position_id, leg_no=1, asset_in=tok, asset_out=A.NATIVE, amount_in=max(sold, 0),
114 unmodified lines1151161171181191201211227 unmodified lines130131132133134135136100 unmodified lines23723823924024124224321 unmodified lines26526626726826927013 unmodified lines284285286287288289290100 unmodified lines391392393394395396397398114 unmodified linesif f is None or r.ok:returnrail = "price ran" if (r.error or "").startswith("price ran") else "entry failed"self._blocked(conn, ctx, run_id, beat_id, f["e"], rail, (r.error or "failed")[:300], r.request.amount_in / A.WEI, attempt=f["tries"], retry=bool(r.retryable))if r.retryable:self.failed[did] = {**f, "error": r.error}def _retry_over(self, conn, ctx, did: int, f: dict) -> str | None:7 unmodified linesdef _buy(self, e: dict, mint: str, quote: str, pool: dict | None, size: float, retry: int = 0) -> bool:return self.ex.submit(RhRequest(kind="buy", token=mint, quote_asset=quote, amount_in=int(size * A.WEI), slippage_bps=config.SLIPPAGE_ENTRY_BPS,max_slippage_bps=config.MAX_SLIPPAGE_ENTRY_BPS, pool=pool, decision_id=e["decision_id"], hold_s=e.get("hold_s"),strategy=e.get("strategy"), decimals=int(e["info"].get("decimals") or 18), ref_price=e.get("ref_price"), retry=retry))def _sell(self, conn, p: dict, did: int | None, slip: float, forced_kind: str | None = None) -> bool:pool = pool_of(conn, p.get("pool"))100 unmodified linesheld_mints = {p["mint"].lower() for p in opens if p["mint"].lower() not in selling} | (inflight - selling)c = rails.load_circuit(conn, RH_CIRCUIT)blocked = "kill switch" if c.kill_switch else "circuit tripped" if rails.breaker_blocks(c) else "paused" if c.entries_paused else Nonen_enter = n_retry = 0; skipped = []if self.failed or entries:native_eth = live_first.take_balance(self, ctx.m1_epoch) / A.WEI; self.wallet_eth = native_ethcommitted = self.ex.committed_wei() / A.WEI21 unmodified linesn_enter += 1; n_retry += 1; cash -= size; held_mints.add(mint)for e in entries:mint = e["mint"].lower()if mint in held_mints:skipped.append((mint, "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "the wallet holds this token or has an order of it queued"); continueif e["info"].get("source") == "v4" and not config.RH_V4_WALLET:13 unmodified lineselse:skipped.append((mint, "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "an order of this token is queued or in flight", size)self.due_mark = self.mark_ctx = (ctx, beat_id)return {"stage": "trading live", "wallet_eth": self.wallet_eth, "entered": n_enter, "retried": n_retry, "exited": ex["exited"], "liquidated": ex["liquidated"],"in_flight": len(inflight), "blocked": blocked, "skipped": skipped[:10], "failed_orders": sum(1 for r in drained if not r.ok),"awaiting_retry": len(self.failed)}100 unmodified linesWHERE l.book = %s AND l.status = 'closed' AND l.entry_decision_id IS NOT NULL AND COALESCE(l.forced_exit_kind, '') <> 'operator'AND NOT EXISTS (SELECT 1 FROM circuit_events e WHERE e.kind = 'rh_reconcile' AND e.ts >= l.opened_atAND e.ts <= COALESCE(l.closed_at, now()) AND e.detail::text ILIKE '%%' || lower(l.mint) || '%%')ORDER BY l.closed_at DESC LIMIT %s""",(MIRROR, BOOK, GAP_TRADES)).fetchall() # an operator's Sell Now is the operator's choice, not an execution gap;# nor a position the reconciler found gone from the wallet while it was held (ANT 2026-11-03, 0x493f2e7b 11-05: the coin's# contract took or wiped the tokens; the reconcile pause handles those, and two of them alone read as a 3.2-point gap)pairs = [(r["rl"], r["rp"]) for r in rows if r["rl"] is not None and r["rp"] is not None]114 unmodified lines1151161171181191201211221237 unmodified lines131132133134135136137138100 unmodified lines23924024124224324424521 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229313 unmodified lines307308309310311312313100 unmodified lines414415416417418419420421422423114 unmodified linesif f is None or r.ok:returnrail = "price ran" if (r.error or "").startswith("price ran") else "entry failed"add = f["e"].get("of_entry") is not None # a re-pick add is not tried againself._blocked(conn, ctx, run_id, beat_id, f["e"], rail, (r.error or "failed")[:300], r.request.amount_in / A.WEI, attempt=f["tries"], retry=bool(r.retryable) and not add)if r.retryable and not add:self.failed[did] = {**f, "error": r.error}def _retry_over(self, conn, ctx, did: int, f: dict) -> str | None:7 unmodified linesdef _buy(self, e: dict, mint: str, quote: str, pool: dict | None, size: float, retry: int = 0) -> bool:return self.ex.submit(RhRequest(kind="buy", token=mint, quote_asset=quote, amount_in=int(size * A.WEI), slippage_bps=config.SLIPPAGE_ENTRY_BPS,max_slippage_bps=config.MAX_SLIPPAGE_ENTRY_BPS, pool=pool, decision_id=e["decision_id"], hold_s=e.get("hold_s"),strategy=e.get("strategy"), decimals=int(e["info"].get("decimals") or 18), ref_price=e.get("ref_price"), retry=retry,add=e.get("of_entry") is not None))def _sell(self, conn, p: dict, did: int | None, slip: float, forced_kind: str | None = None) -> bool:pool = pool_of(conn, p.get("pool"))100 unmodified linesheld_mints = {p["mint"].lower() for p in opens if p["mint"].lower() not in selling} | (inflight - selling)c = rails.load_circuit(conn, RH_CIRCUIT)blocked = "kill switch" if c.kill_switch else "circuit tripped" if rails.breaker_blocks(c) else "paused" if c.entries_paused else Nonen_enter = n_retry = n_add = 0; skipped = []if self.failed or entries:native_eth = live_first.take_balance(self, ctx.m1_epoch) / A.WEI; self.wallet_eth = native_ethcommitted = self.ex.committed_wei() / A.WEI21 unmodified linesn_enter += 1; n_retry += 1; cash -= size; held_mints.add(mint)for e in entries:mint = e["mint"].lower()if e.get("of_entry") is not None: # a paper re-pick add: into the wallet's position of the same entry decisionp = next((q for q in opens if q["mint"].lower() == mint), None)pool = pool_of(conn, e["info"].get("pool")); quote = ((pool or {}).get("quote_asset") or ZERO).lower()rail = blocked or ("add: no such position" if p is None or p.get("entry_decision_id") != e["of_entry"] else None) \or ("held" if mint in inflight else None) \or ("v4 paper only" if e["info"].get("source") == "v4" and not config.RH_V4_WALLET else None) \or ("base mark stale" if A.base_mark(conn, quote)[1] else None)size, why = (0.0, "") if rail else sizing.size_position(e["score"], e.get("threshold", 0.0), e.get("table") or [], bankroll, cash, e["info"]["resq"],flat=config.FLY_SIZING == "flat", market=RH, margin=e.get("size_margin"),creator_heavy=bool(e["info"].get("creator_heavy")), held_cost=float(p["cost_sol"]))if rail or size <= 0:why = {"held": "an order of this token is queued or in flight", "add: no such position": "the wallet holds no position of this add's entry","v4 paper only": "a plain v4 coin: the wallet waits for the operator (RH_V4_WALLET)","base mark stale": f"no fresh ETH mark of its quote {quote}"}.get(rail, rail or why)skipped.append((mint, rail or why)); self._blocked(conn, ctx, run_id, beat_id, e, rail or "sizing", why, size, add=True); continueif self._buy(e, mint, quote, pool, size):n_add += 1; cash -= size; self.sent[e["decision_id"]] = {"e": e, "ts": m1, "tries": 1}conn.execute("UPDATE decisions SET book_targets = array_append(COALESCE(book_targets, '{}'), %s) WHERE id = %s", (BOOK, e["decision_id"]))else:skipped.append((mint, "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "an order of this token is queued or in flight", size, add=True)continueif mint in held_mints:skipped.append((mint, "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "the wallet holds this token or has an order of it queued"); continueif e["info"].get("source") == "v4" and not config.RH_V4_WALLET:13 unmodified lineselse:skipped.append((mint, "held")); self._blocked(conn, ctx, run_id, beat_id, e, "held", "an order of this token is queued or in flight", size)self.due_mark = self.mark_ctx = (ctx, beat_id)return {"stage": "trading live", "wallet_eth": self.wallet_eth, "entered": n_enter, "retried": n_retry, "added": n_add, "exited": ex["exited"], "liquidated": ex["liquidated"],"in_flight": len(inflight), "blocked": blocked, "skipped": skipped[:10], "failed_orders": sum(1 for r in drained if not r.ok),"awaiting_retry": len(self.failed)}100 unmodified linesWHERE l.book = %s AND l.status = 'closed' AND l.entry_decision_id IS NOT NULL AND COALESCE(l.forced_exit_kind, '') <> 'operator'AND NOT EXISTS (SELECT 1 FROM circuit_events e WHERE e.kind = 'rh_reconcile' AND e.ts >= l.opened_atAND e.ts <= COALESCE(l.closed_at, now()) AND e.detail::text ILIKE '%%' || lower(l.mint) || '%%')AND NOT EXISTS (SELECT 1 FROM decisions a WHERE a.kind = 'fly_rh_add' AND (a.detail->>'of_entry')::bigint = l.entry_decision_id)ORDER BY l.closed_at DESC LIMIT %s""",(MIRROR, BOOK, GAP_TRADES)).fetchall() # an operator's Sell Now is the operator's choice, not an execution gap;# nor a trade paper added to on a re-pick (its add may have been sized out or skipped on the wallet: no longer the same trade);# nor a position the reconciler found gone from the wallet while it was held (ANT 2026-11-03, 0x493f2e7b 11-05: the coin's# contract took or wiped the tokens; the reconcile pause handles those, and two of them alone read as a 3.2-point gap)pairs = [(r["rl"], r["rp"]) for r in rows if r["rl"] is not None and r["rp"] is not None]
1234567891011124 unmodified lines1718192021222324"""What this install has turned on: the menu and the chain picker read it."""from __future__ import annotationsimport osfrom ... import config, marketsfrom .. import runtimefrom ..hub import topicfrom ..state import KALSHI_BOOKS, kalshi_enabled, market_infodef _version() -> str:4 unmodified linesreturn "dev"@topic("meta", every=30)def meta(params: dict) -> dict:return {"pid": os.getpid(), "hosts_workers": runtime.HOSTS_WORKERS, "kalshi": kalshi_enabled(), "rh": bool(config.RH_ENABLED),"markets": [market_info(m) for m in markets.enabled()], "kalshi_books": KALSHI_BOOKS,"version": _version()}123456789101112131415161718194 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""What this install has turned on: the menu and the chain picker read it. And what it runs (``versions``, the stripalong the top of every page, Bryce 2026-11-07: so two installs can be told apart at a glance): the code, read once when the console starts (a later commit changes nothing already loaded), and each chain'sselector and fly as the engines report them, by their number in this install and by their file's sha256, which is thesame on every machine that runs the same model."""from __future__ import annotationsimport jsonimport osimport subprocessfrom pathlib import Pathfrom ... import config, marketsfrom ...db.queries import qfrom .. import runtimefrom ..hub import topicfrom ..state import KALSHI_BOOKS, kalshi_enabled, market_info, settingdef _version() -> str:4 unmodified linesreturn "dev"def _git(*args: str) -> str | None:try:r = subprocess.run(["git", "-C", str(config.REPO_ROOT), *args], capture_output=True, text=True, timeout=5)return r.stdout.strip() if r.returncode == 0 else Noneexcept Exception:return Nonedef code_version() -> dict:"""What code this console runs, in this order: ``FLY_CODE_VERSION`` (a deploy that stamps its own), a release's``release.json`` (Docker installs: its number and commit), the git commit the tree was at (``changed``: tracked filesdiffered from it), else the package version. {"label", "commit", "release", "changed", "source", "detail"}."""env = os.environ.get("FLY_CODE_VERSION", "").strip()if env:return {"label": env, "commit": None, "release": None, "changed": False, "source": "FLY_CODE_VERSION", "detail": env}rel = Path(config.REPO_ROOT) / "release.json"if rel.is_file():try:r = json.loads(rel.read_text())seq, commit = r.get("seq"), str(r.get("commit") or "")[:7] or Nonereturn {"label": f"release {seq}" + (f" · {commit}" if commit else ""), "commit": commit, "release": seq, "changed": False, "source": "release.json","detail": f"release {seq}, commit {r.get('commit')}, made {r.get('created_at')}"}except Exception:passcommit = _git("rev-parse", "--short=7", "HEAD")if commit:changed = bool(_git("status", "--porcelain", "--untracked-files=no"))subject = _git("log", "-1", "--format=%cd %s", "--date=format:%Y-%m-%d %H:%M") or ""return {"label": commit + (" +changes" if changed else ""), "commit": commit, "release": None, "changed": changed, "source": "git","detail": f"{commit}: {subject}" + (" (with uncommitted changes)" if changed else "")}v = _version()return {"label": v, "commit": None, "release": None, "changed": False, "source": "package", "detail": f"fly-trader {v}"}CODE = code_version()def _model(snapshot_id) -> dict | None:if not snapshot_id:return Noner = q("SELECT id, path, sha256 FROM brain_snapshots WHERE id = %s", (int(snapshot_id),))if not r:return {"id": int(snapshot_id), "sha": None, "file": None}return {"id": int(r[0]["id"]), "sha": (r[0]["sha256"] or "")[:8] or None, "file": Path(r[0]["path"]).name if r[0]["path"] else None}def model_versions() -> list[dict]:"""Each memecoin chain's selector and fly as its engines last reported them: the fly (fly_status*: ``bootstrap``) andthe selector that decides its buys, the fly's gate (``gate``; agent/fly_session._follow_deployed), else the selectorbook's (selector_status*: ``snapshot``). After a handover the selector book stops and its last report goes stale (apaper-only install, 2026-11-04), while the fly's gate keeps following the deployed selector."""out = []for m in markets.enabled():if m.chain not in ("sol", "rh"):continuesfx = "" if m.chain == "sol" else f"_{m.chain}"sel, _ = setting(f"selector_status{sfx}"); fly, _ = setting(f"fly_status{sfx}")out.append({"chain": m.chain, "selector": _model(fly.get("gate") or sel.get("snapshot")), "fly": _model(fly.get("bootstrap"))})return out@topic("meta", every=30)def meta(params: dict) -> dict:return {"pid": os.getpid(), "hosts_workers": runtime.HOSTS_WORKERS, "kalshi": kalshi_enabled(), "rh": bool(config.RH_ENABLED),"markets": [market_info(m) for m in markets.enabled()], "kalshi_books": KALSHI_BOOKS,"version": _version(), "versions": {"code": CODE, "models": model_versions()}}
85 unmodified lines868788899091929394959664 unmodified lines16116216316416516616716816917010 unmodified lines181182183184185186187255 unmodified lines4434444454464474484494504514524534544554564574584594604614622 unmodified lines46546646746846947047147247385 unmodified lines@topic("overview.summary", every=5)def summary(params: dict) -> dict:"""The narrative and the money's metrics — the live book while live money trades, else the selector's paper book:wealth, realized P&L, closed (wins), open, drawdown, with sparklines (wealth and drawdown over the book's wholehistory, realized P&L cumulative over the last 180 trades). A live book's capital and realized P&L are its wallet's(ops/wallets.money), so they hold what the trade ledger never sees."""mk = market_param(params); s = system_state(mk); live = bool(s["live_money"]); BOOK = mk.live_book if live else mk.selector_book; u = mk.unitmoney = wallets.money(mk) if live else Nonecap = money["start"] if money else mk.capital()w = q1("SELECT wealth, exposure, n_open, drawdown FROM wealth_marks WHERE book = %s ORDER BY ts DESC LIMIT 1", (BOOK,)) or {}64 unmodified lines@topic("overview.book", every=15)def book(params: dict) -> dict:"""The money's book — live while live money trades, else the selector's paper book: its whole wealth history andits open positions (held, exits in, cost, gross return). A live position can be sold now (``sell_now``) at the exit'sslippage stepping up to the forced one (``sell``, in percent)."""mk = market_param(params); live = bool(system_state(mk)["live_money"]); BOOK = mk.live_book if live else mk.selector_book; u = mk.unithist = _series(marks([BOOK]), [BOOK])rows = q("""SELECT p.id, p.mint, p.opened_at, p.cost_sol, p.entry_price, p.last_mark_price, p.hold_s, p.strategy,(d.detail->>'correctness')::float AS correctness10 unmodified lines"correctness": float(r["correctness"]) if r["correctness"] is not None else None,"ret": (float(r["last_mark_price"]) / float(r["entry_price"]) - 1) * 100 if r["entry_price"] and r["last_mark_price"] else None})return {"unit": u, "history": hist[0]["data"] if hist else [], "positions": out, "live": live, "book": BOOK,"title": "Live wealth" if live else "Paper wealth", "sub": "the bot wallet since it started trading" if live else "the selector book since it started","observer": isinstance(runtime.sup(), runtime.Observer), "sell": {"from_pct": config.SLIPPAGE_EXIT_BPS / 100, "to_pct": config.SLIPPAGE_FORCED_BPS / 100}}255 unmodified linesreturn out@topic("overview.setups", every=60)def setups(params: dict) -> dict:"""The selector's setups per UTC day over the last ``SETUP_DAYS`` days, per chain (Solana, then Robinhood Chain): thebuying chances its strategy stack found (``setups_by_day``), the trades its paper book took from them, and the livebook's. ``ran``: the share of the day's minutes the selector book ran (to the current minute today) -- a day it ranonly part of says nothing of the market."""now = datetime.now(timezone.utc); today = now.date()days = [today - timedelta(days=SETUP_DAYS - 1 - i) for i in range(SETUP_DAYS)]since = datetime(days[0].year, days[0].month, days[0].day, tzinfo=timezone.utc)enabled = markets.enabled(); sel = [m.selector_book for m in enabled]per = setups_by_day(selector_picks(sel, since - SETUP_GAP))ran = {(r["book"], r["d"]): int(r["minutes"]) for r in q("""SELECT r.config->>'book' AS book, (b.ts AT TIME ZONE 'UTC')::date AS d, count(DISTINCT b.ts) AS minutes FROM beats b JOIN runs r USING (run_id)WHERE b.ts >= %s AND r.config->>'book' = ANY(%s) GROUP BY 1, 2""", (since, sel))}live: dict[tuple[str, object], int] = {}for book, t, _ in _every_position([m.live_book for m in enabled], since)[0]:live[(book, t.date())] = live.get((book, t.date()), 0) + 12 unmodified linesrows = []for d in days:span = 1440 if d < today else max(1, now.hour * 60 + now.minute)share = min(1.0, ran.get((m.selector_book, d), 0) / span); c = per.get((m.selector_book, d)) or {"setups": 0, "trades": 0}rows.append({"day": d.isoformat(), "setups": c["setups"] if share > 0 else None, "trades": c["trades"] if share > 0 else None,"live": live.get((m.live_book, d), 0), "ran": round(share, 3)})out.append({"chain": m.chain, "name": m.name, "setups": sum(r["setups"] or 0 for r in rows), "trades": sum(r["trades"] or 0 for r in rows),"live": sum(r["live"] for r in rows), "days": rows})return {"tz": "UTC", "n_days": SETUP_DAYS, "gap_min": int(SETUP_GAP.total_seconds() // 60), "chains": out}85 unmodified lines86878889909192939495969764 unmodified lines16216316416516616716816917017110 unmodified lines182183184185186187188255 unmodified lines4444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834842 unmodified lines48748848949049149249349449549649785 unmodified lines@topic("overview.summary", every=5)def summary(params: dict) -> dict:"""The narrative and the money's metrics — the live book while live money trades, else the paper book in the seat(the selector's, the fly's after its handover):wealth, realized P&L, closed (wins), open, drawdown, with sparklines (wealth and drawdown over the book's wholehistory, realized P&L cumulative over the last 180 trades). A live book's capital and realized P&L are its wallet's(ops/wallets.money), so they hold what the trade ledger never sees."""mk = market_param(params); s = system_state(mk); live = bool(s["live_money"]); BOOK = s["money_book"]; u = mk.unitmoney = wallets.money(mk) if live else Nonecap = money["start"] if money else mk.capital()w = q1("SELECT wealth, exposure, n_open, drawdown FROM wealth_marks WHERE book = %s ORDER BY ts DESC LIMIT 1", (BOOK,)) or {}64 unmodified lines@topic("overview.book", every=15)def book(params: dict) -> dict:"""The money's book — live while live money trades, else the paper book in the seat: its whole wealth history andits open positions (held, exits in, cost, gross return). A live position can be sold now (``sell_now``) at the exit'sslippage stepping up to the forced one (``sell``, in percent)."""mk = market_param(params); s = system_state(mk); live = bool(s["live_money"]); BOOK = s["money_book"]; u = mk.unithist = _series(marks([BOOK]), [BOOK])rows = q("""SELECT p.id, p.mint, p.opened_at, p.cost_sol, p.entry_price, p.last_mark_price, p.hold_s, p.strategy,(d.detail->>'correctness')::float AS correctness10 unmodified lines"correctness": float(r["correctness"]) if r["correctness"] is not None else None,"ret": (float(r["last_mark_price"]) / float(r["entry_price"]) - 1) * 100 if r["entry_price"] and r["last_mark_price"] else None})return {"unit": u, "history": hist[0]["data"] if hist else [], "positions": out, "live": live, "book": BOOK,"title": "Live wealth" if live else "Paper wealth", "sub": "the bot wallet since it started trading" if live else ("the fly's paper book since it started" if BOOK == mk.fly_book else "the selector book since it started"),"observer": isinstance(runtime.sup(), runtime.Observer), "sell": {"from_pct": config.SLIPPAGE_EXIT_BPS / 100, "to_pct": config.SLIPPAGE_FORCED_BPS / 100}}255 unmodified linesreturn outdef _seat(m) -> datetime | None:"""When the chain's fly took the selector's seat (agent/handover.py), else None: the selector holds it."""from ...agent import handoverwith transaction() as conn:h = handover.state(conn, m.chain)at = _utc_of((h or {}).get("at"))return at@topic("overview.setups", every=60)def setups(params: dict) -> dict:"""The trading book's setups per UTC day over the last ``SETUP_DAYS`` days, per chain (Solana, then Robinhood Chain): thebuying chances its strategy stack found (``setups_by_day``), the trades its paper book took from them, and the livebook's. The trading book is the selector's until the chain's handover and the fly's from then on (``seat``), whichthe selector book stops for (a paper-only install, 2026-11-04: its chart showed no setups after it while the fly traded everyday). ``ran``: the share of the day's minutes that book ran (to the current minute today) -- a day it ran only partof says nothing of the market."""now = datetime.now(timezone.utc); today = now.date()days = [today - timedelta(days=SETUP_DAYS - 1 - i) for i in range(SETUP_DAYS)]since = datetime(days[0].year, days[0].month, days[0].day, tzinfo=timezone.utc)enabled = markets.enabled()seats = {m.chain: _seat(m) for m in enabled}ninf, pinf = datetime(1970, 1, 1, tzinfo=timezone.utc), datetime(9999, 1, 1, tzinfo=timezone.utc)spans = [(m.chain, m.selector_book, ninf, seats[m.chain] or pinf) for m in enabled] + \[(m.chain, m.fly_book, seats[m.chain], pinf) for m in enabled if seats[m.chain]] # (chain, book, from, to): the seat's bookpicks = selector_picks(sorted({b for _, b, _, _ in spans}), since - SETUP_GAP)per = setups_by_day([(c, mint, t, e) for book, mint, t, e in picks for c, b, lo, hi in spans if b == book and lo <= t < hi])ran: dict[tuple[str, object], int] = {}if spans:vals = ", ".join(["(%s, %s, %s::timestamptz, %s::timestamptz)"] * len(spans))for r in q(f"""WITH w(chain, book, lo, hi) AS (VALUES {vals})SELECT w.chain, (b.ts AT TIME ZONE 'UTC')::date AS d, count(DISTINCT b.ts) AS minutes FROM beats b JOIN runs r USING (run_id)JOIN w ON w.book = r.config->>'book' WHERE b.ts >= %s AND b.ts >= w.lo AND b.ts < w.hi GROUP BY 1, 2""",tuple(x for sp in spans for x in sp) + (since,)):ran[(r["chain"], r["d"])] = ran.get((r["chain"], r["d"]), 0) + int(r["minutes"])live: dict[tuple[str, object], int] = {}for book, t, _ in _every_position([m.live_book for m in enabled], since)[0]:live[(book, t.date())] = live.get((book, t.date()), 0) + 12 unmodified linesrows = []for d in days:span = 1440 if d < today else max(1, now.hour * 60 + now.minute)share = min(1.0, ran.get((m.chain, d), 0) / span); c = per.get((m.chain, d)) or {"setups": 0, "trades": 0}rows.append({"day": d.isoformat(), "setups": c["setups"] if share > 0 else None, "trades": c["trades"] if share > 0 else None,"live": live.get((m.live_book, d), 0), "ran": round(share, 3)})at = seats[m.chain]out.append({"chain": m.chain, "name": m.name, "setups": sum(r["setups"] or 0 for r in rows), "trades": sum(r["trades"] or 0 for r in rows),"live": sum(r["live"] for r in rows), "days": rows,"seat": {"book": "fly" if at else "selector", "since": at.isoformat() if at else None}})return {"tz": "UTC", "n_days": SETUP_DAYS, "gap_min": int(SETUP_GAP.total_seconds() // 60), "chains": out}
346 unmodified lines347348349350351352353346 unmodified lines("LIVE_WITHOUT_HANDOVER", "1" if config.LIVE_WITHOUT_HANDOVER else "0", "1: live money trades whoever holds the seat; 0: only once the fly has won it."),("Cluster", config.SOLANA_CLUSTER, "Solana network for live orders."),("Starting capital", f"{config.CAPITAL_SOL:g} SOL", "Paper books start here (`fly-trader reset-paper` restarts them from it when live funds arrive)."),("Position sizing", f"{config.KELLY_FRACTION:g} × Kelly", "Each buy is sized from how certain the model is: this share of the growth-optimal bet for its score band."),("Largest position", f"{config.MAX_POSITION_FRACTION:.0%} of the bankroll", "Bankroll = wealth at cost minus the gas reserve."),("Pool share cap", f"{config.MAX_POOL_SHARE:.0%} of the pool", "Bounds the price impact of larger buys."),("Smallest position", f"{config.MIN_POSITION_SOL:g} SOL", "Smaller sized buys are skipped."),346 unmodified lines347348349350351352353354346 unmodified lines("LIVE_WITHOUT_HANDOVER", "1" if config.LIVE_WITHOUT_HANDOVER else "0", "1: live money trades whoever holds the seat; 0: only once the fly has won it."),("Cluster", config.SOLANA_CLUSTER, "Solana network for live orders."),("Starting capital", f"{config.CAPITAL_SOL:g} SOL", "Paper books start here (`fly-trader reset-paper` restarts them from it when live funds arrive)."),("Position sizing", f"{config.KELLY_FRACTION:g} × Kelly" + (f" (Robinhood Chain {config.RH_KELLY_FRACTION:g} ×)" if config.RH_KELLY_FRACTION != config.KELLY_FRACTION else ""),"Each buy is sized from how certain the model is: this share of the growth-optimal bet for its score band."),("Largest position", f"{config.MAX_POSITION_FRACTION:.0%} of the bankroll", "Bankroll = wealth at cost minus the gas reserve."),("Pool share cap", f"{config.MAX_POOL_SHARE:.0%} of the pool", "Bounds the price impact of larger buys."),("Smallest position", f"{config.MIN_POSITION_SOL:g} SOL", "Smaller sized buys are skipped."),
10 unmodified lines111213141516171819202122232425262728293027 unmodified lines585960616263644 unmodified lines6970717273747510 unmodified linesfrom ..state import KALSHI_BOOKS, kalshi_enabled, labelsN = 60FLY_KINDS = ["fly_enter", "fly_exit", "fly_rh_enter", "fly_rh_exit", "blocked"]KALSHI_KINDS = ["kalshi_taker_enter", "kalshi_maker_post", "kalshi_maker_fill", "kalshi_settle", "kalshi_exit"]KALSHI_ACTION = {"kalshi_taker_enter": "bought", "kalshi_maker_post": "posted", "kalshi_maker_fill": "filled", "kalshi_maker_cancel": "cancelled","kalshi_settle": "settled", "kalshi_exit": "sold"}RAIL_TEXT = {"held": "already holding it", "filtered": "a filter said no", "paper_fill": "the simulated fill failed"}def action_of(kind: str) -> str:"""A decision kind as a verb: bought / sold / not taken, or the Kalshi arm's own (posted, filled, settled…)."""if kind in KALSHI_ACTION:return KALSHI_ACTION[kind]return "bought" if kind.endswith("_enter") or kind == "enter" else "sold" if kind.endswith("_exit") or kind == "exit" else "not taken" if kind == "blocked" else kinddef actor_of(kind: str, book: str | None) -> str:27 unmodified linesfor r in dec:m = markets.for_book(r["book"] or ""); live = (r["book"] or "").startswith("live"); act = action_of(r["kind"])size = float(r["size_sol"]) if r["size_sol"] is not None else Noneif act == "bought":detail = f"{_num(size, 4)} {m.unit}" + (f" — {r['reason']}" if r["reason"] else "")elif act == "sold":detail = f"cost {_num(size, 4)} {m.unit}" + (f" — {r['reason']}" if r["reason"] else "")4 unmodified linesdetail += f" (score {float(r['m_hat']):.3f})"who = "Live" if live else "Fly"out.append({"id": f"d:{r['id']}", "ts": r["ts"], "chain": m.chain, "book": r["book"], "kind": r["kind"], "action": act,"side": "buy" if act == "bought" else "sell" if act == "sold" else None, "mint": r["mint"], "ticker": None,"token": names.get(r["mint"], (r["mint"] or "")[:6]), "size": size, "unit": m.unit, "price": None, "live": live,"strategy": r["strategy"], "detail": detail.strip(),"text": f"{who} {act} {names.get(r['mint'], r['mint'])} on {m.name}: {detail.strip()}"})10 unmodified lines1112131415161718192021222324252627282930313227 unmodified lines606162636465664 unmodified lines7172737475767710 unmodified linesfrom ..state import KALSHI_BOOKS, kalshi_enabled, labelsN = 60FLY_KINDS = ["fly_enter", "fly_add", "fly_exit", "fly_rh_enter", "fly_rh_add", "fly_rh_exit", "blocked"]KALSHI_KINDS = ["kalshi_taker_enter", "kalshi_maker_post", "kalshi_maker_fill", "kalshi_settle", "kalshi_exit"]KALSHI_ACTION = {"kalshi_taker_enter": "bought", "kalshi_maker_post": "posted", "kalshi_maker_fill": "filled", "kalshi_maker_cancel": "cancelled","kalshi_settle": "settled", "kalshi_exit": "sold"}RAIL_TEXT = {"held": "already holding it", "filtered": "a filter said no", "paper_fill": "the simulated fill failed","crashed": "sold in a crash within the hour"}def action_of(kind: str) -> str:"""A decision kind as a verb: bought / sold / not taken, or the Kalshi arm's own (posted, filled, settled…)."""if kind in KALSHI_ACTION:return KALSHI_ACTION[kind]return ("bought" if kind.endswith("_enter") or kind == "enter" else "added" if kind.endswith("_add") else "sold" if kind.endswith("_exit") or kind == "exit"else "not taken" if kind == "blocked" else kind)def actor_of(kind: str, book: str | None) -> str:27 unmodified linesfor r in dec:m = markets.for_book(r["book"] or ""); live = (r["book"] or "").startswith("live"); act = action_of(r["kind"])size = float(r["size_sol"]) if r["size_sol"] is not None else Noneif act in ("bought", "added"):detail = f"{_num(size, 4)} {m.unit}" + (f" — {r['reason']}" if r["reason"] else "")elif act == "sold":detail = f"cost {_num(size, 4)} {m.unit}" + (f" — {r['reason']}" if r["reason"] else "")4 unmodified linesdetail += f" (score {float(r['m_hat']):.3f})"who = "Live" if live else "Fly"out.append({"id": f"d:{r['id']}", "ts": r["ts"], "chain": m.chain, "book": r["book"], "kind": r["kind"], "action": act,"side": "buy" if act in ("bought", "added") else "sell" if act == "sold" else None, "mint": r["mint"], "ticker": None,"token": names.get(r["mint"], (r["mint"] or "")[:6]), "size": size, "unit": m.unit, "price": None, "live": live,"strategy": r["strategy"], "detail": detail.strip(),"text": f"{who} {act} {names.get(r['mint'], r['mint'])} on {m.name}: {detail.strip()}"})
14 unmodified lines15161718192021222324254 unmodified lines303132333435363714 unmodified linesdef _book(params: dict, mk: markets.MarketSpec) -> str:"""The book asked for when it belongs to this chain, else the chain's selector book — the Streamlit page reset itsremembered book the same way when the chain changed under it."""b = params.get("book")if not isinstance(b, str) or not b or len(b) > 64 or markets.for_book(b) is not mk:return mk.selector_bookreturn b4 unmodified linesmk = market_param(params)seen = [r["book"] for r in q("SELECT DISTINCT book FROM positions UNION SELECT DISTINCT book FROM fills ORDER BY 1")]out = list(mk.books) + [b for b in seen if b not in mk.books and markets.for_book(b) is mk]live = bool(system_state(mk)["live_money"]) # while live money trades, the page opens on the live bookreturn {"chain": mk.chain, "unit": mk.unit, "books": out, "default": mk.live_book if live else mk.selector_book, "live": live,"help": f"{mk.selector_book} is the selector's paper book, {mk.fly_book} the fly's, {mk.live_book} the bot wallet; amounts in {mk.unit}."}14 unmodified lines1516171819202122232425264 unmodified lines313233343536373814 unmodified linesdef _book(params: dict, mk: markets.MarketSpec) -> str:"""The book asked for when it belongs to this chain, else the chain's money book (ui/state.system_state: the wallet'swhile live money trades, else the paper book in the seat) — the Streamlit page reset its remembered book the same waywhen the chain changed under it."""b = params.get("book")if not isinstance(b, str) or not b or len(b) > 64 or markets.for_book(b) is not mk:return system_state(mk)["money_book"]return b4 unmodified linesmk = market_param(params)seen = [r["book"] for r in q("SELECT DISTINCT book FROM positions UNION SELECT DISTINCT book FROM fills ORDER BY 1")]out = list(mk.books) + [b for b in seen if b not in mk.books and markets.for_book(b) is mk]s = system_state(mk); live = bool(s["live_money"]) # the page opens on the money's book: live, else the seat's paper bookreturn {"chain": mk.chain, "unit": mk.unit, "books": out, "default": s["money_book"], "live": live,"help": f"{mk.selector_book} is the selector's paper book, {mk.fly_book} the fly's, {mk.live_book} the bot wallet; amounts in {mk.unit}."}
CHANGELOG.md+84
console/src/components/Layout.tsx+30-1
console/src/context.tsx+8
console/src/pages/Overview.tsx+16-12
fly_trader/agent/crash_exit.py+3-1
fly_trader/agent/fly_live.py+34-8
fly_trader/agent/fly_session.py+21-8
fly_trader/agent/paper_trading.py+100-15
fly_trader/agent/sizing.py+12-8
fly_trader/config.py+17
fly_trader/execution/broker_paper.py+5-3
fly_trader/execution/ledger.py+6-4
fly_trader/execution/worker.py+8-3
fly_trader/rh/accounting.py+31-4
fly_trader/rh/exec.py+5-2
fly_trader/rh/live.py+30-5
fly_trader/ui/api/meta.py+71-3
fly_trader/ui/api/overview.py+39-15
fly_trader/ui/api/safety.py+2-1
fly_trader/ui/api/ticker.py+7-5
fly_trader/ui/api/trades.py+6-5
fly_trader/ui/static/console/assets/index-fghN0RdQ.jsDeleted