// Model & training (memecoins) as a Dashtreme dashboard: the model at work (KPI widgets, its backtest by half, win rate, // sizing bands, strategy stack), the automatic retraining pipeline (the selector every 7 days until the fly holds its seat; // the fly bootstrapped once), the day-by-day backtest, the plastic fly and its replay, every saved model and the trainer's // log (topics and actions in fly_trader/ui/api/model.py). Like the Streamlit page, it shows the Solana side. import type { ApexOptions } from 'apexcharts' import type { ReactNode } from 'react' import { useNow, useTopic, type TopicState } from '../lib/hooks' import { ago, dt, int, num, pct, pctPts } from '../lib/format' import { Callout, Caption, Card, Empty, Expander, Help, KVList, Loaded, Md, Metric, Metrics, Progress, RowGroup, Widget, WidgetGrid, type WidgetColor } from '../components/ui' import { DataTable, Pill, type Col } from '../components/DataTable' import { ApexChart, BarChart, RadialGauge } from '../components/Charts' import { ActionButton } from '../components/feedback' import { PageHead } from '../components/ChainPicker' type Wf = { n: number | null; days: number | null; mean: number | null; win: number | null; pf: number | null; days_positive: number | null; weeks: number | null; weeks_pos: number | null } type Band = { band: string; n: number | null; mean: number; win: number; bet: number } type Sizing = { caption: string; bands: Band[]; bankroll: string | null } type Component = { component: string | null; kept: boolean | null; why: string | null; win_sel: number | null; win_eval: number | null; pf_eval: number | null total_eval: number | null; n_eval: number | null; trials: number | null; best: string; params: string } type Strategy = { strategy: string; hold_min: number | null; line: number; trigger: string; n_eval: number | null; win_eval: number | null; pf_eval: number | null } type Stack = { fallback: boolean; components: Component[]; strategies: Strategy[] } type Half = { name: string; n: number | null; mean: number; random_mean: number | null; win: number | null; pf: number | null; weeks: number | null; weeks_pos: number | null; days: string[] | null } type AtWork = { id: number; current: boolean; ts?: string; since?: string; first_day?: string | null; trained_through?: string | null; threshold?: number horizon_min?: number | null; min_age_h?: number | null; wf?: Wf; random_mean?: number | null; backtest_line?: string; sizing?: Sizing; stack?: Stack | null; halves?: Half[] } type LoadedData = { model: AtWork | null; latest: { id: number; ts: string; deployable: boolean; deploy_reason: string | null } | null } type Retraining = { handover: boolean; interval_days: number; alive: boolean; running: boolean; stage: string | null; status: string; last_run_at: string | null; next_run: string latest: { id: number; deployable: boolean; backtest_line: string } | null; progress: { value: number; text: string } | null waiting: string | null; failed: string | null } type DayRow = { day: string | null; half: string | null; ic: number | null; n: number | null; model: number | null; random: number | null; winners: number | null; pf: number | null } type Results = { hidden: boolean; rows: DayRow[] } type PerStrategy = { strategy: string; ic: number | null; drift: number | null; mean_plastic: number | null; mean_frozen: number | null; n_plastic: number | null n_frozen: number | null; triggers: string | null; line: number | null; frozen_line: number | null } type FlyData = { running: boolean; frozen: boolean; runner_alive: boolean replay: { passed: boolean; reason: string | null; n: number | null; mean: number | null; random_mean: number | null; frozen_mean: number | null days_positive: number | null; days: number | null; alpha: string; half_life: string; caption: string } | null live: { line: number | null; frozen_line: number | null; drift: number | null; pending: number | null; ic: number | null; shadow_plastic: number | null shadow_frozen: number | null; device: string | null; drift_max: number; per_strategy: PerStrategy[] } | null detail: string | null updates: { hour: string; n: number | null; mean_abs_delta: number | null; drift: number | null; ic: number | null }[] rollbacks: { ts: string; reason: string | null; from_snapshot: number | null; to_snapshot: number | null }[] bootstrap: { id: number; ts: string; ok: boolean; text: string } | null } type Saved = { id: number; model: string; type: string; saved: string; data: string; trades: number | null; mean: number | null; random: number | null; pf: number | null deployed: boolean | null; in_use: boolean } const dash = (v: unknown) => (v === null || v === undefined ? '—' : String(v)) const yes = (v: boolean | null | undefined): ReactNode => v === null || v === undefined ? null : v ? : const signed = (v: number | null | undefined, text: string) => 0 ? 'text-pos' : 'text-neg'}>{text} const bySign = (v: number | null | undefined, pos: WidgetColor = 'success'): WidgetColor => (v == null ? 'dark' : v > 0 ? pos : v < 0 ? 'danger' : 'dark') /** A small static table (a few rows: no paging, search or export needed). */ function MiniTable({ rows, cols }: { rows: R[]; cols: { label: string; help?: string; num?: boolean; cell: (r: R) => ReactNode }[] }) { return (
{cols.map((c) => )}{rows.map((r, i) => {cols.map((c) => )})}
{c.label}
{c.cell(r) ?? '—'}
) } export default function Model() { const loaded = useTopic('model.loaded') const results = useTopic('model.results') return ( <>
) } // ---------------------------------------------------------------- Model at work function ModelAtWork({ s, days }: { s: TopicState; days?: Results }) { const now = useNow(10000) return ( {({ model: m, latest }) => { const next = m && latest && latest.id > m.id && (latest.deployable ? Model #{latest.id} qualified and replaces #{m.id} within 10 minutes, without a restart. : Model #{latest.id} ({ago(latest.ts, now)}) was not put to work: {latest.deploy_reason || 'it did not qualify'}.) if (!m || !m.current) { return ( {m ? Model #{m.id} is in use but was trained on outdated data (before the data fixes of 2026-09-14). Its backtest is not valid and is hidden. : !latest ? No model has been trained on the current data yet, so nothing is trading. The automatic retraining below runs as soon as the data is ready. : No model is at work. The latest, #{latest.id}, was not put to work: {latest.deploy_reason || 'it did not qualify'}.} {next} ) } const wf: Partial = m.wf ?? {} const byWeek = wf.days == null && wf.weeks != null // the strategy-stack selectors judge their evaluation half by week const posN = byWeek ? wf.weeks_pos : wf.days_positive, posD = byWeek ? wf.weeks : wf.days const daySpark = (days?.rows ?? []).map((r) => r.model).filter((v): v is number => v !== null) return ( <> 1 ? daySpark : null} help="Net return per trade on the test days, after fees and price impact. 'random' is the same number of random buys under the same rules." />
{next}
Share of test trades that made money. {posD ? : null}
{m.sizing && }
{m.stack && m.stack.strategies.length > 0 && }
{m.stack && } ) }}
) } function Halves({ halves }: { halves: Half[] }) { if (!halves.length) return No backtest halves recorded with this model. const series = [{ name: 'model % / trade', data: halves.map((h) => h.mean * 100) }] if (halves.some((h) => h.random_mean != null)) series.push({ name: 'random % / trade', data: halves.map((h) => (h.random_mean == null ? null : h.random_mean * 100)) as number[] }) return ( <> h.name)} series={series} height={250} yLabel="% per trade" yFormat={(v) => `${v.toFixed(1)}%`} /> h.name }, { label: 'trades', num: true, cell: (h) => int(h.n) }, { label: 'model / trade', num: true, cell: (h) => signed(h.mean, pct(h.mean)) }, { label: 'random / trade', num: true, cell: (h) => signed(h.random_mean, pct(h.random_mean)) }, { label: 'winners', num: true, cell: (h) => pct(h.win, 0, false) }, { label: 'profit factor', num: true, cell: (h) => num(h.pf, 2) }, { label: 'profitable weeks', num: true, cell: (h) => (h.weeks == null ? '—' : `${dash(h.weeks_pos)} of ${h.weeks}`) }, { label: 'days', cell: (h) => (h.days ? h.days.map((x) => x.slice(5)).join(' → ') : '—') }, ]} /> Selection chose the settings and the buy line; evaluation judged them on later weeks; the holdout's days were seen by no fit at all (overall and per chain). ) } function SizingCard({ sz }: { sz: Sizing }) { return ( {sz.caption} {sz.bands.length > 0 && ( <> b.band)} height={220} yFormat={(v) => `${v.toFixed(1)}%`} series={[{ name: 'bet (share of bankroll)', data: sz.bands.map((b) => b.bet) }, { name: 'average per trade', data: sz.bands.map((b) => b.mean) }]} /> b.band }, { label: 'test trades', num: true, cell: (b) => int(b.n) }, { label: 'average per trade', num: true, cell: (b) => signed(b.mean, pctPts(b.mean, 2)) }, { label: 'winning trades', num: true, cell: (b) => pctPts(b.win, 0, false) }, { label: 'bet (share of bankroll)', num: true, help: '0 % means that band has no edge: no buy.', cell: (b) => (b.bet === 0 ? 0.0% · no buy : pctPts(b.bet, 1, false)) }, ]} /> )} {sz.bankroll && {sz.bankroll}} ) } function StrategiesCard({ st }: { st: Stack }) { return ( {st.strategies.map((s) => ( ))} {st.strategies.map((s) => (
{s.strategy}
{s.trigger} }, ]} />
))}
) } function ComponentsCard({ st }: { st: Stack }) { const kept = st.components.filter((c) => c.kept).length const cols: Col[] = [ { key: 'component', label: 'component' }, { key: 'kept', label: 'kept', render: (r) => (r.kept == null ? null : {r.kept ? 'kept' : 'dropped'}) }, { key: 'why', label: 'why', wrap: true, render: (r) => {r.why} }, { key: 'win_sel', label: 'winning (selection)', num: true, render: (r) => pctPts(r.win_sel, 0, false) }, { key: 'win_eval', label: 'winning (evaluation)', num: true, render: (r) => pctPts(r.win_eval, 0, false) }, { key: 'pf_eval', label: 'profit factor (evaluation)', num: true, render: (r) => num(r.pf_eval, 2) }, { key: 'total_eval', label: 'total (evaluation)', num: true, render: (r) => signed(r.total_eval, num(r.total_eval, 2, true)), help: "Sum of the net returns of the evaluation half's trades (1.00 = one position's cost)." }, { key: 'n_eval', label: 'trades (evaluation)', num: true, render: (r) => int(r.n_eval) }, { key: 'trials', label: 'settings tried', num: true, render: (r) => int(r.trials) }, { key: 'best', label: 'best reached', wrap: true, help: 'The most profitable setting this component tried on the selection half, whether or not it cleared the bars.', render: (r) => {r.best} }, { key: 'params', label: 'parameters', wrap: true, render: (r) => {r.params} }, ] return ( {st.fallback && ( No setting reached 65 % winning trades on both halves: this model trades the most profitable system that passes profit factor 1.3 and the deploy rule instead. )} ) } // ---------------------------------------------------------------- Automatic retraining function statusColor(r: Retraining): WidgetColor { if (!r.alive) return 'dark' if (r.running) return 'info' if (r.stage === 'failed') return 'danger' if (r.stage === 'waiting for data') return 'warning' return 'success' } function Retrain() { const s = useTopic('model.retraining') const now = useNow(5000) const d = s.data const startNote = d && !d.alive ? ' The Trainer is not running, so this also starts it.' : '' return ( {d.running && ( )} )}> {(r) => ( <> {!r.alive && Automatic retraining is off because the Trainer is not running. Click Retrain now, or start the Trainer on the Processes page.} {r.progress && } {r.waiting && {r.waiting}} {r.failed && {r.failed}} )} ) } const STEPS = [ { icon: 'bx-analyse', text: 'The selector retrains on every day of history. Every day after the first 21 is backtested by a model that never saw it, against random picks, with real fees and price impact.' }, { icon: 'bx-up-arrow-circle', text: 'It goes to work only if that backtest made money and beat random picks; the trading engine switches to it without a restart.' }, { icon: 'bx-brain', text: "The fly is taught by the selector once — when none exists for the current definitions, or on request — and from then on learns from the market; weekly retraining stops when the fly takes the selector's seat." }, ] function HowRetraining() { return (
    {STEPS.map((st, i) => (
  1. {i + 1} ·{st.text}
  2. ))}
) } // ---------------------------------------------------------------- Latest selector backtest, day by day function DayByDay({ s }: { s: TopicState }) { const cols: Col[] = [ { key: 'day', label: 'day' }, { key: 'half', label: 'half', help: 'selection: the days that chose the buy line; evaluation: the days that judge it.', render: (r) => (r.half ? {r.half} : null) }, { key: 'ic', label: 'IC', num: true, render: (r) => num(r.ic, 3), help: 'Rank correlation of the predictions with the realised returns (0 = no skill).' }, { key: 'n', label: 'trades', num: true, render: (r) => int(r.n) }, { key: 'model', label: 'model % / trade', num: true, render: (r) => signed(r.model, num(r.model, 2, true)) }, { key: 'random', label: 'random % / trade', num: true, render: (r) => signed(r.random, num(r.random, 2, true)), help: 'Random picks, same count, costs and fills.' }, { key: 'winners', label: 'winners %', num: true, render: (r) => num(r.winners, 0) }, { key: 'pf', label: 'profit factor', num: true, render: (r) => num(r.pf, 2) }, ] return ( {(d) => { if (d.hidden) return The last backtest ran on outdated data and is hidden. if (!d.rows.length) return No selector backtest on the current data yet. const series = (['model', 'random'] as const).filter((k) => d.rows.some((r) => r[k] !== null)) .map((k) => ({ name: `${k} % / trade`, data: d.rows.map((r) => r[k]) })) return ( <> r.day ?? '')} series={series} height={260} yLabel="% per trade" /> Each day is traded by a model trained only on days at least two days earlier, with the paper broker's fees and price impact. The buy line is chosen on the selection half and judged on the evaluation half. ) }} ) } // ---------------------------------------------------------------- The plastic fly function FlyActions({ d }: { d: FlyData }) { return ( <> {d.frozen ? ( ) : ( )} ) } function PlasticFly() { const s = useTopic('model.fly') const now = useNow(10000) const d = s.data return ( <> }> {(f) => ( <> {f.live ? : (
{f.detail}
)} {f.bootstrap && (