// ==UserScript== // @name Tokai Tokyo Trade Chart // @name:en Tokai Tokyo Trade Chart // @name:ja 東海東京証券 売買チャート // @name:zh-CN 东海东京证券 买卖点图表 // @namespace https://github.com/CheerChen // @version 0.1.0 // @description Add price charts with buy/sell points to the Tokai Tokyo Securities Online holdings page. // @description:en Add price charts with buy/sell points to the Tokai Tokyo Securities Online holdings page. // @description:ja 東海東京証券オンラインのお預り資産に、価格チャートと売買ポイントを表示します。 // @description:zh-CN 在东海东京证券网上交易的持仓资产页面显示价格走势图和买卖点。 // @author cheerchen37 // @match https://onlinetrade.tokaitokyo.co.jp/web/rmfAstAdpAdpLstSummaryAction.do* // @require https://cdn.jsdelivr.net/npm/lightweight-charts@5.3.0/dist/lightweight-charts.standalone.production.js#sha256=M4piXs5SxbhfsCbiItrV0PNl90UGCvv66WvakWNhQuk= // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @connect toushin-lib.fwg.ne.jp // @icon https://www.google.com/s2/favicons?sz=64&domain=onlinetrade.tokaitokyo.co.jp // @noframes // @run-at document-idle // @license MIT // @homepage https://github.com/CheerChen/userscripts // @supportURL https://github.com/CheerChen/userscripts/issues // @updateURL https://raw.githubusercontent.com/CheerChen/userscripts/master/tokaitokyo-trade-chart.user.js // ==/UserScript== /* global LightweightCharts */ (function () { 'use strict'; // The site never exposes ISIN or 投信協会コード, so each fund is linked to // the 投信総合検索ライブラリー once, by the user, and kept in GM storage. const LIB = 'https://toushin-lib.fwg.ne.jp/FdsWeb'; const NAV_CSV = ({ isin, assoc }) => `${LIB}/FDST030000/csv-file-download?isinCd=${isin}&associFundCd=${assoc}`; const SEARCH = `${LIB}/FDST999900/fundDataSearch`; const LINK_STORE = 'fundLinks:v1'; const TX_STORE = 'transactions:v1'; const NAV_TTL = 6 * 3600 * 1000; const COLORS = { line: '#2a6f97', buy: '#0a8f5a', sell: '#d9480f', cost: '#868e96', match: '#e7f5ff' }; const section = document.getElementById('domestic-trust'); if (!section) return; // ------------------------------------------------------------------ parsing // Names are compared without whitespace: the site mixes ASCII and // full-width spaces between the same names on different pages. const key = name => String(name).replace(/[\s\u3000]+/g, ''); function number(text) { const m = String(text).replace(/[,\s円]/g, '').match(/^(-)?(\d+(?:\.\d+)?)/); return m ? (m[1] ? -1 : 1) * Number(m[2]) : null; } function baseDate() { const m = document.body.textContent.match(/[(\d{4})\/(\d{2})\/(\d{2})基準]/); return m ? `${m[1]}-${m[2]}-${m[3]}` : null; } // 国内投信 table: one row pair per fund and 預り区分 (一般 / 特定 / NISA ...). function readHoldings() { const cell = (tr, id) => tr.querySelector(`td[headers="domestic-trust-${id}"]`); const funds = new Map(); const rows = [...section.querySelectorAll('table tbody tr')]; for (let i = 0; i < rows.length; i++) { const top = rows[i], nameCell = cell(top, 'th1'); if (!nameCell) continue; const bottom = rows[i + 1]; const name = [...nameCell.childNodes].filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent).join('').trim(); const qty = number(cell(top, 'th3')?.textContent); const cost = number(cell(top, 'th4-1')?.textContent); const price = number(bottom && cell(bottom, 'th4-2')?.textContent); const fund = funds.get(key(name)) || { name, qty: 0, costSum: 0, price }; if (qty && cost != null) { fund.qty += qty; fund.costSum += qty * cost; } funds.set(key(name), fund); } return [...funds.values()].map(f => ({ name: f.name, price: f.price, avgCost: f.qty ? f.costSum / f.qty : null })); } // Minimal CSV reader for the site's quoted export. // Fields never contain line breaks in this export. function parseCsv(text) { return text.split(/\r?\n/).map(line => { const cells = []; let cell = '', quoted = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (quoted) { if (c === '"' && line[i + 1] === '"') { cell += '"'; i++; } else if (c === '"') quoted = false; else cell += c; } else if (c === '"') quoted = true; else if (c === ',') { cells.push(cell); cell = ''; } else cell += c; } cells.push(cell); return cells; }); } // --------------------------------------------------------------- requests async function getDoc(url, init) { const res = await fetch(url, { credentials: 'same-origin', ...init }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return new DOMParser().parseFromString(await res.text(), 'text/html'); } // 取引履歴: search fund executions over the longest window the site // allows (two years), then read the search's CSV export, which holds all // rows at once instead of 40 per page. async function fetchTransactions() { const init = await getDoc('rmfAstTrhTrhLstInitAction.do'); const form = init.getElementById('rmfAstTrhTrhLstWebDto'); if (!form) throw new Error('取引履歴を開けません(ログイン切れの可能性)'); const fd = new FormData(form); const to = new Date(), from = new Date(to); from.setFullYear(to.getFullYear() - 2); from.setDate(from.getDate() + 1); const p2 = n => String(n).padStart(2, '0'); const select = (name, text) => { const option = [...form.querySelector(`select[name="${name}"]`).options].find(o => o.text.trim() === text); if (!option) throw new Error(`取引履歴の条件「${text}」が見つかりません`); return option.value; }; const radio = (name, label) => { const input = [...form.querySelectorAll(`input[name="${name}"]`)].find(i => form.querySelector(`label[for="${i.id}"]`)?.textContent.trim() === label); if (!input) throw new Error(`取引履歴の条件「${label}」が見つかりません`); return input.value; }; Object.entries({ knskYFrom: String(from.getFullYear()), knskMFrom: p2(from.getMonth() + 1), knskDFrom: p2(from.getDate()), knskYTo: String(to.getFullYear()), knskMTo: p2(to.getMonth() + 1), knskDTo: p2(to.getDate()), shuhnKbn: select('shuhnKbn', '投信'), trhkKbn1: radio('trhkKbn1', '約定'), }).forEach(([k, v]) => fd.set(k, v)); const result = await getDoc(form.getAttribute('action'), { method: 'POST', body: new URLSearchParams(fd) }); const csvLink = [...result.querySelectorAll('a[href]')].find(a => /CsvDownAction/.test(a.getAttribute('href'))); if (!csvLink) { if (/明細数:\s*0\s*件/.test(result.body.textContent)) return []; throw new Error('取引履歴を取得できません'); } const res = await fetch(csvLink.getAttribute('href'), { credentials: 'same-origin' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const rows = parseCsv(await res.text()); // The search-condition block above also starts with "約定日". const header = rows.findIndex(r => r[0] === '約定日' && r.includes('銘柄名') && r.includes('取引区分')); if (header < 0) throw new Error('取引履歴CSVの形式が想定と異なります'); const col = Object.fromEntries(rows[header].map((h, i) => [h, i])); return rows.slice(header + 1).filter(r => /^\d{4}\/\d{2}\/\d{2}$/.test(r[col['約定日']] || '')).map(r => ({ date: r[col['約定日']].replace(/\//g, '-'), name: r[col['銘柄名']], kind: r[col['取引区分']], account: r[col['預り区分']], qty: number(r[col['数量']]), price: number(r[col['単価']]), amount: number(r[col['受渡金額/決済損益']]), })); } function gmRequest(options) { return new Promise((resolve, reject) => GM_xmlhttpRequest({ timeout: 30000, ...options, onload: r => (r.status === 200 ? resolve(r) : reject(new Error(`HTTP ${r.status}`))), onerror: () => reject(new Error('network error')), ontimeout: () => reject(new Error('timeout')), })); } // Library name search (the same request its own search page sends). It // splits the keyword into terms, so the site's abbreviated name matches. async function searchFunds(keyword) { const r = await gmRequest({ method: 'POST', url: SEARCH, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: new URLSearchParams({ s_keyword: keyword, s_kensakuKbn: '1', startNo: '0', draw: '1', searchBtnClickFlg: 'true' }).toString(), }); const list = JSON.parse(r.responseText)?.searchResultInfo?.resultInfoMapList; if (!Array.isArray(list)) throw new Error('検索結果の形式が想定と異なります'); return list.map(f => ({ name: f.fundNm, isin: f.isinCd, assoc: f.associFundCd, nav: f.standardPrice == null ? null : Number(f.standardPrice), date: f.standardDate ? f.standardDate.slice(0, 10) : null, })); } // Rows look like "2026年01月05日,12345,6789,,". async function loadNav(link) { const cacheKey = `nav:${link.isin}:${link.assoc}`; const cached = GM_getValue(cacheKey, null); if (cached && Date.now() - cached.at < NAV_TTL) return { rows: cached.rows }; try { const r = await gmRequest({ method: 'GET', url: NAV_CSV(link), responseType: 'arraybuffer' }); const text = new TextDecoder('shift_jis').decode(r.response); const rows = [...text.matchAll(/^(\d{4})年(\d{2})月(\d{2})日,(\d+(?:\.\d+)?)/gm)] .map(m => ({ time: `${m[1]}-${m[2]}-${m[3]}`, value: Number(m[4]) })); if (!rows.length) throw new Error('empty CSV'); GM_setValue(cacheKey, { at: Date.now(), rows }); return { rows }; } catch (e) { if (cached) return { rows: cached.rows, warning: `基準価額の更新に失敗(${e.message})。前回のデータを表示しています` }; throw new Error(`基準価額を取得できません(${e.message})`); } } const links = () => GM_getValue(LINK_STORE, {}); function saveLink(name, link) { const all = links(); all[key(name)] = link; GM_setValue(LINK_STORE, all); } // The site shows two years of history; keep executed trades of held // funds so older points stay on the chart. function mergeTransactions(fresh, held) { const keyOf = t => [key(t.name), t.date, t.kind, t.account, t.qty, t.amount].join('|'); const keep = t => held.has(key(t.name)); const stored = Object.fromEntries(Object.entries(GM_getValue(TX_STORE, {})).filter(([, t]) => keep(t))); for (const t of fresh.filter(keep)) stored[keyOf(t)] = t; GM_setValue(TX_STORE, stored); return Object.values(stored).sort((a, b) => a.date.localeCompare(b.date)); } // ------------------------------------------------------------------ series function markOf(kind) { if (/売却|解約/.test(kind)) return 'S'; if (/再投/.test(kind)) return 'R'; if (/買付/.test(kind)) return 'B'; return null; } function eventsOf(trades) { const byDate = new Map(); for (const t of trades) { const mark = markOf(t.kind); if (!mark || !t.qty) continue; (byDate.get(t.date) || byDate.set(t.date, []).get(t.date)).push({ ...t, mark }); } return byDate; } function shiftDate(iso, days) { const d = new Date(iso + 'T00:00:00Z'); d.setUTCDate(d.getUTCDate() + days); return d.toISOString().slice(0, 10); } // --------------------------------------------------------------------- UI const yen = v => Math.round(v).toLocaleString('ja-JP'); function el(tag, style, text) { const node = document.createElement(tag); if (style) node.style.cssText = style; if (text != null) node.textContent = text; return node; } function message(parent, text, color = '#c92a2a') { const node = el('div', `color:${color};margin:4px 0;`, text); node.dataset.ttTradeChart = 'message'; parent.append(node); return node; } const BUTTON = 'padding:2px 10px;border:1px solid #ced4da;border-radius:3px;background:#fff;color:#333;font-size:12px;cursor:pointer;'; // One-time link to the library: search with the site's name, highlight // the candidate whose latest NAV equals the site's 参考時価, wait for a click. function setupPanel(body, fund, onLinked) { body.replaceChildren(); const box = el('div', 'border:1px solid #ddd;padding:10px;'); box.dataset.ttTradeChart = 'setup'; box.append(el('div', 'margin:0 0 6px;', '基準価額データの取得元(投信総合検索ライブラリー)を選んでください。')); const row = el('div', 'display:flex;gap:6px;margin:0 0 6px;'); const input = el('input', 'flex:1;padding:3px 6px;font-size:12px;'); input.type = 'search'; input.value = fund.name; input.setAttribute('aria-label', 'ファンド名で検索'); row.append(input); box.append(row); const status = el('div', 'color:#868e96;margin:4px 0;'); const list = el('div', ''); list.dataset.ttTradeChart = 'candidates'; box.append(status, list); let seq = 0, timer; const run = async () => { const mine = ++seq, keyword = input.value.trim(); if (!keyword) { list.replaceChildren(); status.textContent = ''; return; } status.textContent = '検索中…'; try { const found = await searchFunds(keyword); if (mine !== seq) return; const date = baseDate(); const matches = c => c.nav === fund.price && (!date || c.date === date); found.sort((a, b) => matches(b) - matches(a)); status.textContent = found.length ? '' : '該当するファンドがありません。キーワードを短くしてください。'; list.replaceChildren(...found.map(c => { const hit = matches(c); const item = el('button', `display:flex;justify-content:space-between;gap:12px;width:100%;text-align:left;padding:6px 8px;margin:2px 0;border:1px solid ${hit ? '#74c0fc' : '#e9ecef'};border-radius:3px;background:${hit ? COLORS.match : '#fff'};font-size:12px;cursor:pointer;`); item.type = 'button'; item.dataset.candidate = hit ? 'match' : 'other'; item.append(el('span', '', c.name), el('span', 'white-space:nowrap;color:#495057;', c.nav == null ? '--' : `${yen(c.nav)}円(${(c.date || '').replace(/-/g, '/')})${hit ? ' 参考時価と一致' : ''}`)); item.addEventListener('click', () => onLinked({ isin: c.isin, assoc: c.assoc, fundName: c.name })); return item; })); } catch (e) { if (mine === seq) status.textContent = `検索できません(${e.message})。下の欄に直接入力できます。`; } }; input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(run, 300); }); // Fallback if the library's search request ever changes. const manual = el('details', 'margin:8px 0 0;'); manual.append(el('summary', 'cursor:pointer;color:#495057;', 'ISIN・協会コードを直接入力')); const form = el('div', 'display:flex;gap:6px;margin:6px 0 0;'); const isin = el('input', 'width:140px;padding:3px 6px;font-size:12px;'); const assoc = el('input', 'width:110px;padding:3px 6px;font-size:12px;'); isin.placeholder = 'ISIN'; assoc.placeholder = '協会コード'; const save = el('button', BUTTON, '保存'); save.type = 'button'; save.addEventListener('click', () => { if (!/^[A-Z]{2}[0-9A-Z]{10}$/.test(isin.value.trim()) || !/^[0-9A-Z]{8}$/.test(assoc.value.trim())) { status.textContent = 'ISIN は12桁、協会コードは8桁で入力してください。'; return; } onLinked({ isin: isin.value.trim(), assoc: assoc.value.trim(), fundName: '' }); }); form.append(isin, assoc, save); manual.append(form); box.append(manual); body.append(box); run(); } function draw(holder, data, events, opts) { const LC = LightweightCharts; const chart = LC.createChart(holder, { autoSize: true, layout: { background: { color: '#ffffff' }, textColor: '#333', fontSize: 11 }, grid: { vertLines: { color: '#f1f3f5' }, horzLines: { color: '#f1f3f5' } }, rightPriceScale: { borderColor: '#ddd' }, timeScale: { borderColor: '#ddd' }, localization: { locale: 'ja-JP', priceFormatter: yen, dateFormat: 'yyyy/MM/dd' }, crosshair: { mode: LC.CrosshairMode.Normal }, }); const series = chart.addSeries(LC.LineSeries, { color: COLORS.line, lineWidth: 2, priceLineVisible: false }); series.setData(data); const times = new Set(data.map(d => d.time)); const markers = []; for (const [time, list] of [...events].sort((a, b) => a[0].localeCompare(b[0]))) { if (!times.has(time)) continue; if (list.some(t => t.mark === 'B')) markers.push({ time, position: 'belowBar', shape: 'arrowUp', color: COLORS.buy, text: 'B', size: 2 }); if (list.some(t => t.mark === 'S')) markers.push({ time, position: 'aboveBar', shape: 'arrowDown', color: COLORS.sell, text: 'S', size: 2 }); } LC.createSeriesMarkers(series, markers); // Summary for regression tests; values only, no trade details. Object.assign(opts.panel.dataset, { points: data.length, buys: markers.filter(m => m.text === 'B').length, sells: markers.filter(m => m.text === 'S').length, lastTime: data[data.length - 1]?.time || '', lastValue: data[data.length - 1]?.value ?? '', }); if (opts.costLine) { series.createPriceLine({ price: opts.costLine, color: COLORS.cost, lineWidth: 1, lineStyle: LC.LineStyle.Dashed, axisLabelVisible: true, title: '取得コスト' }); } const timeScale = chart.timeScale(); const firstEvent = [...events.keys()].sort()[0]; const resetView = () => { if (firstEvent && data.length) timeScale.setVisibleRange({ from: shiftDate(firstEvent, -45), to: data[data.length - 1].time }); else timeScale.fitContent(); }; resetView(); // Zoom keeps the right edge fixed, like the wheel zoom near the latest bar. const zoom = factor => { const range = timeScale.getVisibleLogicalRange(); if (!range) return; const span = Math.min(Math.max((range.to - range.from) * factor, 10), data.length * 1.1); timeScale.setVisibleLogicalRange({ from: range.to - span, to: range.to }); }; const tools = el('div', 'position:absolute;right:62px;top:6px;z-index:4;display:flex;gap:2px;'); for (const [text, label, action] of [['-', '縮小', () => zoom(1.5)], ['+', '拡大', () => zoom(1 / 1.5)], ['↺', 'リセット', resetView]]) { const button = el('button', 'width:24px;height:22px;padding:0;border:1px solid #ced4da;border-radius:3px;background:#fff;color:#333;font-size:13px;line-height:20px;cursor:pointer;', text); button.type = 'button'; button.title = label; button.setAttribute('aria-label', label); button.dataset.zoom = label; button.addEventListener('click', action); tools.append(button); } holder.append(tools); timeScale.subscribeVisibleLogicalRangeChange(range => { if (range) opts.panel.dataset.span = (range.to - range.from).toFixed(1); }); const tip = el('div', 'position:absolute;left:6px;top:6px;z-index:3;pointer-events:none;background:rgba(255,255,255,.92);border:1px solid #ddd;padding:4px 6px;line-height:1.5;display:none;'); holder.append(tip); chart.subscribeCrosshairMove(param => { const point = param.time && param.seriesData.get(series); if (!point) { tip.style.display = 'none'; return; } tip.replaceChildren(el('div', 'font-weight:bold;', `${String(param.time).replace(/-/g, '/')} ${yen(point.value)}円`)); for (const t of events.get(param.time) || []) { const color = t.mark === 'B' ? COLORS.buy : t.mark === 'S' ? COLORS.sell : '#495057'; const label = t.mark === 'R' ? '' : `${t.mark} `; tip.append(el('div', `color:${color};`, `${label}${t.kind} ${t.account || ''} ${yen(t.qty)}口 @${yen(t.price)} ${yen(t.amount)}円`)); } tip.style.display = 'block'; }); return chart; } // ------------------------------------------------------------------- main function panelFor(root, fund) { const panel = el('div', 'margin:8px 0 16px;'); panel.dataset.ttTradeChart = 'panel'; panel.dataset.fund = key(fund.name); const head = el('div', 'display:flex;align-items:center;gap:8px;margin:0 0 4px;'); head.append(el('span', 'font-weight:bold;', fund.name)); const body = el('div', ''); panel.append(head, body); root.append(panel); return { panel, head, body }; } async function renderFund(root, fund, tradesReady) { const { panel, head, body } = panelFor(root, fund); const change = el('button', BUTTON, '変更'); change.type = 'button'; change.dataset.ttTradeChart = 'change'; change.style.display = 'none'; head.append(change); let chart = null; const dropChart = () => { chart?.remove(); chart = null; }; const showChart = async link => { dropChart(); change.style.display = ''; panel.dataset.state = 'loading'; body.replaceChildren(el('div', 'color:#868e96;', '読み込み中…')); try { const [nav, trades] = await Promise.all([loadNav(link), tradesReady]); body.replaceChildren(); if (nav.warning) message(body, nav.warning, '#e67700'); const date = baseDate(); // A wrong pick shows up here: the site prices at NAV, so the // library's value on the site's base date must be the same. const onBase = date && nav.rows.find(r => r.time === date); if (onBase && fund.price != null && onBase.value !== fund.price) { message(body, `選択したファンドの基準価額(${yen(onBase.value)}円)が参考時価(${yen(fund.price)}円)と一致しません。「変更」で選び直してください。`, '#e67700'); } const holder = el('div', 'position:relative;width:100%;height:320px;border:1px solid #ddd;'); body.append(holder); chart = draw(holder, nav.rows, eventsOf(trades.filter(t => key(t.name) === key(fund.name))), { costLine: fund.avgCost, panel }); panel.dataset.state = 'ready'; } catch (e) { body.replaceChildren(); message(body, e.message); panel.dataset.state = 'error'; } }; const setup = () => { dropChart(); change.style.display = 'none'; panel.dataset.state = 'setup'; setupPanel(body, fund, link => { saveLink(fund.name, link); showChart(link); }); }; change.addEventListener('click', setup); const link = links()[key(fund.name)]; if (link) showChart(link); else setup(); } function main() { const root = el('div', 'margin:12px 0 4px;font-size:12px;'); root.dataset.ttTradeChart = 'root'; section.append(root); if (typeof LightweightCharts === 'undefined') { message(root, 'チャートライブラリを読み込めませんでした'); root.dataset.ttTradeChartState = 'error'; return; } const holdings = readHoldings(); if (!holdings.length) { root.dataset.ttTradeChartState = 'ready'; return; } const held = new Set(holdings.map(h => key(h.name))); const tradesReady = fetchTransactions().then( fresh => mergeTransactions(fresh, held), e => { message(root, `取引履歴の取得に失敗しました:${e.message}。保存済みの売買ポイントのみ表示します`); return mergeTransactions([], held); }); for (const fund of holdings) renderFund(root, fund, tradesReady); root.dataset.ttTradeChartState = 'ready'; } try { main(); } catch (e) { console.error('[Tokai Tokyo Trade Chart]', e); } })();