Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Created September 23, 2026 14:04
Show Gist options
  • Select an option

  • Save qianlifeng/a99f529ece21561ff7b73d872e72998c to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/a99f529ece21561ff7b73d872e72998c to your computer and use it in GitHub Desktop.
Wox.Plugin.Stock
// {
// "Id": "074ff6c9-50d1-4c26-9583-c6e48b3c48f2",
// "Name": "i18n:plugin_name",
// "Author": "qianlifeng",
// "Version": "1.0.0",
// "MinWoxVersion": "2.4.2",
// "Runtime": "NODEJS",
// "Description": "i18n:plugin_description",
// "Icon": "svg:<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='14' fill='#1a4a5c'/><path d='M15 14v22M24 11v26M33 8v24' fill='none' stroke='#cbd5e1' stroke-width='2' stroke-linecap='round'/><rect x='11.5' y='21' width='7' height='9' rx='1.5' fill='#fb7185'/><rect x='20.5' y='17' width='7' height='11' rx='1.5' fill='#34d399'/><rect x='29.5' y='13' width='7' height='13' rx='1.5' fill='#6ee7b7'/></svg>",
// "TriggerKeywords": ["stock", "gp"],
// "SupportedOS": ["Windows", "Linux", "Macos"],
// "Features": [
// { "Name": "debounce", "Params": { "IntervalMs": 300 } },
// { "Name": "ignoreAutoScore" },
// { "Name": "mru", "Params": { "HashBy": "scoreKey" } }
// ],
// "SettingDefinitions": [
// {
// "Type": "table",
// "Value": {
// "Key": "watchlist",
// "DefaultValue": "[]",
// "Title": "i18n:setting_watchlist",
// "Tooltip": "i18n:setting_watchlist_tip",
// "MaxHeight": 360,
// "InlineTable": true,
// "Columns": [
// {
// "Key": "name",
// "Label": "i18n:column_name",
// "Type": "text",
// "Width": 140
// },
// {
// "Key": "code",
// "Label": "i18n:column_code",
// "Type": "text",
// "Width": 110,
// "Validators": [{ "Type": "not_empty", "Value": {} }]
// },
// {
// "Key": "market",
// "Label": "i18n:column_market",
// "Type": "select",
// "Width": 120,
// "Validators": [{ "Type": "not_empty", "Value": {} }],
// "SelectOptions": [
// { "Label": "i18n:market_a", "Value": "a" },
// { "Label": "i18n:market_hk", "Value": "hk" },
// { "Label": "i18n:market_us", "Value": "us" }
// ]
// },
// {
// "Key": "quoteId",
// "Label": "i18n:column_quote_id",
// "Tooltip": "i18n:column_quote_id_tip",
// "Type": "text",
// "Width": 140,
// "HideInTable": true
// }
// ]
// },
// "IsPlatformSpecific": false
// }
// ],
// "I18n": {
// "en_US": {
// "plugin_name": "Stock",
// "plugin_description": "Look up A-share, Hong Kong, and US quotes. Each market can use a different source.",
// "setting_watchlist": "Watchlist",
// "setting_watchlist_tip": "Quotes refresh about once a minute. Each market has its own source order and tries the next source when one fails.\n\nAdd a row here, or use Add to watchlist on a search result:\n1. Code: 600519, 00700, or AAPL\n2. Market: A-share, Hong Kong, or US\n3. Name is optional. Quote ID is filled in when the source provides one.",
// "column_name": "Name",
// "column_code": "Code",
// "column_market": "Market",
// "column_quote_id": "Quote ID",
// "column_quote_id_tip": "Source id such as 1.600519 or 105.AAPL. Leave blank for a US ticker and the plugin will use a source that accepts the code.",
// "sort": "Sort",
// "sort_default": "Default",
// "sort_desc": "Gainers",
// "sort_asc": "Losers",
// "market_a": "A-share",
// "market_hk": "Hong Kong",
// "market_us": "US",
// "empty_watchlist_title": "Watchlist is empty",
// "empty_watchlist_sub": "Type a name or code, such as 茅台, 600519, 00700, or AAPL",
// "empty_title": "No matching stock",
// "empty_sub": "Try a code or a Chinese name",
// "error_title": "Quote lookup failed",
// "quote_unavailable": "Quote unavailable",
// "action_copy_price": "Copy price",
// "action_copy_code": "Copy code",
// "action_open": "Open quote",
// "action_add": "Add to watchlist",
// "action_remove": "Remove from watchlist",
// "notify_copied": "Copied",
// "notify_added": "Added to watchlist",
// "notify_removed": "Removed from watchlist",
// "notify_exists": "Already in the watchlist",
// "notify_full": "Watchlist is full",
// "notify_copy_failed": "Could not copy",
// "notify_open_failed": "Could not open the quote page",
// "notify_save_failed": "Could not save the watchlist",
// "source_eastmoney": "East Money",
// "source_tencent": "Tencent",
// "source_yahoo": "Yahoo",
// "relative_now": "Just now",
// "relative_minute": "{n} minute ago",
// "relative_minutes": "{n} minutes ago",
// "relative_hour": "{n} hour ago",
// "relative_hours": "{n} hours ago",
// "relative_day": "{n} day ago",
// "relative_days": "{n} days ago",
// "session_pre": "Pre",
// "session_post": "Post",
// "tool_search": "Search A-share, Hong Kong, and US stocks by name or code",
// "tool_quotes": "Get cached-or-live quotes for known stocks. Tries the next source for a market when one fails.",
// "tool_list": "List watchlist stocks without prices",
// "tool_add": "Add a stock to the watchlist",
// "tool_remove": "Remove a stock from the watchlist"
// },
// "zh_CN": {
// "plugin_name": "股票",
// "plugin_description": "查询 A 股、港股和美股报价。每个市场可以换自己的数据源。",
// "setting_watchlist": "自选股",
// "setting_watchlist_tip": "报价大约每分钟刷新一次。每个市场有自己的数据源顺序,某个源失败时会尝试下一个。\n\n可以在这里添加,也可以在搜索结果里加入自选:\n1. 代码:600519、00700 或 AAPL\n2. 市场:A股、港股或美股\n3. 名称可以不填。行情 ID 能自动补上时会写上。",
// "column_name": "名称",
// "column_code": "代码",
// "column_market": "市场",
// "column_quote_id": "行情 ID",
// "column_quote_id_tip": "数据源编号,例如 1.600519 或 105.AAPL。美股只填代码时可以留空,插件会改用接受代码的源。",
// "sort": "排序",
// "sort_default": "默认",
// "sort_desc": "涨幅",
// "sort_asc": "跌幅",
// "market_a": "A股",
// "market_hk": "港股",
// "market_us": "美股",
// "empty_watchlist_title": "自选股是空的",
// "empty_watchlist_sub": "输入名称或代码,例如 茅台、600519、00700、AAPL",
// "empty_title": "没有匹配的股票",
// "empty_sub": "试试代码或中文名",
// "error_title": "行情查询失败",
// "quote_unavailable": "暂时没有报价",
// "action_copy_price": "复制价格",
// "action_copy_code": "复制代码",
// "action_open": "打开行情",
// "action_add": "加入自选",
// "action_remove": "移出自选",
// "notify_copied": "已复制",
// "notify_added": "已加入自选",
// "notify_removed": "已移出自选",
// "notify_exists": "自选里已经有了",
// "notify_full": "自选已满",
// "notify_copy_failed": "复制失败",
// "notify_open_failed": "无法打开行情页",
// "notify_save_failed": "自选保存失败",
// "source_eastmoney": "东方财富",
// "source_tencent": "腾讯",
// "source_yahoo": "Yahoo",
// "relative_now": "刚刚",
// "relative_minute": "{n} 分钟前",
// "relative_minutes": "{n} 分钟前",
// "relative_hour": "{n} 小时前",
// "relative_hours": "{n} 小时前",
// "relative_day": "{n} 天前",
// "relative_days": "{n} 天前",
// "session_pre": "盘前",
// "session_post": "盘后",
// "tool_search": "按名称或代码搜索 A 股、港股和美股",
// "tool_quotes": "查询已知股票的报价。某个市场的数据源失败时会尝试该市场的下一个源。",
// "tool_list": "列出不带价格的自选股",
// "tool_add": "把股票加入自选",
// "tool_remove": "把股票移出自选"
// }
// }
// }
/**
* Stock quotes for A-shares, Hong Kong, and the US.
*
* Each market has an ordered source list in MARKET_PROVIDER_ORDER.
* Search uses SEARCH_PROVIDER_ORDER. A later source runs only when an
* earlier one throws or cannot price that symbol. To replace a source,
* add a provider object and put its id in the market's list.
* Quotes are cached for 60 seconds.
*/
const { spawn } = require("child_process")
const fs = require("fs")
const https = require("https")
const http = require("http")
const zlib = require("zlib")
const SETTING_WATCHLIST = "watchlist"
const QUOTE_TTL_MS = 60 * 1000
const MAX_SEARCH_RESULTS = 8
const MAX_WATCHLIST = 50
const REQUEST_TIMEOUT_MS = 8000
const USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
const MARKETS = ["a", "hk", "us"]
// First id is preferred. The rest are fallbacks for that market only.
const MARKET_PROVIDER_ORDER = {
a: ["eastmoney", "tencent"],
hk: ["eastmoney", "tencent"],
us: ["eastmoney", "yahoo", "tencent"]
}
// A later search source runs only when an earlier one throws, not when it
// returns no matches.
const SEARCH_PROVIDER_ORDER = ["eastmoney", "yahoo"]
const PLUGIN_ICON_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='14' fill='#1a4a5c'/><path d='M15 14v22M24 11v26M33 8v24' fill='none' stroke='#cbd5e1' stroke-width='2' stroke-linecap='round'/><rect x='11.5' y='21' width='7' height='9' rx='1.5' fill='#fb7185'/><rect x='20.5' y='17' width='7' height='11' rx='1.5' fill='#34d399'/><rect x='29.5' y='13' width='7' height='13' rx='1.5' fill='#6ee7b7'/></svg>"
const DOWN_ICON_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='14' fill='#1a4a5c'/><path d='M15 10v24M24 12v26M33 16v20' fill='none' stroke='#cbd5e1' stroke-width='2' stroke-linecap='round'/><rect x='11.5' y='14' width='7' height='13' rx='1.5' fill='#fda4af'/><rect x='20.5' y='18' width='7' height='11' rx='1.5' fill='#fb7185'/><rect x='29.5' y='22' width='7' height='9' rx='1.5' fill='#e11d48'/></svg>"
const FLAT_ICON_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='14' fill='#1a4a5c'/><path d='M15 14v22M24 12v24M33 14v22' fill='none' stroke='#cbd5e1' stroke-width='2' stroke-linecap='round'/><rect x='11.5' y='18' width='7' height='11' rx='1.5' fill='#94a3b8'/><rect x='20.5' y='16' width='7' height='12' rx='1.5' fill='#cbd5e1'/><rect x='29.5' y='18' width='7' height='11' rx='1.5' fill='#94a3b8'/></svg>"
const PRE_ICON_PATH = "M6 2 4 4h4zm-.5 3.5V7h1V5.5zM2.818 6.611l-.707.707 1.06 1.061.708-.707zm6.364 0-1.06 1.061.706.707 1.06-1.06zM6 8.001a2.51 2.51 0 0 0-2.45 2H1v1h10v-1H8.45A2.51 2.51 0 0 0 6 8"
const POST_ICON_PATH = "M8.2 1.8a4.8 4.8 0 1 0 3.6 8.1A3.8 3.8 0 0 1 8.2 1.8z"
const ACTION_COPY_ICON = { ImageType: "svg", ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"8\" y=\"8\" width=\"12\" height=\"12\" rx=\"2\"/><path d=\"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2\"/></svg>" }
const ACTION_OPEN_ICON = { ImageType: "svg", ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M14 5h5v5M19 5l-9 9\"/><path d=\"M13 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-7\"/></svg>" }
const ACTION_ADD_ICON = { ImageType: "svg", ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 5v14M5 12h14\"/></svg>" }
const ACTION_DELETE_ICON = { ImageType: "svg", ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3\"/></svg>" }
const I18N = readOwnI18n()
function readOwnI18n() {
const source = fs.readFileSync(__filename, "utf8")
const lines = source.split(/\r?\n/)
let header = ""
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) {
if (header) header += "\n"
continue
}
if (!trimmed.startsWith("//")) break
header += `${trimmed.slice(2).trim()}\n`
}
const start = header.indexOf("{")
const metadata = JSON.parse(header.slice(start))
return metadata.I18n || {}
}
function finiteNumber(value) {
const number = typeof value === "number" ? value : Number(String(value ?? "").replace(/,/g, ""))
return Number.isFinite(number) ? number : NaN
}
function asArray(value) {
if (Array.isArray(value)) return value
if (value && typeof value === "object") return Object.values(value)
return []
}
function instrumentKey(instrument) {
if (!instrument) return ""
if (instrument.quoteId) return instrument.quoteId
return `${instrument.market}:${instrument.code}`
}
function sameInstrument(left, right) {
if (!left || !right) return false
if (left.quoteId && right.quoteId && left.quoteId === right.quoteId) return true
return left.market === right.market && String(left.code).toUpperCase() === String(right.code).toUpperCase()
}
// normalizeInstrument turns a search row or watchlist row into provider-neutral identity.
function normalizeInstrument(raw) {
if (!raw || !MARKETS.includes(raw.market)) return null
let code = String(raw.code || "").trim()
if (!code) return null
if (raw.market === "us") code = code.toUpperCase()
if (raw.market === "hk") code = code.replace(/\D/g, "").padStart(5, "0")
if (raw.market === "a") code = code.replace(/\D/g, "")
if (!code) return null
return {
market: raw.market,
code,
name: String(raw.name || code).trim() || code,
quoteId: String(raw.quoteId || "").trim()
}
}
function normalizeWatchlist(raw) {
let rows = raw
if (typeof raw === "string") {
try {
rows = JSON.parse(raw || "[]")
} catch {
rows = []
}
}
if (!Array.isArray(rows)) return []
const seen = new Set()
const items = []
for (const row of rows) {
const item = normalizeInstrument(row)
if (!item) continue
const key = instrumentKey(item)
if (seen.has(key)) continue
seen.add(key)
items.push(item)
if (items.length >= MAX_WATCHLIST) break
}
return items
}
function addWatchItem(list, raw) {
const item = normalizeInstrument(raw)
const next = normalizeWatchlist(list)
if (!item) return { list: next, item: null, added: false, reason: "invalid" }
if (next.some((row) => sameInstrument(row, item))) {
return { list: next, item, added: false, reason: "exists" }
}
if (next.length >= MAX_WATCHLIST) {
return { list: next, item, added: false, reason: "full" }
}
next.push(item)
return { list: next, item, added: true, reason: "added" }
}
function removeWatchItem(list, raw) {
const next = normalizeWatchlist(list)
const target = {
market: raw && raw.market,
code: raw && raw.code,
quoteId: raw && raw.quoteId ? String(raw.quoteId) : ""
}
const filtered = next.filter((row) => !sameInstrument(row, target))
return { list: filtered, removed: filtered.length !== next.length }
}
// inferInstrument builds an identity from a bare code when name search is down.
function inferInstrument(text) {
const raw = String(text || "").trim()
if (/^\d{6}$/.test(raw)) {
let quoteId = ""
if (/^[69]/.test(raw)) quoteId = `1.${raw}`
else if (/^[03]/.test(raw)) quoteId = `0.${raw}`
if (!quoteId) return null
return normalizeInstrument({ market: "a", code: raw, name: raw, quoteId })
}
if (/^\d{1,5}$/.test(raw)) {
const code = raw.padStart(5, "0")
return normalizeInstrument({ market: "hk", code, name: code, quoteId: `116.${code}` })
}
if (/^[A-Za-z]{1,5}([.\-][A-Za-z])?$/.test(raw)) {
return normalizeInstrument({ market: "us", code: raw.toUpperCase(), name: raw.toUpperCase(), quoteId: "" })
}
return null
}
function blockedSecurity(row) {
const blob = `${row.Name || ""} ${row.SecurityTypeName || ""}`
if (/债|指数|基金|窝轮|牛熊|权证|界内证/.test(blob)) return true
if (/notes|bond|warrant|preferred|\betf\b/i.test(blob)) return true
if (/-R$/.test(row.Name || "")) return true
return false
}
function marketOfClassify(classify) {
if (classify === "AStock") return "a"
if (classify === "HK") return "hk"
if (classify === "UsStock") return "us"
return ""
}
function rankHit(query, code, name, pinyin, market) {
const needle = String(query || "").trim().toLowerCase()
const values = [code, name, pinyin].map((value) => String(value || "").toLowerCase())
if (values.some((value) => value === needle)) return 0
// Hong Kong codes are often typed without leading zeros. Do not apply that
// to A-shares, or 00700 would also match 000700.
if (market === "hk") {
const bareCode = String(code || "").replace(/^0+/, "")
const bareNeedle = needle.replace(/^0+/, "")
if (bareCode && bareCode === bareNeedle) return 0
}
// Anything else stays in the search engine's order. A later English name
// such as "Google DeepMind..." must not hide 谷歌, whose name does not contain "google".
return 1
}
// selectSearchHits keeps A-share, Hong Kong, and US equities from an East Money suggest payload.
function selectSearchHits(rows, query, markets, limit = MAX_SEARCH_RESULTS) {
const allowed = new Set(markets)
const picked = []
asArray(rows).forEach((row, index) => {
const market = marketOfClassify(row.Classify)
const quoteId = String(row.QuoteID || "").trim()
const codeFromId = quoteId.includes(".") ? quoteId.split(".").slice(1).join(".") : ""
if (!market || !allowed.has(market) || blockedSecurity(row)) return
const item = normalizeInstrument({
market,
code: codeFromId || row.Code,
name: row.Name || row.Code,
quoteId
})
if (!item) return
// AAPL.TO is Toronto, not a US listing. Share classes such as BRK.B stay.
if (item.market === "us" && !/^[A-Z]{1,5}([.\-][A-Z])?$/.test(item.code)) return
picked.push({
...item,
rank: rankHit(query, item.code, item.name, row.PinYin, item.market),
index
})
})
picked.sort((left, right) => left.rank - right.rank || left.index - right.index)
const exact = picked.filter((item) => item.rank === 0)
const chosen = exact.length ? exact : picked
return chosen.slice(0, limit).map(({ market, code, name, quoteId }) => ({ market, code, name, quoteId }))
}
class TtlCache {
constructor(ttlMs) {
this.ttlMs = ttlMs
this.values = new Map()
}
get(key, now) {
const hit = this.values.get(key)
if (!hit || hit.expires <= now) {
this.values.delete(key)
return null
}
return hit.value
}
set(key, value, now) {
this.values.set(key, { value, expires: now + this.ttlMs })
}
}
function quoteCacheKey(providerId, symbol) {
return `quote:${providerId}:${symbol}`
}
// httpGet decodes GBK quote pages and follows a few redirects. Callers inject
// a fake fetch in tests.
function httpGet(url, headers = {}, redirects = 0, attempt = 0) {
return new Promise((resolve, reject) => {
const lib = url.startsWith("http://") ? http : https
const req = lib.get(url, {
headers: { "User-Agent": USER_AGENT, Accept: "*/*", ...headers },
timeout: REQUEST_TIMEOUT_MS
}, (res) => {
const status = res.statusCode || 0
if (status >= 300 && status < 400 && res.headers.location && redirects < 3) {
res.resume()
const next = new URL(res.headers.location, url).toString()
httpGet(next, headers, redirects + 1).then(resolve, reject)
return
}
const chunks = []
res.on("data", (chunk) => chunks.push(chunk))
res.on("end", () => {
try {
if (status >= 400) {
reject(new Error(`HTTP ${status} for ${url}`))
return
}
let buf = Buffer.concat(chunks)
if (buf.length >= 2 && buf[0] === 0x1f && buf[1] === 0x8b) buf = zlib.gunzipSync(buf)
const contentType = String(res.headers["content-type"] || "")
const encoding = /gbk|gb2312/i.test(contentType) || /gtimg\.cn/i.test(url) ? "gbk" : "utf8"
resolve(new TextDecoder(encoding).decode(buf))
} catch (err) {
reject(err)
}
})
})
req.on("error", reject)
req.on("timeout", () => {
req.destroy(new Error(`timeout for ${url}`))
})
}).catch((err) => {
const message = `${err && err.code ? err.code : ""} ${err && err.message ? err.message : err}`
if (attempt < 1 && redirects === 0 && /socket hang up|ECONNRESET|ETIMEDOUT|timeout/i.test(message)) {
return httpGet(url, headers, 0, attempt + 1)
}
throw err
})
}
function currencyForMarket(market) {
if (market === "hk") return "HKD"
if (market === "us") return "USD"
return "CNY"
}
function currencyForEastMoneyMarket(marketCode) {
const code = Number(marketCode)
if (code === 116) return "HKD"
if (code === 105 || code === 106 || code === 107) return "USD"
return "CNY"
}
function parseEastMoneyListRow(row) {
return {
symbol: `${row.f13}.${row.f12}`,
code: String(row.f12 || ""),
name: row.f14 || "",
price: finiteNumber(row.f2),
changePercent: finiteNumber(row.f3),
change: finiteNumber(row.f4),
volume: finiteNumber(row.f5),
amount: finiteNumber(row.f6),
turnover: finiteNumber(row.f8),
pe: finiteNumber(row.f9),
high: finiteNumber(row.f15),
low: finiteNumber(row.f16),
open: finiteNumber(row.f17),
prevClose: finiteNumber(row.f18),
time: finiteNumber(row.f124) || 0,
timeText: "",
currency: currencyForEastMoneyMarket(row.f13)
}
}
function parseEastMoneySingleRow(row) {
return {
symbol: "",
code: String(row.f57 || ""),
name: row.f58 || "",
price: finiteNumber(row.f43),
change: finiteNumber(row.f169),
changePercent: finiteNumber(row.f170),
open: finiteNumber(row.f46),
high: finiteNumber(row.f44),
low: finiteNumber(row.f45),
prevClose: finiteNumber(row.f60),
volume: finiteNumber(row.f47),
amount: finiteNumber(row.f48),
turnover: finiteNumber(row.f168),
pe: finiteNumber(row.f162),
time: finiteNumber(row.f86) || 0,
timeText: "",
currency: ""
}
}
// parseEastMoneyQuotes accepts either the batch ulist payload or one stock/get payload.
function parseEastMoneyQuotes(payload) {
const body = typeof payload === "string" ? JSON.parse(payload) : payload
if (!body || body.rc !== 0 || !body.data) {
throw new Error("eastmoney quote failed")
}
if (body.data.diff) {
return asArray(body.data.diff).map(parseEastMoneyListRow).filter((quote) => quote.symbol && quote.price > 0)
}
const quote = parseEastMoneySingleRow(body.data)
return quote.price > 0 ? [quote] : []
}
// Tencent packs one tilde-separated record per line. Field 35 carries the
// raw turnover for A-shares; field 37 is 万元 there and raw currency for US.
function parseTencentQuotes(text) {
const quotes = []
const pattern = /v_([A-Za-z0-9_]+)="([^"]*)"/g
for (const match of String(text || "").matchAll(pattern)) {
const symbol = match[1]
const parts = match[2].split("~")
const price = finiteNumber(parts[3])
if (!(price > 0)) continue
const slash = String(parts[35] || "").split("/")
let amount = NaN
if (slash.length >= 3 && finiteNumber(slash[2]) > 0) amount = finiteNumber(slash[2])
else if (finiteNumber(parts[37]) > 0) {
amount = symbol.toLowerCase().startsWith("us") ? finiteNumber(parts[37]) : finiteNumber(parts[37]) * 10000
}
const rawCode = String(parts[2] || "")
quotes.push({
symbol,
code: rawCode.split(".")[0] || rawCode,
name: parts[1] || "",
price,
prevClose: finiteNumber(parts[4]),
open: finiteNumber(parts[5]),
volume: finiteNumber(parts[6]),
timeText: parts[30] || "",
time: parseExchangeTime(parts[30], symbol),
change: finiteNumber(parts[31]),
changePercent: finiteNumber(parts[32]),
high: finiteNumber(parts[33]),
low: finiteNumber(parts[34]),
amount,
turnover: finiteNumber(parts[38]),
pe: finiteNumber(parts[39]),
currency: symbol.toLowerCase().startsWith("hk") ? "HKD" : symbol.toLowerCase().startsWith("us") ? "USD" : "CNY"
})
}
return quotes
}
function parseYahooChart(payload, requestedSymbol, nowSeconds = Date.now() / 1000) {
const body = typeof payload === "string" ? JSON.parse(payload) : payload
const result = body && body.chart && Array.isArray(body.chart.result) ? body.chart.result[0] : null
if (!result || !result.meta) {
throw new Error(body && body.chart && body.chart.error ? "yahoo quote failed" : "yahoo quote missing")
}
const meta = result.meta
const price = finiteNumber(meta.regularMarketPrice)
const prevClose = finiteNumber(meta.chartPreviousClose ?? meta.previousClose)
const change = finiteNumber(meta.regularMarketChange) || (price > 0 && prevClose > 0 ? price - prevClose : NaN)
return {
symbol: requestedSymbol || meta.symbol || "",
code: String(meta.symbol || requestedSymbol || "").split(".")[0],
name: meta.shortName || meta.longName || meta.symbol || "",
price,
change,
changePercent: finiteNumber(meta.regularMarketChangePercent),
open: finiteNumber(meta.regularMarketOpen),
high: finiteNumber(meta.regularMarketDayHigh),
low: finiteNumber(meta.regularMarketDayLow),
prevClose,
volume: finiteNumber(meta.regularMarketVolume),
amount: NaN,
turnover: NaN,
pe: NaN,
currency: meta.currency || "",
time: finiteNumber(meta.regularMarketTime) || 0,
timeText: "",
extended: extendedSession(meta, nowSeconds)
}
}
// extendedSession is the US pre-market or after-hours print. During the regular
// session it stays empty so the row keeps the regular price only.
function extendedSession(meta, nowSeconds) {
const regular = finiteNumber(meta && meta.regularMarketPrice)
const price = finiteNumber(meta && meta.fulldayPrice)
if (!(regular > 0) || !(price > 0)) return null
if (Math.abs(price - regular) < Math.max(0.01, regular * 0.00005)) return null
const period = meta.currentTradingPeriod || {}
const pre = period.pre || {}
const regularPeriod = period.regular || {}
const now = Number(nowSeconds) || 0
if (now >= regularPeriod.start && now < regularPeriod.end) return null
const session = now >= pre.start && now < pre.end ? "pre" : "post"
return {
session,
price,
change: finiteNumber(meta.fulldayChange),
changePercent: finiteNumber(meta.fulldayChangePercent)
}
}
function yahooSearchHit(hit) {
const quoteType = String(hit.quoteType || "")
if (quoteType && quoteType !== "EQUITY") return null
const symbol = String(hit.symbol || "").toUpperCase()
const name = hit.shortname || hit.longname || hit.shortName || symbol
if (symbol.endsWith(".SS")) {
const code = symbol.slice(0, -3)
return { market: "a", code, name, quoteId: `1.${code}` }
}
if (symbol.endsWith(".SZ")) {
const code = symbol.slice(0, -3)
return { market: "a", code, name, quoteId: `0.${code}` }
}
if (symbol.endsWith(".HK")) {
const code = symbol.slice(0, -3).replace(/\D/g, "").padStart(5, "0")
return { market: "hk", code, name, quoteId: `116.${code}` }
}
if (/^[A-Z]{1,5}([.\-][A-Z])?$/.test(symbol)) {
return { market: "us", code: symbol, name, quoteId: "" }
}
return null
}
const PROVIDERS = {
eastmoney: {
id: "eastmoney",
labelKey: "source_eastmoney",
markets: ["a", "hk", "us"],
symbolFor(instrument) {
if (instrument.quoteId) return instrument.quoteId
if (instrument.market === "a") {
if (/^[69]/.test(instrument.code)) return `1.${instrument.code}`
if (/^[03]/.test(instrument.code)) return `0.${instrument.code}`
}
if (instrument.market === "hk") return `116.${instrument.code}`
return ""
},
pageUrl(instrument) {
if (instrument.market === "hk") return `https://quote.eastmoney.com/hk/${instrument.code}.html`
if (instrument.market === "us") return `https://quote.eastmoney.com/us/${instrument.code}.html`
const prefix = this.symbolFor(instrument).startsWith("0.") ? "sz" : "sh"
return `https://quote.eastmoney.com/${prefix}${instrument.code}.html`
},
async search(text, markets, fetchImpl) {
const url = `https://searchadapter.eastmoney.com/api/suggest/get?input=${encodeURIComponent(text)}&type=14&count=30`
const payload = JSON.parse(await fetchImpl(url))
const rows = payload && payload.QuotationCodeTable ? payload.QuotationCodeTable.Data : []
return selectSearchHits(rows, text, markets, MAX_SEARCH_RESULTS)
},
// stock/get is one symbol per call. The batch ulist endpoint was resetting
// the connection, so a failed call can still fall through to the next source.
async quotes(items, fetchImpl) {
const results = await mapPool(items, 4, async (item) => {
const url = `https://push2delay.eastmoney.com/api/qt/stock/get?secid=${encodeURIComponent(item.symbol)}&invt=2&fltt=2&fields=f43,f44,f45,f46,f47,f48,f57,f58,f60,f86,f162,f168,f169,f170`
try {
const parsed = parseEastMoneyQuotes(await fetchImpl(url))
const quote = parsed[0]
if (!quote || !(quote.price > 0)) return null
return {
...quote,
symbol: item.symbol,
currency: quote.currency || currencyForMarket(item.market)
}
} catch (err) {
return { error: err }
}
})
const quotes = results.filter((quote) => quote && quote.price > 0)
if (quotes.length) return quotes
const failure = results.find((quote) => quote && quote.error)
throw (failure && failure.error) || new Error("eastmoney quote failed")
}
},
tencent: {
id: "tencent",
labelKey: "source_tencent",
markets: ["a", "hk", "us"],
symbolFor(instrument) {
if (instrument.market === "a") {
const prefix = instrument.quoteId.startsWith("0.") || /^[03]/.test(instrument.code) ? "sz" : "sh"
return `${prefix}${instrument.code}`
}
if (instrument.market === "hk") return `hk${instrument.code}`
if (instrument.market === "us") return `us${instrument.code}`
return ""
},
pageUrl(instrument) {
return `https://gu.qq.com/${this.symbolFor(instrument)}`
},
async quotes(items, fetchImpl) {
const url = `https://qt.gtimg.cn/q=${items.map((item) => item.symbol).join(",")}`
const parsed = parseTencentQuotes(await fetchImpl(url))
const bySymbol = new Map(parsed.map((quote) => [quote.symbol.toLowerCase(), quote]))
return items.map((item) => bySymbol.get(item.symbol.toLowerCase())).filter(Boolean)
}
},
yahoo: {
id: "yahoo",
labelKey: "source_yahoo",
markets: ["us", "hk", "a"],
symbolFor(instrument) {
if (instrument.market === "us") return instrument.code
if (instrument.market === "hk") return `${String(Number(instrument.code)).padStart(4, "0")}.HK`
if (instrument.market === "a") return `${instrument.code}.${instrument.quoteId.startsWith("0.") || /^[03]/.test(instrument.code) ? "SZ" : "SS"}`
return ""
},
pageUrl(instrument) {
return `https://finance.yahoo.com/quote/${encodeURIComponent(this.symbolFor(instrument))}`
},
async search(text, markets, fetchImpl) {
const url = `https://query1.finance.yahoo.com/v1/finance/search?q=${encodeURIComponent(text)}&quotesCount=10&newsCount=0&enableFuzzyQuery=false`
const payload = JSON.parse(await fetchImpl(url))
const hits = asArray(payload && payload.quotes).map(yahooSearchHit).map(normalizeInstrument).filter(Boolean)
const allowed = new Set(markets)
return hits.filter((hit) => allowed.has(hit.market)).slice(0, MAX_SEARCH_RESULTS)
},
async quotes(items, fetchImpl) {
const results = await mapPool(items, 4, async (item) => {
const url = `https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(item.symbol)}?interval=1d&range=1d&includePrePost=true`
try {
const quote = parseYahooChart(await fetchImpl(url), item.symbol)
return quote.price > 0 ? quote : null
} catch (err) {
return { error: err }
}
})
const quotes = results.filter((quote) => quote && quote.price > 0)
if (quotes.length) return quotes
const failure = results.find((quote) => quote && quote.error)
throw (failure && failure.error) || new Error("yahoo quote failed")
}
}
}
async function mapPool(items, limit, worker) {
const output = new Array(items.length)
let cursor = 0
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (cursor < items.length) {
const index = cursor
cursor += 1
output[index] = await worker(items[index], index)
}
})
await Promise.all(runners)
return output
}
// quotesWithFallback prices each instrument with that market's source list.
// A source is skipped when it has no symbol, throws, or omits the symbol.
function quotesWithFallback(instruments, options) {
const resolved = new Map()
const groups = new Map()
for (const instrument of instruments) {
const list = groups.get(instrument.market) || []
list.push(instrument)
groups.set(instrument.market, list)
}
const jobs = []
for (const [market, items] of groups) {
jobs.push(fillMarketQuotes(market, items, resolved, options))
}
return Promise.all(jobs).then(() => instruments.map((instrument) => resolved.get(instrumentKey(instrument)) || null))
}
async function fillMarketQuotes(market, items, resolved, options) {
let rest = items.slice()
for (const providerId of options.order[market] || []) {
if (!rest.length) break
const provider = options.providers[providerId]
if (!provider || typeof provider.quotes !== "function" || !provider.markets.includes(market)) continue
const fetchItems = []
const skipped = []
for (const instrument of rest) {
const symbol = provider.symbolFor(instrument)
if (!symbol) {
skipped.push(instrument)
continue
}
const cached = options.cache.get(quoteCacheKey(providerId, symbol), options.now)
if (cached) {
resolved.set(instrumentKey(instrument), cached)
continue
}
fetchItems.push({ instrument, symbol })
}
rest = skipped
if (!fetchItems.length) continue
try {
const quotes = await provider.quotes(fetchItems.map((row) => ({ ...row.instrument, symbol: row.symbol })), options.fetchImpl)
const bySymbol = new Map()
for (const quote of quotes) {
if (quote && quote.symbol && quote.price > 0) bySymbol.set(quote.symbol, quote)
}
const missed = []
for (const row of fetchItems) {
const quote = bySymbol.get(row.symbol)
if (!quote) {
missed.push(row.instrument)
continue
}
const stored = {
...quote,
providerId,
symbol: row.symbol,
market: row.instrument.market,
quoteId: row.instrument.quoteId || "",
code: row.instrument.code,
name: quote.name || row.instrument.name,
pageUrl: provider.pageUrl(row.instrument)
}
options.cache.set(quoteCacheKey(providerId, row.symbol), stored, options.now)
resolved.set(instrumentKey(row.instrument), stored)
}
rest = rest.concat(missed)
} catch (err) {
if (options.onError) options.onError(providerId, market, err)
rest = rest.concat(fetchItems.map((row) => row.instrument))
}
}
}
// searchWithFallback returns the first source that finds an A-share, Hong Kong,
// or US equity. An empty list tries the next source, because one feed can miss
// an English company name that another feed has. A thrown source is skipped too.
async function searchWithFallback(text, markets, options) {
const failures = []
for (const providerId of options.searchOrder) {
const provider = options.providers[providerId]
if (!provider || typeof provider.search !== "function") continue
const covered = markets.filter((market) => provider.markets.includes(market))
if (!covered.length) continue
const cacheKey = `search:${providerId}:${covered.join(",")}:${text.toLowerCase()}`
const cached = options.cache.get(cacheKey, options.now)
if (cached) return { providerId, instruments: cached.filter((item) => markets.includes(item.market)) }
try {
const instruments = (await provider.search(text, covered, options.fetchImpl) || []).map(normalizeInstrument).filter(Boolean)
if (!instruments.length) continue
options.cache.set(cacheKey, instruments, options.now)
return { providerId, instruments }
} catch (err) {
failures.push(`${providerId}: ${err && err.message ? err.message : err}`)
if (options.onError) options.onError(providerId, covered.join(","), err)
}
}
const inferred = inferInstrument(text)
if (inferred && markets.includes(inferred.market)) return { providerId: "symbol", instruments: [inferred] }
if (failures.length) throw new Error(failures.join("; "))
return { providerId: "", instruments: [] }
}
function primaryHotkey(key) {
return `${process.platform === "darwin" ? "cmd" : "ctrl"}+${key}`
}
const SORT_DEFAULT = "default"
const SORT_CHANGE_DESC = "desc"
const SORT_CHANGE_ASC = "asc"
function selectedSort(query) {
const refinements = (query && (query.Refinements || query.refinements)) || {}
const value = refinements.sort
return value === SORT_CHANGE_DESC || value === SORT_CHANGE_ASC ? value : SORT_DEFAULT
}
// orderQuoteRows keeps search or watchlist order unless the sort is by change percent.
// Quotes without a percent stay at the end.
function orderQuoteRows(instruments, quotes, sort) {
const rows = instruments.map((instrument, index) => ({ instrument, quote: quotes[index] || null, index }))
if (sort !== SORT_CHANGE_DESC && sort !== SORT_CHANGE_ASC) return rows
const direction = sort === SORT_CHANGE_ASC ? 1 : -1
rows.sort((left, right) => {
const leftPercent = left.quote && Number.isFinite(left.quote.changePercent) ? left.quote.changePercent : null
const rightPercent = right.quote && Number.isFinite(right.quote.changePercent) ? right.quote.changePercent : null
if (leftPercent === null && rightPercent === null) return left.index - right.index
if (leftPercent === null) return 1
if (rightPercent === null) return -1
if (leftPercent === rightPercent) return left.index - right.index
return (leftPercent - rightPercent) * direction
})
return rows
}
function marketsFor(selection) {
return selection === "all" ? MARKETS.slice() : [selection]
}
function queryText(query) {
return String((query && (query.Search || query.search)) || "").trim().slice(0, 40)
}
// parseExchangeTime reads a provider clock. Compact values are China exchange time.
// US strings without a zone are left unset so a wrong offset is not shown.
function parseExchangeTime(text, symbol) {
const compact = String(text || "").match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/)
if (compact) {
const [, year, month, day, hour, minute, second] = compact
const parsed = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}+08:00`)
return Number.isFinite(parsed) ? parsed / 1000 : 0
}
const dashed = String(text || "").match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/)
if (!dashed || String(symbol || "").toLowerCase().startsWith("us")) return 0
const [, year, month, day, hour, minute, second] = dashed
const parsed = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}+08:00`)
return Number.isFinite(parsed) ? parsed / 1000 : 0
}
function formatCount(template, count) {
return String(template || "").replaceAll("{n}", String(count))
}
// formatRelativeTime turns a quote timestamp into a short age such as "3 分钟前".
function formatRelativeTime(unixSeconds, nowMs, labels) {
if (!(unixSeconds > 0) || !(nowMs > 0)) return ""
const delta = Math.max(0, Math.floor(nowMs / 1000 - unixSeconds))
if (delta < 60) return labels.relative_now || ""
const minutes = Math.floor(delta / 60)
if (minutes < 60) return formatCount(minutes === 1 ? labels.relative_minute : labels.relative_minutes, minutes)
const hours = Math.floor(delta / 3600)
if (hours < 24) return formatCount(hours === 1 ? labels.relative_hour : labels.relative_hours, hours)
const days = Math.floor(delta / 86400)
return formatCount(days === 1 ? labels.relative_day : labels.relative_days, days)
}
const BADGE_GLYPHS = {
" ":{"w":3.2,"h":0,"y":0,"d":""},
"+":{"w":5.05,"y":6.14,"d":"M5.05 9.02L2.88 9.02L2.88 11.19L2.16 11.19L2.16 9.02L0 9.02L0 8.3L2.16 8.3L2.16 6.14L2.88 6.14L2.88 8.3L5.05 8.3Z"},
"-":{"w":2.93,"y":8.46,"d":"M2.93 9.15L0 9.15L0 8.46L2.93 8.46Z"},
"%":{"w":8.16,"y":4.05,"d":"M1.75 8.1L0.47 7.58L0.02 6.15L0.55 4.65L1.9 4.05L3.17 4.58L3.62 6L3.1 7.5L1.75 8.1ZM1.82 4.65L1.07 5.03L0.77 6.08L1.07 7.13L1.82 7.5L2.65 7.13L2.87 6.08L2.65 5.03L1.82 4.65ZM6.92 4.2L1.97 11.93L1.22 11.93L6.17 4.2ZM6.4 12L5.12 11.48L4.6 10.13L5.12 8.63L6.47 8.03L7.75 8.55L8.2 9.98L7.67 11.48L6.4 12ZM6.47 8.63L5.65 9L5.35 10.05L5.65 11.03L6.4 11.4L7.22 11.03L7.52 9.98L7.22 9L6.47 8.63Z"},
".":{"w":1.2,"y":10.78,"d":"M0.6 12L0.22 11.85L0 11.4L0.22 11.03L0.6 10.8L1.05 11.03L1.27 11.4L1.05 11.85L0.6 12Z"},
"0":{"w":5.02,"y":4.04,"d":"M5.09 8.03L4.86 9.75L4.34 11.03L3.59 11.78L2.46 12.08L1.41 11.78L0.66 11.03L0.21 9.83L0.06 8.18L0.21 6.45L0.74 5.1L1.49 4.35L2.61 4.05L3.66 4.28L4.49 5.03L4.94 6.3L5.09 8.03ZM4.11 8.1L3.74 5.63L2.61 4.8L1.34 5.63L0.96 8.18L1.34 10.58L2.54 11.33L3.74 10.5L4.11 8.1Z"},
"1":{"w":2.66,"y":4,"d":"M2.68 11.93L1.85 11.93L1.85 5.25L1.55 5.48L1.1 5.78L0.58 6L0.05 6.15L0.05 5.25L0.65 5.03L1.33 4.73L1.85 4.43L2.38 4.05L2.68 4.05Z"},
"2":{"w":4.75,"y":4.04,"d":"M3.61 6.23L3.46 5.63L3.16 5.18L2.71 4.88L2.19 4.8L1.66 4.88L1.21 5.1L0.76 5.4L0.31 5.78L0.31 4.8L1.14 4.28L2.26 4.05L3.16 4.2L3.84 4.58L4.29 5.25L4.51 6.15L4.36 6.98L4.06 7.65L3.54 8.33L2.79 8.93L1.89 9.6L1.29 10.05L1.06 10.58L0.99 11.1L4.81 11.1L4.81 11.93L0.01 11.93L0.01 11.55L0.16 10.65L0.46 9.98L1.14 9.3L2.11 8.47L2.79 7.95L3.31 7.35L3.54 6.83L3.61 6.23Z"},
"3":{"w":4.46,"y":4.04,"d":"M4.51 9.75L4.29 10.65L3.76 11.4L2.86 11.85L1.81 12.08L0.01 11.63L0.01 10.65L1.81 11.33L2.56 11.18L3.09 10.88L3.46 10.43L3.61 9.83L3.09 8.7L1.44 8.33L0.84 8.33L0.84 7.58L1.44 7.58L2.86 7.2L3.31 6.15L2.94 5.18L1.89 4.8L0.31 5.4L0.31 4.5L2.11 4.05L2.94 4.2L3.61 4.58L4.06 5.18L4.21 5.93L3.84 7.13L2.71 7.88L2.71 7.88L3.39 8.1L3.99 8.47L4.36 9L4.51 9.75Z"},
"4":{"w":5.48,"y":4.17,"d":"M4.5 4.2L4.5 9.3L5.55 9.3L5.55 10.13L4.5 10.13L4.5 11.93L3.67 11.93L3.67 10.13L0 10.13L0 9.3L1.05 8.1L2.02 6.83L2.92 5.48L3.6 4.2ZM1.05 9.3L3.67 9.3L3.67 5.55L2.92 6.75L2.17 7.8L1.57 8.63L1.05 9.3Z"},
"5":{"w":4.32,"y":4.17,"d":"M4.37 9.53L4.14 10.58L3.62 11.33L2.72 11.85L1.59 12.08L0.02 11.7L0.02 10.8L1.67 11.33L2.42 11.18L2.94 10.8L3.32 10.28L3.47 9.6L2.94 8.4L1.52 8.03L1.14 8.03L0.84 8.03L0.47 8.03L0.17 8.1L0.47 4.2L3.99 4.2L3.99 5.03L1.22 5.03L1.07 7.28L1.44 7.28L1.74 7.2L2.87 7.43L3.69 7.88L4.22 8.55L4.37 9.53Z"},
"6":{"w":4.89,"y":4.04,"d":"M4.95 9.45L4.73 10.5L4.2 11.33L3.45 11.85L2.48 12.08L1.5 11.78L0.68 11.1L0.23 9.98L0 8.55L0.23 6.68L0.9 5.33L1.88 4.43L3.15 4.05L4.43 4.28L4.43 5.1L3.23 4.8L2.25 5.03L1.58 5.7L1.13 6.75L0.98 8.03L0.98 8.03L1.65 7.35L2.7 7.05L3.6 7.28L4.35 7.73L4.8 8.47L4.95 9.45ZM4.05 9.6L3.9 8.85L3.6 8.33L3.15 7.95L2.55 7.8L1.95 7.95L1.43 8.33L1.13 8.78L0.98 9.38L1.13 10.13L1.43 10.73L1.95 11.18L2.55 11.33L3.15 11.18L3.6 10.8L3.9 10.28L4.05 9.6Z"},
"7":{"w":4.9,"y":4.17,"d":"M4.95 4.73L4.5 5.48L3.97 6.53L3.37 7.73L2.85 9.08L2.4 10.5L2.17 11.93L1.2 11.93L1.5 10.5L1.95 9.08L2.47 7.8L3.07 6.6L3.52 5.63L3.9 5.03L0 5.03L0 4.2L4.95 4.2Z"},
"8":{"w":5,"y":4.04,"d":"M0.04 9.75L0.12 9.15L0.42 8.55L0.87 8.1L1.47 7.73L0.64 6.98L0.34 6.08L0.57 5.25L1.02 4.65L1.69 4.2L2.52 4.05L3.42 4.2L4.09 4.65L4.54 5.25L4.69 6.08L4.39 6.98L3.64 7.73L4.24 8.1L4.69 8.55L4.92 9.15L5.07 9.75L4.84 10.65L4.32 11.4L3.57 11.85L2.52 12L1.54 11.85L0.72 11.4L0.19 10.65L0.04 9.75ZM1.02 9.68L1.09 10.35L1.39 10.8L1.92 11.18L2.52 11.25L3.19 11.1L3.64 10.8L3.94 10.35L4.09 9.68L4.02 9.08L3.64 8.55L3.19 8.25L2.52 8.1L1.92 8.25L1.47 8.55L1.09 9.08L1.02 9.68ZM1.24 6.08L1.39 6.6L1.62 7.05L2.07 7.28L2.52 7.43L3.04 7.28L3.42 7.05L3.72 6.6L3.79 6.08L3.72 5.63L3.42 5.18L3.04 4.95L2.52 4.8L1.99 4.95L1.62 5.18L1.39 5.63L1.24 6.08Z"},
"9":{"w":4.89,"y":4.04,"d":"M4.9 7.58L4.75 9.45L4.07 10.88L3.1 11.78L1.82 12.08L0.47 11.78L0.47 10.95L1.82 11.33L2.72 11.1L3.47 10.43L3.85 9.45L4 8.03L4 8.03L3.32 8.78L2.27 9.08L1.37 8.85L0.7 8.4L0.17 7.65L0.02 6.68L0.25 5.63L0.77 4.8L1.52 4.28L2.5 4.05L3.55 4.28L4.3 5.03L4.75 6.08L4.9 7.58ZM4 6.83L3.85 6L3.55 5.4L3.02 4.95L2.42 4.8L1.82 4.95L1.37 5.33L1.07 5.85L0.92 6.53L1.07 7.28L1.37 7.8L1.82 8.18L2.5 8.25L3.1 8.18L3.55 7.8L3.85 7.35L4 6.83Z"},
"P":{"w":4.71,"y":4.17,"d":"M0.94 9L0.94 11.93L0.04 11.93L0.04 4.2L2.14 4.2L4.09 4.8L4.77 6.53L4.02 8.33L1.92 9ZM0.94 5.03L0.94 8.18L1.92 8.18L3.34 7.73L3.79 6.53L3.34 5.4L1.99 5.03Z"},
"r":{"w":2.87,"y":6.27,"d":"M2.93 7.28L2.26 7.13L1.28 7.65L0.91 9.08L0.91 11.93L0.01 11.93L0.01 6.38L0.91 6.38L0.91 7.58L0.91 7.58L1.51 6.6L2.41 6.3L2.93 6.38Z"},
"e":{"w":4.8,"y":6.24,"d":"M4.81 9.38L0.98 9.38L1.43 10.8L2.71 11.33L4.43 10.65L4.43 11.48L2.56 12L0.68 11.25L0.01 9.15L0.76 7.05L2.56 6.3L4.21 6.98L4.81 8.93ZM3.91 8.63L3.53 7.43L2.56 7.05L1.51 7.5L0.98 8.63Z"},
"o":{"w":5.41,"y":6.24,"d":"M2.71 12L0.76 11.25L0.01 9.22L0.76 7.05L2.86 6.3L4.73 7.05L5.48 9.15L4.73 11.25L2.71 12ZM2.78 7.05L1.43 7.58L0.91 9.15L1.43 10.73L2.78 11.33L4.06 10.73L4.51 9.15L4.06 7.58L2.78 7.05Z"},
"s":{"w":3.65,"y":6.24,"d":"M0.04 11.7L0.04 10.73L1.62 11.33L2.52 11.1L2.82 10.5L2.67 10.13L2.44 9.9L1.99 9.68L1.54 9.45L0.87 9.15L0.42 8.85L0.12 8.4L0.04 7.88L0.19 7.2L0.72 6.68L1.39 6.38L2.14 6.3L3.42 6.53L3.42 7.43L2.07 7.05L1.62 7.05L1.24 7.2L1.02 7.5L0.94 7.8L1.02 8.18L1.24 8.4L1.62 8.63L2.14 8.78L2.74 9.08L3.27 9.45L3.57 9.83L3.72 10.43L3.49 11.18L3.04 11.63L2.29 11.93L1.54 12L0.04 11.7Z"},
"t":{"w":3.21,"y":4.74,"d":"M3.22 11.85L2.39 12L1.34 11.63L0.97 10.43L0.97 7.13L0.07 7.13L0.07 6.38L0.97 6.38L0.97 5.03L1.87 4.8L1.87 6.38L3.22 6.38L3.22 7.13L1.87 7.13L1.87 10.28L2.02 11.03L2.69 11.25L3.22 11.1Z"},
"盘":{"w":11.13,"y":2.22,"d":"M0.17 6L2.12 6L2.2 5.18L2.2 3.38L4.6 3.38L4.97 2.25L5.95 2.48L5.57 3.38L9.47 3.38L9.47 6L11.05 6L11.05 6.75L9.47 6.75L9.47 7.58L9.17 8.55L8.42 8.85L6.92 8.85L6.77 7.95L8.05 8.03L8.65 7.43L8.65 6.75L2.87 6.75L2.27 8.25L0.92 9.6L0.25 8.85L1.37 7.88L1.97 6.75L0.17 6.75ZM0.02 12.23L1.52 12.23L1.52 9.3L9.77 9.3L9.77 12.23L11.2 12.23L11.2 12.98L0.02 12.98ZM8.65 4.13L3.02 4.13L3.02 6L8.65 6ZM8.95 9.98L7.22 9.98L7.22 12.23L8.95 12.23ZM2.35 12.23L4 12.23L4 9.98L2.35 9.98ZM4.82 12.23L6.47 12.23L6.47 9.98L4.82 9.98ZM4.15 7.5L4.6 6.9L6.47 8.1L5.95 8.7L4.15 7.5ZM4.6 4.73L5.05 4.2L6.77 5.18L6.25 5.85L4.6 4.73Z"},
"前":{"w":11,"y":2.22,"d":"M1.6 13.43L0.78 13.43L0.78 5.93L5.73 5.93L5.73 12.23L5.43 13.05L4.6 13.28L3.25 13.28L3.1 12.45L4.38 12.53L4.83 12L4.83 10.58L1.6 10.58ZM0.03 4.05L3.7 4.05L2.73 2.78L3.4 2.25L4.53 3.68L4 4.05L7.08 4.05L6.63 3.83L7.68 2.25L8.5 2.78L7.45 4.05L11.06 4.05L11.06 4.8L0.03 4.8ZM9.33 5.55L10.23 5.55L10.23 11.85L9.93 12.9L8.95 13.28L7.45 13.28L7.3 12.3L8.65 12.38L9.33 11.63ZM7.08 6.08L7.9 6.08L7.9 11.18L7.08 11.18ZM4.83 6.68L1.6 6.68L1.6 7.88L4.83 7.88ZM1.6 9.83L4.83 9.83L4.83 8.63L1.6 8.63Z"},
"后":{"w":11.18,"y":2.62,"d":"M3.36 8.33L10.19 8.33L10.19 13.43L9.28 13.43L9.28 12.6L4.26 12.6L4.26 13.43L3.36 13.43ZM2.31 6.53L2.23 9.08L2.01 10.73L0.66 13.43L0.06 12.68L1.11 10.35L1.33 9L1.41 7.13L1.41 3.3L6.06 3.08L10.11 2.63L10.64 3.6L6.21 3.98L2.31 4.2L2.31 5.7L11.24 5.7L11.24 6.53ZM9.28 9.15L4.26 9.15L4.26 11.85L9.28 11.85Z"}
}
// sessionBadgeSVG matches a launcher text tail. Those tags are 22px tall,
// with an 8px inset on each side and a corner radius of half the height.
// The label is drawn as glyph paths so the inset stays 8px. A centered
// text label would add the icon's width again on the right.
function sessionBadgeSVG(session, text, change) {
const up = change > 0
const down = change < 0
const fill = up ? "#027A48" : down ? "#B42318" : "#00000000"
const stroke = up ? "#027A48" : down ? "#B42318" : "#FFFFFF33"
const label = up || down ? "#FFFFFF" : "#E5E7EB"
const side = 8
const iconWidth = 11
const gap = 2
const letters = []
let textWidth = 0
for (const char of text) {
const glyph = BADGE_GLYPHS[char]
if (!glyph) continue
letters.push({ glyph, x: textWidth })
textWidth += glyph.w + 0.45
}
if (textWidth > 0) textWidth -= 0.45
const width = Math.ceil(side + iconWidth + gap + textWidth + side)
const textX = side + iconWidth + gap
const iconPath = session === "pre" ? PRE_ICON_PATH : POST_ICON_PATH
const glyphs = letters.filter((item) => item.glyph.d).map((item) => `<path fill="${label}" transform="translate(${(textX + item.x).toFixed(2)} 4.2)" d="${item.glyph.d}"/>`).join("")
const markup = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="22" viewBox="0 0 ${width} 22"><rect x="0.5" y="0.5" width="${width - 1}" height="21" rx="10.5" fill="${fill}" stroke="${stroke}" stroke-width="1"/><path fill="#FFC043" transform="translate(${side} 5) scale(0.92)" d="${iconPath}"/>${glyphs}</svg>`
return { markup, width, height: 22 }
}
function formatFixed(value, digits) {
return Number.isFinite(value) ? value.toFixed(digits) : ""
}
function signedFixed(value, digits) {
const text = formatFixed(value, digits)
if (!text) return ""
return value > 0 ? `+${text}` : text
}
// logoIcon uses the public ticker image. Unknown symbols 404 and the row falls back.
function logoIcon(instrument) {
const symbol = PROVIDERS.yahoo.symbolFor(instrument)
if (!symbol) return null
return {
ImageType: "url",
ImageData: `https://financialmodelingprep.com/image-stock/${encodeURIComponent(symbol)}.png`
}
}
function quoteIcon(change) {
const svg = change > 0 ? PLUGIN_ICON_SVG : change < 0 ? DOWN_ICON_SVG : FLAT_ICON_SVG
return { ImageType: "svg", ImageData: svg }
}
function openExternal(target) {
if (process.platform === "win32") {
spawn("cmd", ["/c", "start", "", target], { detached: true, stdio: "ignore", windowsHide: true }).unref()
return
}
const command = process.platform === "darwin" ? "open" : "xdg-open"
spawn(command, [target], { detached: true, stdio: "ignore" }).unref()
}
function contextData(instrument) {
return {
quoteId: instrument.quoteId || "",
code: instrument.code || "",
name: instrument.name || "",
market: instrument.market || ""
}
}
class StockPlugin {
constructor(options = {}) {
this.api = null
this.watchlist = []
this.fetchImpl = options.fetchImpl || httpGet
this.now = options.now || (() => Date.now())
this.cache = options.cache || new TtlCache(QUOTE_TTL_MS)
this.providers = options.providers || PROVIDERS
this.order = options.order || MARKET_PROVIDER_ORDER
this.searchOrder = options.searchOrder || SEARCH_PROVIDER_ORDER
this.openExternal = options.openExternal || openExternal
this.failures = []
this.watchlistQuotes = new Map()
this.refreshTimer = null
this.refreshing = false
this.hostCtx = null
this.queryCtx = null
this.visibleResults = []
this.init = this.init.bind(this)
this.query = this.query.bind(this)
}
async init(ctx, params) {
this.api = params && params.API
this.hostCtx = ctx
await this.loadSettings(ctx)
if (this.api && typeof this.api.OnSettingChanged === "function") {
await this.api.OnSettingChanged(ctx, async (_ctx, key, value) => {
if (key !== SETTING_WATCHLIST) return
this.watchlist = normalizeWatchlist(value)
await this.refreshWatchlist()
})
}
if (this.api && typeof this.api.OnMRURestore === "function") {
await this.api.OnMRURestore(ctx, async (restoreCtx, mruData) => this.restoreResult(restoreCtx, mruData))
}
if (this.api && typeof this.api.OnUnload === "function") {
await this.api.OnUnload(ctx, async () => {
this.stopWatchlistRefresh()
})
}
await this.registerTools(ctx)
// Translated labels are remembered for MRU restore, which cannot wait on GetTranslation.
void this.labels(ctx)
this.startWatchlistRefresh()
}
async loadSettings(ctx) {
if (!this.api || typeof this.api.GetSetting !== "function") return
this.watchlist = normalizeWatchlist(await this.api.GetSetting(ctx, SETTING_WATCHLIST))
}
async translate(ctx, key) {
if (this.api && typeof this.api.GetTranslation === "function") {
try {
const value = await this.api.GetTranslation(ctx, key)
if (value && value !== key && !String(value).startsWith("i18n:")) return value
} catch {
// Older hosts or unit tests fall through to the header dictionary.
}
}
return (I18N.en_US && I18N.en_US[key]) || key
}
async labels(ctx) {
const keys = [
"sort", "sort_default", "sort_desc", "sort_asc", "market_a", "market_hk", "market_us",
"empty_watchlist_title", "empty_watchlist_sub", "empty_title", "empty_sub",
"error_title", "quote_unavailable",
"source_eastmoney", "source_tencent", "source_yahoo",
"relative_now", "relative_minute", "relative_minutes", "relative_hour", "relative_hours", "relative_day", "relative_days",
"session_pre", "session_post",
"notify_copied", "notify_added", "notify_removed", "notify_exists", "notify_full",
"notify_copy_failed", "notify_open_failed", "notify_save_failed"
]
const entries = await Promise.all(keys.map(async (key) => [key, await this.translate(ctx, key)]))
this.labelsCache = Object.fromEntries(entries)
return this.labelsCache
}
async notify(ctx, key) {
if (!this.api || typeof this.api.Notify !== "function") return
await this.api.Notify(ctx, await this.translate(ctx, key))
}
async log(ctx, level, message) {
if (this.api && typeof this.api.Log === "function") {
await this.api.Log(ctx, level, message)
}
}
quoteOptions() {
return {
providers: this.providers,
order: this.order,
cache: this.cache,
now: this.now(),
fetchImpl: this.fetchImpl,
onError: (providerId, market, err) => {
this.failures.push({ providerId, market, message: err && err.message ? err.message : String(err) })
}
}
}
async search(text, markets) {
return searchWithFallback(text, markets, {
...this.quoteOptions(),
searchOrder: this.searchOrder
})
}
async quotes(instruments) {
const quotes = await quotesWithFallback(instruments, this.quoteOptions())
await this.attachExtendedHours(instruments, quotes)
return quotes
}
// attachExtendedHours adds a US pre-market or after-hours print when the
// quote itself did not include one. Regular hours stay unchanged.
async attachExtendedHours(instruments, quotes) {
const pending = []
instruments.forEach((instrument, index) => {
const quote = quotes[index]
if (instrument.market === "us" && quote && quote.providerId !== "yahoo" && !quote.extended) pending.push({ instrument, index })
})
await mapPool(pending, 4, async (row) => {
const symbol = PROVIDERS.yahoo.symbolFor(row.instrument)
if (!symbol) return
try {
const url = `https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(symbol)}?interval=1d&range=1d&includePrePost=true`
const extended = extendedSession(JSON.parse(await this.fetchImpl(url)).chart.result[0].meta, this.now() / 1000)
if (extended) quotes[row.index].extended = extended
} catch {
// The regular quote still stands when the extended session is unavailable.
}
})
}
// startWatchlistRefresh prices the watchlist on a timer. Opening the watchlist
// only reads this snapshot, so a query does not wait on the network.
startWatchlistRefresh() {
this.stopWatchlistRefresh()
const tick = () => {
this.refreshWatchlist().catch(() => {})
}
tick()
this.refreshTimer = setInterval(tick, QUOTE_TTL_MS)
if (typeof this.refreshTimer.unref === "function") this.refreshTimer.unref()
}
stopWatchlistRefresh() {
if (!this.refreshTimer) return
clearInterval(this.refreshTimer)
this.refreshTimer = null
}
cachedWatchlistQuote(instrument) {
return this.watchlistQuotes.get(instrumentKey(instrument)) || null
}
// cachedQuote is the newest price already in memory. MRU restore must not
// call quotes(): a live fetch blocks the whole start page, and Wox discards
// a restore that takes longer than 300ms.
cachedQuote(instrument) {
const watched = this.cachedWatchlistQuote(instrument)
const priced = this.cachedProviderQuote(instrument)
if (watched && priced) return (priced.time || 0) >= (watched.time || 0) ? priced : watched
return priced || watched || null
}
// cachedProviderQuote reads the 60s quote cache filled by search. It does not fetch.
cachedProviderQuote(instrument) {
if (!instrument || !this.cache) return null
const order = (this.order && this.order[instrument.market]) || []
let found = null
for (const providerId of order) {
const provider = this.providers && this.providers[providerId]
if (!provider || typeof provider.symbolFor !== "function" || !provider.markets.includes(instrument.market)) continue
const symbol = provider.symbolFor(instrument)
if (!symbol) continue
const cached = this.cache.get(quoteCacheKey(providerId, symbol), this.now())
if (!cached) continue
if (!found || (cached.time || 0) > (found.time || 0)) found = cached
}
return found
}
async refreshWatchlist() {
if (this.refreshing) return
const items = this.watchlist.slice()
const live = new Set(items.map((item) => instrumentKey(item)))
if (!items.length) {
this.watchlistQuotes = new Map()
return
}
this.refreshing = true
try {
const quotes = await quotesWithFallback(items, {
...this.quoteOptions(),
cache: new TtlCache(QUOTE_TTL_MS)
})
await this.attachExtendedHours(items, quotes)
const next = new Map()
for (const [key, quote] of this.watchlistQuotes) {
if (live.has(key)) next.set(key, quote)
}
items.forEach((item, index) => {
if (quotes[index]) next.set(instrumentKey(item), quotes[index])
})
this.watchlistQuotes = next
await this.log(this.hostCtx, "Info", `watchlist refresh count=${items.length} priced=${quotes.filter(Boolean).length}`)
await this.publishVisibleQuotes()
} catch (err) {
await this.log(this.hostCtx, "Warning", `watchlist refresh failed: ${err && err.message ? err.message : err}`)
} finally {
this.refreshing = false
}
}
async persistWatchlist(ctx, next) {
const previous = this.watchlist
this.watchlist = next
if (!this.api || typeof this.api.SaveSetting !== "function") return true
try {
await this.api.SaveSetting(ctx, SETTING_WATCHLIST, JSON.stringify(next), false)
return true
} catch (err) {
this.watchlist = previous
await this.log(ctx, "Error", `watchlist save failed: ${err && err.message ? err.message : err}`)
await this.notify(ctx, "notify_save_failed")
return false
}
}
rememberVisibleResults(rows) {
this.visibleResults = rows.map((row) => ({
instrument: row.instrument,
quote: row.quote,
result: row.result
}))
}
async updateVisibleResult(ctx, instrument) {
const row = this.visibleResults.find((item) => sameInstrument(item.instrument, instrument))
if (!row) return
const labels = await this.labels(ctx)
const quote = this.cachedWatchlistQuote(instrument) || row.quote
const updated = this.quoteResult(instrument, quote, labels, row.result.Score)
updated.Id = row.result.Id
row.quote = quote
row.result = updated
await this.pushVisibleResult(ctx, updated)
}
async publishVisibleQuotes() {
const labels = await this.labels(this.queryCtx || this.hostCtx)
for (const row of this.visibleResults) {
if (!this.watchlist.some((item) => sameInstrument(item, row.instrument))) continue
const quote = this.cachedWatchlistQuote(row.instrument)
if (!quote) continue
const updated = this.quoteResult(row.instrument, quote, labels, row.result.Score)
updated.Id = row.result.Id
row.quote = quote
row.result = updated
await this.pushVisibleResult(this.queryCtx || this.hostCtx, updated)
}
}
async pushVisibleResult(ctx, result) {
if (!this.api || typeof this.api.UpdateResult !== "function") return
await this.api.UpdateResult(ctx, {
Id: result.Id,
Title: result.Title,
SubTitle: result.SubTitle,
Icon: result.Icon,
Tails: result.Tails,
Actions: result.Actions
})
}
async query(ctx, query) {
this.queryCtx = ctx
const labels = await this.labels(ctx)
const sort = selectedSort(query)
const text = queryText(query)
const refinement = this.sortRefinement(labels)
try {
const instruments = text
? (await this.search(text, MARKETS)).instruments
: this.watchlist.slice()
if (!instruments.length) {
this.visibleResults = []
return {
Results: [text ? this.emptyResult(labels) : this.emptyWatchlistResult(labels)],
Refinements: [refinement]
}
}
const quotes = text
? await this.quotes(instruments)
: instruments.map((item) => this.cachedWatchlistQuote(item))
const ordered = orderQuoteRows(instruments, quotes, sort)
const results = ordered.map((row, index) => this.quoteResult(row.instrument, row.quote, labels, 1000 - index))
this.rememberVisibleResults(ordered.map((row, index) => ({
instrument: row.instrument,
quote: row.quote,
result: results[index]
})))
const providers = [...new Set(quotes.filter(Boolean).map((quote) => quote.providerId))]
await this.log(ctx, "Info", `stock query text=${text || "-"} sort=${sort} results=${results.length} providers=${providers.join(",") || "-"} fallbacks=${this.failures.length}`)
this.failures = []
return { Results: results, Refinements: [refinement] }
} catch (err) {
this.visibleResults = []
await this.log(ctx, "Error", `stock query failed: ${err && err.message ? err.message : err}`)
return {
Results: [{
Title: "i18n:error_title",
SubTitle: err && err.message ? String(err.message).slice(0, 180) : "i18n:quote_unavailable",
Icon: quoteIcon(0),
Score: 1,
Actions: []
}],
Refinements: [refinement]
}
}
}
sortRefinement(labels) {
return {
Id: "sort",
Title: labels.sort,
Type: "sort",
Hotkey: primaryHotkey("s"),
DefaultValue: [SORT_DEFAULT],
Persist: false,
Options: [
{ Value: SORT_DEFAULT, Title: labels.sort_default },
{ Value: SORT_CHANGE_DESC, Title: labels.sort_desc },
{ Value: SORT_CHANGE_ASC, Title: labels.sort_asc }
]
}
}
emptyWatchlistResult(labels) {
return {
Title: "i18n:empty_watchlist_title",
SubTitle: labels.empty_watchlist_sub,
Icon: quoteIcon(0),
Score: 1,
Actions: []
}
}
emptyResult(labels) {
return {
Title: "i18n:empty_title",
SubTitle: labels.empty_sub,
Icon: quoteIcon(0),
Score: 1,
Actions: []
}
}
quoteResult(instrument, quote, labels, score) {
const context = contextData(instrument)
const key = instrumentKey(instrument).replace(/[^\w.-]+/g, "-")
const watched = this.watchlist.some((row) => sameInstrument(row, instrument))
const market = labels[`market_${instrument.market}`] || instrument.market
const source = quote ? (labels[PROVIDERS[quote.providerId].labelKey] || quote.providerId) : ""
const actions = [
watched
? this.removeAction({ id: `watch-${key}`, instrument, context })
: this.addAction({ id: `watch-${key}`, instrument, context })
]
if (quote) {
actions.push(this.copyAction({
id: `copy-price-${key}`,
name: "i18n:action_copy_price",
text: formatFixed(quote.price, 2),
context,
hotkey: primaryHotkey("enter")
}))
}
actions.push(this.copyAction({
id: `copy-code-${key}`,
name: "i18n:action_copy_code",
text: instrument.code,
context
}))
const pageUrl = (quote && quote.pageUrl) || this.providers.eastmoney.pageUrl(instrument)
if (pageUrl) {
actions.push(this.openAction({ id: `open-${key}`, url: pageUrl, context }))
}
const updated = quote ? formatRelativeTime(quote.time, this.now(), labels) : ""
const tails = []
if (quote) {
tails.push({ Type: "text", Text: formatFixed(quote.price, 2) })
const percent = signedFixed(quote.changePercent, 2)
if (percent) {
tails.push({
Type: "text",
Text: `${percent}%`,
TextCategory: quote.change > 0 ? "success" : quote.change < 0 ? "danger" : "default"
})
}
const extendedPercent = quote.extended ? signedFixed(quote.extended.changePercent, 2) : ""
if (extendedPercent) {
const session = quote.extended.session === "pre" ? labels.session_pre : labels.session_post
const badge = sessionBadgeSVG(quote.extended.session, `${session} ${extendedPercent}%`, quote.extended.change)
tails.push({
Type: "image",
Image: { ImageType: "svg", ImageData: badge.markup },
ImageWidth: badge.width,
ImageHeight: badge.height
})
}
}
return {
Id: `stock-${key}`,
Title: (quote && quote.name) || instrument.name || instrument.code,
SubTitle: [instrument.code, market, source || (quote ? "" : labels.quote_unavailable), updated].filter(Boolean).join(" · "),
Icon: logoIcon(instrument) || quoteIcon(quote ? quote.change : 0),
Score: score,
ScoreKey: `stock:${instrument.market}:${instrument.code}`,
Tails: tails,
Actions: actions
}
}
copyAction(item) {
return {
Id: item.id,
Name: item.name,
Icon: ACTION_COPY_ICON,
IsDefault: false,
Hotkey: item.hotkey || "",
ContextData: item.context,
Action: async (ctx) => {
try {
await this.api.Copy(ctx, { type: "text", text: item.text })
await this.notify(ctx, "notify_copied")
} catch (err) {
await this.log(ctx, "Error", `copy failed: ${err && err.message ? err.message : err}`)
await this.notify(ctx, "notify_copy_failed")
}
}
}
}
openAction(item) {
return {
Id: item.id,
Name: "i18n:action_open",
Icon: ACTION_OPEN_ICON,
IsDefault: false,
ContextData: item.context,
Action: async (ctx) => {
try {
this.openExternal(item.url)
} catch (err) {
await this.log(ctx, "Error", `open failed: ${err && err.message ? err.message : err}`)
await this.notify(ctx, "notify_open_failed")
}
}
}
}
addAction(item) {
return {
Id: item.id,
Name: "i18n:action_add",
Icon: ACTION_ADD_ICON,
IsDefault: true,
PreventHideAfterAction: true,
ContextData: item.context,
Action: async (ctx) => {
await this.addToWatchlist(ctx, item.instrument, true)
}
}
}
removeAction(item) {
return {
Id: item.id,
Name: "i18n:action_remove",
Icon: ACTION_DELETE_ICON,
IsDefault: true,
PreventHideAfterAction: true,
ContextData: item.context,
Action: async (ctx) => {
const result = removeWatchItem(this.watchlist, item.instrument)
if (!result.removed) return
const saved = await this.persistWatchlist(ctx, result.list)
if (!saved) return
await this.notify(ctx, "notify_removed")
await this.updateVisibleResult(ctx, item.instrument)
}
}
}
async addToWatchlist(ctx, raw, refresh) {
const result = addWatchItem(this.watchlist, raw)
if (!result.added) {
await this.notify(ctx, result.reason === "full" ? "notify_full" : "notify_exists")
return { added: false, reason: result.reason, instrument: result.item }
}
const saved = await this.persistWatchlist(ctx, result.list)
if (!saved) return { added: false, reason: "save", instrument: result.item }
await this.notify(ctx, "notify_added")
if (refresh) await this.updateVisibleResult(ctx, result.item)
return { added: true, reason: "added", instrument: result.item }
}
async restoreResult(_ctx, mruData) {
const data = (mruData && mruData.ContextData) || {}
const instrument = normalizeInstrument(data)
if (!instrument) return null
const quote = this.cachedQuote(instrument)
const labels = this.labelsCache || I18N.en_US || {}
return this.quoteResult({ ...instrument, name: (quote && quote.name) || instrument.name }, quote, labels, 100)
}
async registerTools(ctx) {
if (!this.api || typeof this.api.RegisterPluginTool !== "function") return
const tools = [
{
Name: "search_stocks",
Description: "i18n:tool_search",
InputSchema: {
type: "object",
properties: {
text: { type: "string" },
market: { type: "string", enum: ["all", "a", "hk", "us"] }
},
required: ["text"],
additionalProperties: false
},
OutputSchema: {
type: "object",
properties: {
providerId: { type: "string" },
instruments: { type: "array" }
},
required: ["providerId", "instruments"]
},
Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async (_ctx, option) => this.searchTool(option.Arguments || {})
},
{
Name: "get_quotes",
Description: "i18n:tool_quotes",
InputSchema: {
type: "object",
properties: {
instruments: {
type: "array",
items: {
type: "object",
properties: {
code: { type: "string" },
name: { type: "string" },
market: { type: "string", enum: ["a", "hk", "us"] },
quoteId: { type: "string" }
},
required: ["code", "market"]
}
}
},
required: ["instruments"],
additionalProperties: false
},
OutputSchema: {
type: "object",
properties: { quotes: { type: "array" } },
required: ["quotes"]
},
Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async (_ctx, option) => this.quotesTool(option.Arguments || {})
},
{
Name: "list_watchlist",
Description: "i18n:tool_list",
InputSchema: { type: "object", properties: {}, additionalProperties: false },
OutputSchema: {
type: "object",
properties: { instruments: { type: "array" } },
required: ["instruments"]
},
Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async () => ({ Output: { instruments: this.watchlist } })
},
{
Name: "add_watchlist",
Description: "i18n:tool_add",
InputSchema: {
type: "object",
properties: {
code: { type: "string" },
name: { type: "string" },
market: { type: "string", enum: ["a", "hk", "us"] },
quoteId: { type: "string" }
},
required: ["code", "market"],
additionalProperties: false
},
OutputSchema: {
type: "object",
properties: {
added: { type: "boolean" },
reason: { type: "string" }
},
required: ["added", "reason"]
},
Annotations: { ReadOnly: false, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async (toolCtx, option) => {
const result = await this.addToWatchlist(toolCtx, option.Arguments || {}, false)
return { Output: { added: result.added, reason: result.reason } }
}
},
{
Name: "remove_watchlist",
Description: "i18n:tool_remove",
InputSchema: {
type: "object",
properties: {
code: { type: "string" },
market: { type: "string" },
quoteId: { type: "string" }
},
additionalProperties: false
},
OutputSchema: {
type: "object",
properties: { removed: { type: "boolean" } },
required: ["removed"]
},
Annotations: { ReadOnly: false, Destructive: true, Idempotent: true, RequiresUI: false },
Handler: async (toolCtx, option) => {
const result = removeWatchItem(this.watchlist, option.Arguments || {})
if (result.removed) {
const saved = await this.persistWatchlist(toolCtx, result.list)
if (!saved) return { Error: { Code: "EXECUTION_FAILED", Message: "Could not save the watchlist" } }
}
return { Output: { removed: result.removed } }
}
}
]
for (const tool of tools) {
try {
const registered = await this.api.RegisterPluginTool(ctx, {
Tool: {
Name: tool.Name,
Description: tool.Description,
InputSchema: tool.InputSchema,
OutputSchema: tool.OutputSchema,
Annotations: tool.Annotations
},
Handler: tool.Handler
})
if (registered && registered.Error) {
await this.log(ctx, "Warning", `plugin tool ${tool.Name} was not registered: ${registered.Error.Message || registered.Error.Code}`)
}
} catch (err) {
await this.log(ctx, "Warning", `plugin tool ${tool.Name} unavailable: ${err && err.message ? err.message : err}`)
}
}
}
async searchTool(args) {
const text = String(args.text || "").trim()
if (!text) return { Error: { Code: "INVALID_ARGUMENTS", Message: "text is required" } }
const market = args.market || "all"
if (market !== "all" && !MARKETS.includes(market)) {
return { Error: { Code: "INVALID_ARGUMENTS", Message: "market must be all, a, hk, or us" } }
}
try {
const found = await this.search(text, marketsFor(market))
return { Output: { providerId: found.providerId, instruments: found.instruments } }
} catch (err) {
return { Error: { Code: "EXECUTION_FAILED", Message: err && err.message ? err.message : String(err) } }
}
}
async quotesTool(args) {
const instruments = (Array.isArray(args.instruments) ? args.instruments : []).map(normalizeInstrument).filter(Boolean).slice(0, 20)
if (!instruments.length) return { Error: { Code: "INVALID_ARGUMENTS", Message: "instruments must include code and market" } }
try {
const quotes = await this.quotes(instruments)
return {
Output: {
quotes: instruments.map((instrument, index) => {
const quote = quotes[index]
if (!quote) return { code: instrument.code, market: instrument.market, name: instrument.name, available: false }
return {
code: instrument.code,
market: instrument.market,
name: quote.name || instrument.name,
price: quote.price,
change: quote.change,
changePercent: quote.changePercent,
currency: quote.currency,
providerId: quote.providerId,
time: quote.time || 0,
available: true
}
})
}
}
} catch (err) {
return { Error: { Code: "EXECUTION_FAILED", Message: err && err.message ? err.message : String(err) } }
}
}
}
const plugin = new StockPlugin()
module.exports = {
plugin,
StockPlugin,
PROVIDERS,
MARKET_PROVIDER_ORDER,
SEARCH_PROVIDER_ORDER,
QUOTE_TTL_MS,
selectSearchHits,
inferInstrument,
normalizeInstrument,
normalizeWatchlist,
addWatchItem,
removeWatchItem,
parseEastMoneyQuotes,
parseTencentQuotes,
parseYahooChart,
yahooSearchHit,
quotesWithFallback,
searchWithFallback,
TtlCache,
logoIcon,
orderQuoteRows,
formatRelativeTime,
parseExchangeTime,
extendedSession,
sessionBadgeSVG,
I18N
}
@qianlifeng

Copy link
Copy Markdown
Author
logo image

@qianlifeng

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment