/stock: watch tickers and get a chime when one reaches the low or high you set. Works any time, in any session.

Watch stock and crypto prices from inside Claude Code, and get a chime and a toast when one reaches a low or a high you set. Or set no limits at all and just keep an eye on the price. It's a mod: a plugin whose code runs inside Claude Code.
It shows your tickers on one small line under the prompt:

stock-watch AAPL 342.46 ▲ · NVDA 227.35 ▼ · BTC-USD 83,094 ▲ +2
+2: two more tickers are watched but not shown. The /stock pane shows all of them.HIGH / LOW: appears after a ticker once it has hit one of your limits, for example AAPL 351.20 ▲ HIGH.The pictures in this README are illustrations drawn to match what the mod prints. They are not screenshots of a live session, and the prices in them are examples.
/stock add AAPL just watch the price, no alerts
/stock add AAPL low 335 high 350 alert at 335 or below, and at 350 or above
/stock NVDA 120 140 shorthand: low then high
/stock add BTC-USD high 90000 one limit is fine
Each command answers with what it did:
> /stock add AAPL
Watching AAPL: price only, no alerts. Add a limit any time with /stock add AAPL low 180 high 200.
> /stock add AAPL low 335 high 350
Watching AAPL, alert at or below 335.00, alert at or above 350.00.
> /stock add BTC-USD high 90000
Watching BTC-USD, alert at or above 90,000.
When a price reaches a limit you get a toast that stays for 30 seconds, and a chime. A rising chime means your high was reached, a falling chime means your low was reached.

📈 AAPL reached your high: 350.40 USD (limit 350.00)
📉 NVDA fell to your low: 118.90 USD (limit 120.00)
Say the limits with words or with two prices:
| You type | Meaning |
|---|---|
/stock add AAPL low 335 high 350 | Alert at or below 335, and at or above 350. |
/stock add AAPL high 350 | Only the high. |
/stock add AAPL below 335 | below and under mean low. |
/stock add AAPL above 350 | above and over mean high. |
/stock AAPL 350 335 | Two prices: the smaller is the low, the larger is the high. |
/stock AAPL 350 | One bare price is ambiguous, so it asks you to say low or high. |
The low must be below the high. Run the same command again to change a limit. It keeps the ticker and replaces only what you give it.
The chime is the sound. The toast always shows, so you never miss an alert.
> /stock chime off
Stock watch: chime off for every ticker. Toasts still show.
> /stock chime on
Stock watch: chime on.
> /stock AAPL chime off
Stock watch: AAPL chime off. Its toast still shows.
> /stock AAPL chime on
Stock watch: AAPL chime on.
/stock chime off and /stock chime on set it for every ticker. mute and unmute do the same thing./stock AAPL chime off and /stock AAPL chime on set it for one ticker. A ticker with its chime off shows chime off on its row in the pane./stock off stops everything: no price checks, no alerts, and the price line under the prompt is cleared. The pane stays open and shows a notice. Your tickers are kept. A ticker you add while it's off is saved but not checked until you run /stock on. /stock chime off only silences the sound, so use /stock off to stop the mod itself.
> /stock rm AAPL
Stopped watching AAPL.
/stock rm AAPL, or the Remove button on its row in the pane./stock rm AAPL and also delete its entry from the Watch list./stock opens a pane with a box to add tickers, and one pill per ticker. Each pill has a border that is green when the price is above today's open and red when it is below. The colours don't show in text, but this is the layout:

Add [ AAPL or AAPL 180 200 or NVDA high 140 ]
[Check now] [Test sound] [Mute]
╭──────────────────────────────────────────────────────────╮
│ ╭──────────────────────────────────────────────────────╮ │
│ │ AAPL 342.46 ▲0.63% [Remove] │ │ green border
│ │ low 335.00 [·······●········] high 350.00 │ │
│ ╰──────────────────────────────────────────────────────╯ │
│ ╭──────────────────────────────────────────────────────╮ │
│ │ NVDA 118.90 ▼2.10% chime off LOW HIT [Remove] │ │ red border
│ │ low 120.00 [●···············] high 140.00 │ │
│ ╰──────────────────────────────────────────────────────╯ │
│ ╭──────────────────────────────────────────────────────╮ │
│ │ BTC-USD 83,094.31 ▲1.40% [Remove] │ │ green border, no limits
│ ╰──────────────────────────────────────────────────────╯ │
╰──────────────────────────────────────────────────────────╯
Checked every 60s while a session is open. Prices come from Yahoo Finance and can lag.
! marks a price at a limit. A ticker with no limits has no bar.LOW HIT and HIGH HIT show after a limit alerts.| Command | Does |
|---|---|
/stock | Opens the pane. |
/stock add AAPL | Watches the price only. No limits, so no alerts and no chime. |
/stock add AAPL low 180 high 200 | Watches a ticker with limits. Either limit alone is fine. |
/stock AAPL 180 200 | Shorthand: the two prices become the low and the high, in either order. |
/stock rm AAPL | Stops watching it and removes its pill. |
/stock on / /stock off | Starts or stops the whole mod. Off stops price checks, alerts and the price line under the prompt. Your watch list is kept. Remembered across sessions. |
/stock chime off / on | Silences or restores the chime for every ticker. Toasts always show. |
/stock AAPL chime off / on | Silences or restores the chime for one ticker. Its toast still shows. |
/stock list / check | Prints the list, or fetches prices now. |
/stock test | Plays both chimes, high then low. |
A bare /stock AAPL does nothing but explain itself. Use /stock add AAPL, so a mistyped command is never mistaken for a ticker.
Tickers use Yahoo Finance symbols: AAPL, BRK-B, BTC-USD, ^GSPC, EURUSD=X, 7203.T. Up to 20 at a time.
/plugin marketplace add troyjlorents-gh/mod-squad
/plugin install stock-watch@mod-squad
Start a new session after installing, because mods load when a session starts.
Open the plugin's settings to change these. Tickers themselves go in the Watch list, or are added with /stock.
| Setting | Default | Meaning |
|---|---|---|
watchlist | blank | Tickers to watch, separated by semicolons: AAPL 180 200; NVDA high 140; MSFT (a ticker alone is price only). Applied when a session starts and whenever the text changes. /stock changes made later are not undone. |
pollSeconds | 60 | How often prices are fetched, never under 30. |
sound | chime | chime, chime and voice (also says the ticker aloud, macOS), or off. |
statusLine | show | show puts the tickers under the prompt. hide leaves that line empty. The pane and the alerts still work. |
statusCount | 3 | How many tickers the status line shows, 1 to 5. The rest show as +N. |
Every hook passes the event on. None of them changes a prompt, a tool call or an answer.
| Hook | What it does |
|---|---|
session.start | Registers /stock, loads your saved tickers, applies the Watch list setting, and starts the price checks (unless you turned the mod off). |
prompt.submit | Starts the price checks if the session missed its start signal. Your prompt is sent unchanged. |
command.run | Handles /stock. |
ui.render | Draws the stock pane. |
/stock test to hear what your setup does.hooks/register.tsx 351 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Watch } from '../types'
5import { CHIME_USAGE, POWER_USAGE, USAGE, alertText, evaluate, fmtChange, fmtPrice, parseCommand, parseQuote, quoteUrl, rangeBar, statusText } from './watch'
6import type { Side } from './watch'
7
8const PANE = 'stock-watch'
9const MAX_WATCHES = 20
10const MIN_POLL_S = 30
11
12const watchesRef = atom({ plugin: 'stock-watch', key: 'watches' } as const, [] as Watch[])
13const mutedRef = atom({ plugin: 'stock-watch', key: 'muted' } as const, false)
14const pollRef = atom({ plugin: 'stock-watch', key: 'poll' } as const, { isRunning: false, at: 0 })
15// Off stops price checks, alerts and the status line. The watch list is kept, and /stock on turns it back on.
16const enabledRef = atom({ plugin: 'stock-watch', key: 'enabled' } as const, true)
17
18type Options = { pollSeconds?: number; sound?: string; watchlist?: string; statusLine?: string; statusCount?: number }
19type Cfg = { pollMs: number; sound: 'chime' | 'voice' | 'off'; watchlist: string; statusLine: boolean; statusCount: number; isPolling: boolean; isBusy: boolean }
20
21function config(options: unknown): Cfg {
22 const o = (options ?? {}) as Options
23 const s = Number(o.pollSeconds)
24 return {
25 pollMs: Math.max(MIN_POLL_S, Number.isFinite(s) && s > 0 ? s : 60) * 1000,
26 sound: o.sound === 'off' ? 'off' : o.sound === 'chime and voice' ? 'voice' : 'chime',
27 watchlist: (o.watchlist ?? '').trim(),
28 statusLine: o.statusLine !== 'hide',
29 statusCount: Math.min(5, Math.max(1, Math.round(Number(o.statusCount)) || 3)),
30 isPolling: false,
31 isBusy: false,
32 }
33}
34
35/* ----------------------------------------------------------------------- state */
36
37// The store is shared by every session on this machine, so each change reads it fresh and writes it back.
38async function stored($: EngineInterface): Promise<Watch[]> {
39 const v = await $.store.get('watches').catch(() => undefined)
40 return Array.isArray(v) ? (v as Watch[]) : []
41}
42
43// The status line settings, read by save() and load(), which are called from places that do not carry the config.
44let statusView = { show: true, count: 3 }
45
46/** Shows the price line under the prompt, or clears it when the mod is off or the line is hidden. */
47async function showLine($: EngineInterface, ws: Watch[]) {
48 const on = statusView.show && (await read($, enabledRef))
49 $.ui.status(on ? statusText(ws, statusView.count) : undefined)
50}
51
52async function save($: EngineInterface, ws: Watch[]) {
53 await $.store.set('watches', ws).catch(() => undefined)
54 await update($, watchesRef, () => ws)
55 await showLine($, ws)
56}
57
58/** Loads the store into the pane's state (a session that just started, or another session's change). */
59async function load($: EngineInterface) {
60 const ws = await stored($)
61 await update($, watchesRef, () => ws)
62 await update($, mutedRef, () => false)
63 if ((await $.store.get('muted').catch(() => undefined)) === true) await update($, mutedRef, () => true)
64 await showLine($, ws)
65}
66
67/* ----------------------------------------------------------------------- sound */
68
69/** Plays a clip. macOS plays through the engine; Windows has no engine player, so PowerShell plays it. */
70async function chime($: EngineInterface, side: Side) {
71 const asset = side === 'high' ? 'sounds/high.wav' : 'sounds/low.wav'
72 const isWindows = (await $.env.get('OS').catch(() => undefined)) === 'Windows_NT'
73 if (isWindows) {
74 try {
75 const path = `${$.plugin.root}/${asset}`.replace(/\//g, '\\').replace(/'/g, "''")
76 const r = await $.process.run(['powershell', '-NoProfile', '-NonInteractive', '-Command', `(New-Object Media.SoundPlayer '${path}').PlaySync()`], { timeoutMs: 15_000 })
77 if (r.exitCode === 0) return
78 } catch {
79 // No process (the desktop app): fall through to the engine's player.
80 }
81 }
82 try {
83 await $.audio.play({ asset })
84 } catch {
85 // No player here: the toast still shows.
86 }
87}
88
89async function announce($: EngineInterface, cfg: Cfg, w: Watch, side: Side, price: number) {
90 $.ui.toast(alertText(w, side, price), { timeoutMs: 30_000 })
91 if (cfg.sound === 'off' || w.quiet === true || (await read($, mutedRef))) return
92 await chime($, side)
93 if (cfg.sound === 'voice') await $.audio.speak(`${w.sym.replace(/[^A-Z0-9]/g, ' ')} ${side === 'high' ? 'reached your high' : 'fell to your low'}`).catch(() => undefined)
94}
95
96/* ------------------------------------------------------------------------ poll */
97
98async function fetchQuote($: EngineInterface, sym: string) {
99 try {
100 const r = await $.http.fetch(quoteUrl(sym), { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; stock-watch)', Accept: 'application/json' } })
101 if (r.status === 429) return { error: 'rate-limited by the price service; will retry' }
102 if (!r.ok && r.text.trim() === '') return { error: `price service returned ${r.status}` }
103 return parseQuote(r.text)
104 } catch (e) {
105 return { error: e instanceof Error ? e.message : 'could not reach the price service' }
106 }
107}
108
109/** Fetches every watched ticker once, records the price, and alerts on a fresh crossing. */
110async function check($: EngineInterface, cfg: Cfg) {
111 if (cfg.isBusy || !(await read($, enabledRef))) return
112 cfg.isBusy = true
113 try {
114 await update($, pollRef, p => ({ ...p, isRunning: true }))
115 for (const { sym } of await stored($)) {
116 const q = await fetchQuote($, sym)
117 // Another session may have changed or alerted since the loop began: re-read before deciding.
118 const ws = await stored($)
119 const i = ws.findIndex(w => w.sym === sym)
120 const w = ws[i]
121 if (w === undefined) continue
122 if ('error' in q) {
123 ws[i] = { ...w, error: q.error }
124 await save($, ws)
125 continue
126 }
127 const { side, alert } = evaluate(w, q.price)
128 ws[i] = { ...w, price: q.price, prev: q.prev, open: q.open ?? w.open, name: q.name ?? w.name, currency: q.currency ?? w.currency, at: await $.clock.now(), error: undefined, fired: side ?? undefined }
129 // Written before the sound plays, so a second session polling right now sees it already fired.
130 await save($, ws)
131 if (alert !== null) await announce($, cfg, ws[i] as Watch, alert, q.price)
132 }
133 } finally {
134 await update($, pollRef, () => ({ isRunning: false, at: 0 })).catch(() => undefined)
135 cfg.isBusy = false
136 }
137}
138
139function tick($: EngineInterface, cfg: Cfg) {
140 $.clock.after(cfg.pollMs, () => {
141 void check($, cfg)
142 .catch(() => undefined)
143 .then(() => tick($, cfg))
144 })
145}
146
147/** Starts the checking loop once per session. */
148function start($: EngineInterface, cfg: Cfg) {
149 if (cfg.isPolling) return
150 cfg.isPolling = true
151 $.clock.after(2_000, () => void check($, cfg).catch(() => undefined))
152 tick($, cfg)
153}
154
155/* ------------------------------------------------------------------ watch list */
156
157/**
158 * Adds or updates every ticker in the settings' watch list. Applied only when the text changed since it was last
159 * applied, so a later /stock change is not undone by the next session. Entries are never removed from here.
160 */
161async function applyWatchlist($: EngineInterface, cfg: Cfg) {
162 if (cfg.watchlist === '') return
163 if ((await $.store.get('watchlistApplied').catch(() => undefined)) === cfg.watchlist) return
164 const ws = await stored($)
165 const bad: string[] = []
166 for (const entry of cfg.watchlist.split(/[;\n]+/).map(x => x.trim()).filter(Boolean)) {
167 const cmd = parseCommand(`add ${entry}`)
168 if (cmd.kind !== 'add') {
169 bad.push(entry)
170 continue
171 }
172 const i = ws.findIndex(w => w.sym === cmd.sym)
173 const prior = i >= 0 ? ws[i] : undefined
174 const next: Watch = { ...(prior ?? { sym: cmd.sym }), low: cmd.low ?? prior?.low, high: cmd.high ?? prior?.high }
175 // A changed limit re-arms; an unchanged one keeps its state.
176 if (prior === undefined || prior.low !== next.low || prior.high !== next.high) next.fired = undefined
177 if (i >= 0) ws[i] = next
178 else if (ws.length < MAX_WATCHES) ws.push(next)
179 }
180 await save($, ws)
181 await $.store.set('watchlistApplied', cfg.watchlist).catch(() => undefined)
182 if (bad.length > 0) $.ui.toast(`stock-watch: could not read ${bad.map(b => `"${b}"`).join(', ')} in the watch list. Use: AAPL 180 200; NVDA high 140`, { timeoutMs: 15_000 })
183}
184
185/* -------------------------------------------------------------------- commands */
186
187async function run($: EngineInterface, cfg: Cfg, args: string): Promise<string> {
188 const cmd = parseCommand(args)
189 switch (cmd.kind) {
190 case 'error':
191 return cmd.text
192 case 'open':
193 case 'list': {
194 const ws = await stored($)
195 await update($, watchesRef, () => ws)
196 if (cmd.kind === 'open') return ws.length === 0 ? `Stock watch: nothing watched yet. ${USAGE}` : `Stock watch: ${ws.length} ticker${ws.length === 1 ? '' : 's'}.`
197 return ws.length === 0 ? 'Stock watch: nothing watched yet.' : ws.map(w => `${w.sym} ${fmtPrice(w.price)} low ${fmtPrice(w.low)} high ${fmtPrice(w.high)}${w.error ? ` (${w.error})` : ''}`).join('\n')
198 }
199 case 'add': {
200 const ws = await stored($)
201 const i = ws.findIndex(w => w.sym === cmd.sym)
202 if (i < 0 && ws.length >= MAX_WATCHES) return `Stock watch: up to ${MAX_WATCHES} tickers.`
203 const prior = i >= 0 ? ws[i] : undefined
204 // A changed limit starts fresh: the price may already be past it, and that should alert.
205 const next: Watch = { ...(prior ?? { sym: cmd.sym }), low: cmd.low ?? prior?.low, high: cmd.high ?? prior?.high, fired: undefined }
206 if (next.low !== undefined && next.high !== undefined && next.low >= next.high) return `The low (${next.low}) must be below the high (${next.high}).`
207 if (i >= 0) ws[i] = next
208 else ws.push(next)
209 await save($, ws)
210 $.clock.after(1, () => void check($, cfg).catch(() => undefined))
211 const off = (await read($, enabledRef)) ? '' : ' Stock watch is off, so this price is not checked until /stock on.'
212 if (next.low === undefined && next.high === undefined) return `Watching ${next.sym}: price only, no alerts. Add a limit any time with /stock add ${next.sym} low 180 high 200.${off}`
213 return `Watching ${next.sym}${next.low !== undefined ? `, alert at or below ${fmtPrice(next.low)}` : ''}${next.high !== undefined ? `, alert at or above ${fmtPrice(next.high)}` : ''}.${off}`
214 }
215 case 'rm': {
216 const ws = await stored($)
217 if (!ws.some(w => w.sym === cmd.sym)) return `Stock watch: ${cmd.sym} is not on the list.`
218 await save($, ws.filter(w => w.sym !== cmd.sym))
219 return `Stopped watching ${cmd.sym}.`
220 }
221 case 'check':
222 if (!(await read($, enabledRef))) return 'Stock watch is off. Run /stock on first.'
223 $.clock.after(1, () => void check($, cfg).catch(() => undefined))
224 return 'Stock watch: checking prices now.'
225 case 'power': {
226 await update($, enabledRef, () => cmd.on)
227 await $.store.set('enabled', cmd.on).catch(() => undefined)
228 await showLine($, await stored($))
229 if (!cmd.on) return 'Stock watch: off. Prices are not checked, no alerts fire, and the price line is hidden. Your watch list is kept. /stock on turns it back on.'
230 $.clock.after(1, () => void check($, cfg).catch(() => undefined))
231 return 'Stock watch: on. Checking prices now.'
232 }
233 case 'test':
234 await chime($, 'high')
235 await chime($, 'low')
236 return 'Stock watch: played the high chime, then the low chime. Silent? That surface has no player; the toast still shows.'
237 case 'mute':
238 case 'unmute':
239 case 'chime': {
240 const m = cmd.kind === 'mute' || (cmd.kind === 'chime' && !cmd.on)
241 await update($, mutedRef, () => m)
242 await $.store.set('muted', m).catch(() => undefined)
243 return m ? 'Stock watch: chime off for every ticker. Toasts still show.' : 'Stock watch: chime on.'
244 }
245 case 'quiet': {
246 const ws = await stored($)
247 if (!ws.some(w => w.sym === cmd.sym)) return `Stock watch: ${cmd.sym} is not on the list.`
248 await save($, ws.map(w => (w.sym === cmd.sym ? { ...w, quiet: cmd.quiet } : w)))
249 return cmd.quiet ? `Stock watch: ${cmd.sym} chime off. Its toast still shows.` : `Stock watch: ${cmd.sym} chime on.`
250 }
251 }
252}
253
254const OPEN = { id: PANE, title: 'Stock watch', focus: true, closeOnEscape: true, rows: 22, columns: 84 } as const
255
256export const register: Register = (on, options) => {
257 const cfg = config(options)
258 statusView = { show: cfg.statusLine, count: cfg.statusCount }
259
260 on('session.start', async ($, e, next) => {
261 await $.command.register({
262 name: 'stock',
263 description: 'Stock watch: alert me when a ticker hits a low or high',
264 argumentHint: 'add AAPL low 180 high 200 | rm AAPL | list | check | test | chime on|off | on | off',
265 immediate: true,
266 })
267 const saved = await $.store.get('enabled').catch(() => undefined)
268 if (saved === false) await update($, enabledRef, () => false)
269 await load($)
270 await applyWatchlist($, cfg)
271 start($, cfg)
272 return next(e)
273 }).catch(($, e, next) => next(e))
274
275 // A session that missed session.start still begins polling on its first prompt.
276 on('prompt.submit', async ($, e, next) => {
277 start($, cfg)
278 return next(e)
279 }).catch(($, e, next) => next(e))
280
281 on('command.run', { command: 'stock' }, async ($, e) => {
282 start($, cfg)
283 const text = await run($, cfg, e.args)
284 if (parseCommand(e.args).kind === 'open') await $.ui.open(OPEN).catch(() => undefined)
285 return { text }
286 })
287
288 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
289 const { Box, Text, Button, Input } = $.ui.resolve(e)
290 const ws = await read($, watchesRef)
291 const muted = await read($, mutedRef)
292 const enabled = await read($, enabledRef)
293 const cols = Math.max(20, e.props.bodyColumns)
294
295 return (
296 <Box flexDirection="column" width={cols}>
297 <Input key="add" label="Add" placeholder="AAPL or AAPL 180 200 or NVDA high 140" onSubmit={value => void run($, cfg, `add ${value}`).then(t => $.ui.toast(t))} />
298 <Box columnGap={1} marginTop={1}>
299 <Button key="check" label="Check now" hotkey="c" variant="secondary" onPress={() => void run($, cfg, 'check')} />
300 <Button key="test" label="Test sound" hotkey="t" variant="secondary" onPress={() => void run($, cfg, 'test')} />
301 <Button key="mute" label={muted ? 'Unmute' : 'Mute'} hotkey="m" variant={muted ? 'primary' : 'secondary'} onPress={() => void run($, cfg, muted ? 'unmute' : 'mute')} />
302 </Box>
303 {!enabled && (
304 <Text color="#f59e0b" wrap="wrap">
305 Stock watch is off. Prices are not checked and no alerts fire. Type /stock on to start again.
306 </Text>
307 )}
308 <Box flexDirection="column" marginTop={1} borderStyle="round" borderColor="#22c55e" paddingX={1} width={cols}>
309 {ws.length === 0 && (
310 <Text dimColor wrap="wrap">
311 Nothing watched yet. Type a ticker above, for example AAPL to watch the price, or AAPL 180 200 to alert at a low and a high.
312 </Text>
313 )}
314 {ws.map(w => {
315 // Up or down from today's open (the previous close when the open is not known yet).
316 const ch = fmtChange(w.price, w.open ?? w.prev)
317 const tone = ch.dir > 0 ? '#22c55e' : ch.dir < 0 ? '#ef4444' : undefined
318 return (
319 <Box key={w.sym} flexDirection="column" marginBottom={1} borderStyle="round" borderColor={tone} paddingX={1} width={cols - 2}>
320 <Box columnGap={1}>
321 <Text bold>{w.sym.padEnd(8)}</Text>
322 <Text bold>{fmtPrice(w.price)}</Text>
323 <Text color={tone} dimColor={ch.dir === 0}>
324 {ch.text}
325 </Text>
326 {w.quiet === true && <Text dimColor>chime off</Text>}
327 {w.fired !== undefined && <Text color={w.fired === 'high' ? '#22c55e' : '#ef4444'} bold>{w.fired === 'high' ? 'HIGH HIT' : 'LOW HIT'}</Text>}
328 <Button key={`rm-${w.sym}`} label="Remove" variant="secondary" onPress={() => void run($, cfg, `rm ${w.sym}`)} />
329 </Box>
330 {(w.low !== undefined || w.high !== undefined) && (
331 <Text dimColor wrap="truncate">
332 {`low ${fmtPrice(w.low)} ${rangeBar(w)} high ${fmtPrice(w.high)}`}
333 </Text>
334 )}
335 {w.error !== undefined && (
336 <Text color="#f59e0b" wrap="truncate">
337 {w.error}
338 </Text>
339 )}
340 </Box>
341 )
342 })}
343 </Box>
344 <Text dimColor wrap="wrap">
345 {`Checked every ${Math.round(cfg.pollMs / 1000)}s while a session is open. Prices come from Yahoo Finance and can lag.`}
346 </Text>
347 </Box>
348 )
349 })
350}
351hooks/watch.ts 160 lines1import type { Watch } from '../types'
2
3export type Side = 'low' | 'high'
4
5export type Cmd =
6 | { kind: 'open' }
7 | { kind: 'add'; sym: string; low?: number; high?: number }
8 | { kind: 'rm'; sym: string }
9 | { kind: 'chime'; on: boolean }
10 | { kind: 'power'; on: boolean }
11 | { kind: 'quiet'; sym: string; quiet: boolean }
12 | { kind: 'list' | 'check' | 'test' | 'mute' | 'unmute' }
13 | { kind: 'error'; text: string }
14
15export const POWER_USAGE = 'Usage: /stock on | off (off stops checking prices, alerts and the status line; the watch list is kept)'
16
17export const CHIME_USAGE = 'Usage: /stock chime on | off (every ticker) · /stock AAPL chime on | off (one ticker)'
18
19export const USAGE =
20 'Usage: /stock add AAPL low 180 high 200 · /stock AAPL 180 200 (low, high) · /stock add AAPL (price only) · /stock rm AAPL · /stock list | check | test | mute | unmute'
21
22const VERBS = new Set(['add', 'rm', 'remove', 'delete', 'list', 'check', 'refresh', 'test', 'mute', 'unmute'])
23const LOW_WORDS = new Set(['low', 'below', 'under', '<', '<=', 'lo'])
24const HIGH_WORDS = new Set(['high', 'above', 'over', '>', '>=', 'hi'])
25// AAPL, BRK-B, BTC-USD, ^GSPC, EURUSD=X, 7203.T
26const SYMBOL = /^[A-Z0-9^][A-Z0-9.=^-]{0,11}$/
27const NUMBER = /^\$?\d[\d,]*\.?\d*$/
28
29export const toNumber = (t: string): number | null => (NUMBER.test(t) ? Number(t.replace(/[$,]/g, '')) : null)
30
31/** Parses what follows `/stock` (or what is typed in the pane's box). */
32export function parseCommand(args: string): Cmd {
33 const tokens = args.trim().split(/\s+/).filter(Boolean)
34 if (tokens.length === 0) return { kind: 'open' }
35 const verb = (tokens[0] ?? '').toLowerCase()
36 if (verb === 'on' || verb === 'off') return tokens.length === 1 ? { kind: 'power', on: verb === 'on' } : { kind: 'error', text: POWER_USAGE }
37 if (verb === 'chime') {
38 const v = (tokens[1] ?? '').toLowerCase()
39 return v === 'on' || v === 'off' ? { kind: 'chime', on: v === 'on' } : { kind: 'error', text: CHIME_USAGE }
40 }
41 // /stock AAPL chime off: silences one ticker's chime; its toast still shows.
42 if (tokens.length === 3 && (tokens[1] ?? '').toLowerCase() === 'chime') {
43 const sym = verb.toUpperCase()
44 const v = (tokens[2] ?? '').toLowerCase()
45 if (!SYMBOL.test(sym) || (v !== 'on' && v !== 'off')) return { kind: 'error', text: CHIME_USAGE }
46 return { kind: 'quiet', sym, quiet: v === 'off' }
47 }
48 if (verb === 'list' || verb === 'check' || verb === 'test' || verb === 'mute' || verb === 'unmute') return { kind: verb }
49 if (verb === 'refresh') return { kind: 'check' }
50
51 const rest = VERBS.has(verb) ? tokens.slice(1) : tokens
52 const sym = (rest[0] ?? '').toUpperCase()
53 if (verb === 'rm' || verb === 'remove' || verb === 'delete') return SYMBOL.test(sym) ? { kind: 'rm', sym } : { kind: 'error', text: USAGE }
54 if (!SYMBOL.test(sym) || toNumber(sym) !== null) return { kind: 'error', text: USAGE }
55
56 let low: number | undefined
57 let high: number | undefined
58 const bare: number[] = []
59 for (let i = 1; i < rest.length; i++) {
60 const t = (rest[i] ?? '').toLowerCase()
61 const side = LOW_WORDS.has(t) ? 'low' : HIGH_WORDS.has(t) ? 'high' : null
62 if (side !== null) {
63 const n = toNumber(rest[i + 1] ?? '')
64 if (n === null) return { kind: 'error', text: `"${t}" needs a price after it. ${USAGE}` }
65 if (side === 'low') low = n
66 else high = n
67 i++
68 continue
69 }
70 const n = toNumber(t)
71 if (n === null) return { kind: 'error', text: `Did not understand "${rest[i]}". ${USAGE}` }
72 bare.push(n)
73 }
74 if (bare.length > 2) return { kind: 'error', text: USAGE }
75 if (bare.length === 1) return { kind: 'error', text: `One bare price is ambiguous: say "low ${bare[0]}" or "high ${bare[0]}".` }
76 if (bare.length === 2 && low === undefined && high === undefined) [low, high] = [Math.min(...bare), Math.max(...bare)]
77 // Price-only needs the explicit `add`, so a mistyped command is not mistaken for a ticker.
78 if (low === undefined && high === undefined && verb !== 'add') return { kind: 'error', text: `To just watch ${sym}'s price, use /stock add ${sym}. ${USAGE}` }
79 if (low !== undefined && high !== undefined && low >= high) return { kind: 'error', text: `The low (${low}) must be below the high (${high}).` }
80 return { kind: 'add', sym, low, high }
81}
82
83/* -------------------------------------------------------------------- quotes */
84
85export type Quote = { price: number; prev?: number; open?: number; name?: string; currency?: string }
86
87/** Reads Yahoo Finance's chart response. Defensive: any other shape is an error message, never a throw. */
88export function parseQuote(text: string): Quote | { error: string } {
89 let j: any
90 try {
91 j = JSON.parse(text)
92 } catch {
93 return { error: 'the price service did not answer with data (it may be rate-limiting)' }
94 }
95 const err = j?.chart?.error
96 if (err) return { error: String(err.description ?? err.code ?? 'unknown symbol') }
97 const m = j?.chart?.result?.[0]?.meta
98 const price = m?.regularMarketPrice
99 if (typeof price !== 'number' || !Number.isFinite(price)) return { error: 'no price in the response' }
100 const prev = typeof m.chartPreviousClose === 'number' ? m.chartPreviousClose : typeof m.previousClose === 'number' ? m.previousClose : undefined
101 // Today's open is the latest daily candle's open; the previous close is the fallback baseline.
102 const opens: unknown[] = j.chart.result[0].indicators?.quote?.[0]?.open ?? []
103 const open = [...opens].reverse().find((v): v is number => typeof v === 'number' && Number.isFinite(v))
104 return { price, prev, open, name: m.longName ?? m.shortName, currency: m.currency }
105}
106
107export const quoteUrl = (sym: string) => `https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(sym)}?interval=1d&range=1d`
108
109/* ------------------------------------------------------------------- alerting */
110
111/**
112 * What a new price does to a watch: which limit it is past (null inside the band), and whether that is a
113 * fresh crossing worth an alert. A limit alerts once; it re-arms when the price comes back inside the band.
114 */
115export function evaluate(w: Watch, price: number): { side: Side | null; alert: Side | null } {
116 const side: Side | null = w.low !== undefined && price <= w.low ? 'low' : w.high !== undefined && price >= w.high ? 'high' : null
117 return { side, alert: side !== null && w.fired !== side ? side : null }
118}
119
120/* ----------------------------------------------------------------- formatting */
121
122export const fmtPrice = (n: number | undefined): string =>
123 n === undefined ? '-' : n >= 1000 ? n.toLocaleString('en-US', { maximumFractionDigits: 2 }) : n.toFixed(n >= 1 ? 2 : 4)
124
125export function fmtChange(price: number | undefined, prev: number | undefined): { text: string; dir: 1 | -1 | 0 } {
126 if (price === undefined || prev === undefined || prev === 0) return { text: '', dir: 0 }
127 const pct = ((price - prev) / prev) * 100
128 return { text: `${pct >= 0 ? '▲' : '▼'}${Math.abs(pct).toFixed(2)}%`, dir: pct > 0 ? 1 : pct < 0 ? -1 : 0 }
129}
130
131/** `[···●······]` with the price's place between the low and the high; `!` at a limit. */
132export function rangeBar(w: Watch, width = 16): string {
133 if (w.price === undefined || w.low === undefined || w.high === undefined) return ''
134 const t = Math.min(1, Math.max(0, (w.price - w.low) / (w.high - w.low)))
135 const at = Math.round(t * (width - 1))
136 return `[${Array.from({ length: width }, (_, i) => (i === at ? (t === 0 || t === 1 ? '!' : '●') : '·')).join('')}]`
137}
138
139/** Prices without cents once they are large (83,094 not 83,094.31): the status line is narrow. */
140export const fmtShort = (n: number | undefined): string => (n !== undefined && n >= 1000 ? n.toLocaleString('en-US', { maximumFractionDigits: 0 }) : fmtPrice(n))
141
142/**
143 * The pinned line under the prompt: the first few tickers with ▲ or ▼ from today's open (the previous close
144 * until the open is known), HIGH or LOW once a limit has been hit, and +N for the ones not shown.
145 */
146export function statusText(ws: Watch[], count = 3): string | undefined {
147 const shown = ws.filter(w => w.price !== undefined).slice(0, count)
148 if (shown.length === 0) return undefined
149 const parts = shown.map(w => {
150 const dir = fmtChange(w.price, w.open ?? w.prev).dir
151 return `${w.sym} ${fmtShort(w.price)}${dir > 0 ? ' ▲' : dir < 0 ? ' ▼' : ''}${w.fired === undefined ? '' : w.fired === 'high' ? ' HIGH' : ' LOW'}`
152 })
153 return `${parts.join(' · ')}${ws.length > shown.length ? ` +${ws.length - shown.length}` : ''}`
154}
155
156export function alertText(w: Watch, side: Side, price: number): string {
157 const limit = side === 'high' ? w.high : w.low
158 return `${side === 'high' ? '📈' : '📉'} ${w.sym} ${side === 'high' ? 'reached your high' : 'fell to your low'}: ${fmtPrice(price)}${w.currency ? ` ${w.currency}` : ''} (limit ${fmtPrice(limit)})`
159}
160types/index.d.ts 34 lines1/** One ticker being watched. Stored in the plugin's store, shared by every session on the machine. */
2export type Watch = {
3 sym: string
4 low?: number
5 high?: number
6 /** Which limit already alerted. Cleared when the price is back inside the band, which re-arms it. */
7 fired?: 'low' | 'high'
8 price?: number
9 /** Today's open, the baseline for the up/down colour. Falls back to the previous close when absent. */
10 open?: number
11 prev?: number
12 /** This ticker's chime is off. Its toast still shows. */
13 quiet?: boolean
14 name?: string
15 currency?: string
16 /** When the price was last fetched (ms since epoch). */
17 at?: number
18 /** Why the last fetch failed, if it did. */
19 error?: string
20}
21
22declare module 'claude-code' {
23 interface PluginState {
24 'stock-watch': {
25 watches: Watch[]
26 muted: boolean
27 /** Off: prices are not checked and no alerts or status line. Remembered. */
28 enabled: boolean
29 /** The last poll: when it ended, and whether one is running now. */
30 poll: { isRunning: boolean; at: number }
31 }
32 }
33}
34