// ==UserScript== // @name JIS DC Trade Chart // @name:en JIS DC Trade Chart // @name:ja JIS 確定拠出年金 売買チャート // @name:zh-CN JIS 企业年金买卖点图表 // @namespace https://github.com/CheerChen // @version 0.1.1 // @description Add price charts with buy/sell points to the JIS&T defined-contribution pension profit and loss page. // @description:en Add price charts with buy/sell points to the JIS&T defined-contribution pension profit and loss page. // @description:ja JIS&T 確定拠出年金の評価損益照会に、基準価額チャートと売買ポイントを表示します。 // @description:zh-CN 在 JIS&T 企业年金(确定缴费)的评价损益页面显示价格走势图和买卖点。 // @author cheerchen37 // @match https://www.jis-t.ne.jp/dczws000/o3w* // @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=www.jis-t.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/jis-dc-trade-chart.user.js // ==/UserScript== /* global LightweightCharts */ (function () { 'use strict'; // JIS&T product code (as in the holdings link) -> [ISIN, 投信協会コード, // 信託財産留保額 rate if any]. Daily NAV comes from the 投信総合検索ライブラリー // CSV for that fund. Pairs were matched by NAV and day change against the // library and checked against the site's latest NAV. For funds with a // 留保額 the site shows NAV - floor(NAV * rate); the chart keeps plain NAV, // so S points sit slightly below the line. const FUNDS = { '00002800': ['JP90C00022W4', '0231104B'], // 年金インデックスファンド日本株式(TOPIX連動型) '00000640': ['JP90C0000367', '64311024', 0.002], // DC日本株式インデックスファンドL '00001351': ['JP90C00035B0', '32311984'], // フィデリティ・日本成長株・ファンド '00001350': ['JP90C00003C6', '64313031'], // DC日本株式エクセレント・フォーカス '00002066': ['JP90C00079W4', '6431210A'], // インデックスコレクション(国内債券) '00000770': ['JP90C00011E5', '03311022'], // 三菱UFJ DC国内債券インデックスファンド '00000647': ['JP90C0002Z87', '01312022'], // 野村外国株式インデックスファンド・MSCI-KOKUSAI(確定拠出年金向け) '00005092': ['JP90C000R3N8', '64312249'], // DC全世界株式インデックスファンド(オール・カントリー) '00004683': ['JP90C000M6Q9', '32314217'], // フィデリティ・世界割安成長株投信(確定拠出年金向け) '00002068': ['JP90C00079P8', '6431410A'], // インデックスコレクション(外国債券) '00000934': ['JP90C0000KL7', '79312024'], // 三井住友・DC外国債券インデックスファンド '00002009': ['JP90C0006N12', '0331109C'], // 三菱UFJ DC新興国株式インデックスファンド '00001940': ['JP90C0005SE4', '01317087'], // 野村新興国債券インデックスファンド(確定拠出年金向け) '00002917': ['JP90C000E412', '2931416A'], // DCニッセイJ-REITインデックスファンドB '00003151': ['JP90C000CMM0', '4731D15C'], // たわらノーロード先進国リート '00002070': ['JP90C00079T0', '6431510A'], // インデックスコレクション(バランス株式30) '00002071': ['JP90C00079V6', '6431610A'], // インデックスコレクション(バランス株式50) '00002069': ['JP90C00079X2', '6431710A'], // インデックスコレクション(バランス株式70) '00002160': ['JP90C0009038', '64312133'], // 分散投資コア戦略ファンドA '00002161': ['JP90C0009046', '64313133'], // 分散投資コア戦略ファンドS '00004901': ['JP90C000QA84', '64317241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2035 '00004902': ['JP90C000QBY8', '64318241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2040 '00004903': ['JP90C000QAN3', '64311241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2045 '00004904': ['JP90C000QAP8', '64312241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2050 '00004905': ['JP90C000QAQ6', '64313241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2055 '00004906': ['JP90C000QAW4', '64314241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2060 '00004907': ['JP90C000QAX2', '64315241'], // DCターゲット・イヤーファンド(ライフステージ対応型)2065 }; const NAV_CSV = ([isin, assoc]) => `https://toushin-lib.fwg.ne.jp/FdsWeb/FDST030000/csv-file-download?isinCd=${isin}&associFundCd=${assoc}`; const ENDPOINT = '/dczws000/o3w'; const NAV_TTL = 6 * 3600 * 1000; const TX_STORE = 'transactions:v1'; const COLORS = { line: '#2a6f97', buy: '#0a8f5a', sell: '#d9480f', cost: '#868e96' }; if (pageId(document) !== 'DCCGW303') return; // ------------------------------------------------------------------ parsing function pageId(doc) { return doc.querySelector('input[name="_PageID"]')?.value || ''; } function cellText(td) { const copy = td.cloneNode(true); copy.querySelectorAll('.pc-hidden').forEach(el => el.remove()); // Fields inside a cell are separated only by
. copy.querySelectorAll('br').forEach(br => br.replaceWith(' ')); return copy.textContent.replace(/\s+/g, ' ').trim(); } function number(text) { const m = String(text).replace(/[,\s]/g, '').match(/^(▲|-)?(\d+(?:\.\d+)?)/); return m ? (m[1] ? -1 : 1) * Number(m[2]) : null; } function isoDate(text) { const m = String(text).match(/(\d{4})\/(\d{2})\/(\d{2})/); return m ? `${m[1]}-${m[2]}-${m[3]}` : null; } // Holdings table under 商品別評価損益. function readHoldings() { const header = [...document.querySelectorAll('td.sub-title')].find(td => td.textContent.trim() === '商品別評価損益'); const table = header?.closest('table')?.nextElementSibling; if (!table || table.tagName !== 'TABLE') throw new Error('商品別評価損益の表が見つかりません'); const holdings = [...table.querySelectorAll('tr')].slice(1).map(tr => { const tds = [...tr.children]; const link = tr.querySelector('a[onclick*="sendFormSubWin305_02"]'); const args = link?.getAttribute('onclick').match(/'(\d+)','(\d+)'/); return { no: cellText(tds[0]), name: cellText(tds[1]), value: number(cellText(tds[3])), cost: number(cellText(tds[4])), kindPrdct: args?.[1], codePrdct: args?.[2], }; }).filter(h => h.no); return { table, holdings }; } // 取引履歴照会: each trade is a pair of rows (radius-start / radius-end). function parseTransactions(doc) { return [...doc.querySelectorAll('tr.radius-start-important')].map(top => { const bottom = top.nextElementSibling; const a = [...top.children].map(cellText); const b = [...(bottom?.children || [])].map(cellText); const dates = a[0].split(' '); const words = a[1].split(' '); return { orderDate: isoDate(dates[0] || ''), date: isoDate(dates[1] || ''), kind: words.length >= 3 ? words[0] : '', side: words.length >= 3 ? words[1] : words[0], status: words[words.length - 1], no: a[2], name: a[3], qty: number(b[0]), price: number(b[1]), amount: number(b[3]), }; }).filter(t => t.date && t.no); } // --------------------------------------------------------------- requests async function post(formData) { const res = await fetch(ENDPOINT, { method: 'POST', body: new URLSearchParams(formData), credentials: 'same-origin' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const html = new TextDecoder('shift_jis').decode(await res.arrayBuffer()); return new DOMParser().parseFromString(html, 'text/html'); } function expectPage(doc, id, what) { if (pageId(doc) !== id) throw new Error(`${what}を取得できません(セッション切れの可能性)`); return doc; } // Same request the left menu sends; reading it in the background leaves // the visible page's session usable. async function fetchTransactions() { const menu = new FormData(document.forms.FORM_MENU); Object.entries({ _ControlID: 'DCACW000Control', _PageID: 'DCAGW308', _ActionID: 'goDCDGW301', EVENT: 'DCWGA201-03', MENUNO: '01', MAINMENU: '01', LEFTMENU: '13', }).forEach(([k, v]) => menu.set(k, v)); const first = expectPage(await post(menu), 'DCDGW301', '取引履歴'); const form = first.forms.FORM_301_01; const months = [...form.FYM.options].map(o => o.value).filter(v => v !== '000000'); const range = new FormData(form); range.set('FYM', months[0]); range.set('TYM', months[months.length - 1]); range.set('SORT', '1'); return parseTransactions(expectPage(await post(range), 'DCDGW301', '取引履歴')); } // 商品別評価損益推移 (the product popup) carries the average cost. async function fetchFundDetail(holding) { const fd = new FormData(document.forms.formDCCGW303); fd.set('kindPrdct', holding.kindPrdct); fd.set('codePrdctTreat', holding.codePrdct); fd.set('EVENT', 'DCWGC305-02'); fd.set('_ActionID', 'goDCCGW305'); const doc = expectPage(await post(fd), 'DCCGW305', '商品別詳細'); const text = doc.body.textContent.replace(/\s+/g, ''); return { avgCost: number(text.match(/平均取得単価([\d,.]+)円/)?.[1] || '') }; } // The library serves Shift_JIS text; decode the bytes ourselves. function gmGet(url) { return new Promise((resolve, reject) => GM_xmlhttpRequest({ method: 'GET', url, timeout: 30000, responseType: 'arraybuffer', onload: r => (r.status === 200 ? resolve(new TextDecoder('shift_jis').decode(r.response)) : reject(new Error(`HTTP ${r.status}`))), onerror: () => reject(new Error('network error')), ontimeout: () => reject(new Error('timeout')), })); } // Rows look like "2026年01月05日,12345,6789,,". async function loadNav(code) { const key = 'nav:' + code; const cached = GM_getValue(key, null); if (cached && Date.now() - cached.at < NAV_TTL) return { rows: cached.rows }; try { const rows = [...(await gmGet(NAV_CSV(FUNDS[code]))).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(key, { at: Date.now(), rows }); return { rows }; } catch (e) { if (cached) return { rows: cached.rows, warning: `基準価額の更新に失敗(${e.message})。前回のデータを表示しています` }; throw new Error(`基準価額を取得できません(${e.message})`); } } // The site only shows one year of history; keep settled trades so older // points stay on the chart. function mergeTransactions(fresh, numbers) { const keyOf = t => [t.no, t.date, t.kind, t.side, t.qty, t.amount].join('|'); const charted = t => numbers.has(t.no); const stored = Object.fromEntries(Object.entries(GM_getValue(TX_STORE, {})).filter(([, t]) => charted(t))); fresh = fresh.filter(charted); for (const t of fresh) if (t.status === '約定済') stored[keyOf(t)] = t; GM_setValue(TX_STORE, stored); const all = new Map(Object.entries(stored)); for (const t of fresh) if (t.status !== '約定済') all.set(keyOf(t), t); return [...all.values()].sort((x, y) => x.date.localeCompare(y.date)); } // ------------------------------------------------------------------ series function fundSeries(nav, trades) { const byDate = new Map(); for (const t of trades) { const side = t.side === '購入' ? 'B' : t.side === '売却' ? 'S' : null; if (!side || !t.qty) continue; (byDate.get(t.date) || byDate.set(t.date, []).get(t.date)).push({ ...t, mark: side }); } return { data: nav, events: 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 buildSection(anchorTable) { const root = el('div', 'width:590px;margin:12px 0 4px;font-size:12px;'); root.dataset.jisTradeChart = 'root'; anchorTable.after(root); return root; } function addPanel(root, title, code) { const panel = el('div', 'margin:8px 0 14px;'); panel.dataset.jisTradeChart = 'panel'; panel.dataset.code = code; panel.append(el('div', 'font-weight:bold;margin:0 0 4px;', title)); const holder = el('div', 'position:relative;width:590px;height:300px;border:1px solid #ddd;'); panel.append(holder); root.append(panel); return { panel, holder }; } function message(root, text, color = '#c92a2a') { const node = el('div', `color:${color};margin:4px 0;`, text); node.dataset.jisTradeChart = 'message'; root.append(node); } 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; for (const mark of ['B', 'S']) { if (!list.some(t => t.mark === mark)) continue; markers.push(mark === 'B' ? { time, position: 'belowBar', shape: 'arrowUp', color: COLORS.buy, text: 'B', size: 2 } : { 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(holder.parentElement.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) holder.parentElement.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)}円${opts.unit || ''}`)); for (const t of events.get(param.time) || []) { const color = t.mark === 'B' ? COLORS.buy : COLORS.sell; tip.append(el('div', `color:${color};`, `${t.mark} ${t.kind || t.side} ${yen(t.qty)}口 @${yen(t.price)} ${yen(t.amount)}円${t.status === '約定済' ? '' : '(' + t.status + ')'}`)); } tip.style.display = 'block'; }); return chart; } // ------------------------------------------------------------------- main async function main() { const { table, holdings } = readHoldings(); const root = buildSection(table); if (typeof LightweightCharts === 'undefined') { message(root, 'チャートライブラリを読み込めませんでした'); root.dataset.jisTradeChartState = 'error'; return; } const loading = el('div', 'color:#868e96;', '取引履歴を読み込み中…'); root.append(loading); // Funds only: the site shows 取得金額 for 投信/MMF and not for deposits. const funds = holdings.filter(h => h.codePrdct && h.cost != null); const mapped = funds.filter(h => FUNDS[h.codePrdct]); for (const h of funds) if (!FUNDS[h.codePrdct]) message(root, `${h.name}:日次の基準価額データに未対応です`, '#868e96'); if (!mapped.length) { loading.remove(); root.dataset.jisTradeChartState = 'ready'; return; } const navLoads = new Map(mapped.map(h => [h.codePrdct, loadNav(h.codePrdct)])); navLoads.forEach(p => p.catch(() => {})); let trades; try { trades = mergeTransactions(await fetchTransactions(), new Set(mapped.map(h => h.no))); } catch (e) { loading.remove(); message(root, `取引履歴の取得に失敗しました:${e.message}`); root.dataset.jisTradeChartState = 'error'; return; } loading.remove(); for (const held of mapped) { const mine = trades.filter(t => t.no === held.no); const title = held.name; try { const nav = await navLoads.get(held.codePrdct); if (nav.warning) message(root, nav.warning, '#e67700'); const detail = await fetchFundDetail(held); const { holder } = addPanel(root, title, held.codePrdct); draw(holder, fundSeries(nav.rows, mine), { costLine: detail.avgCost, unit: '/1万口' }); } catch (e) { message(root, `${title}:${e.message}`); } } root.dataset.jisTradeChartState = 'ready'; } main().catch(e => { console.error('[JIS DC Trade Chart]', e); const root = document.querySelector('[data-jis-trade-chart="root"]'); if (root) { message(root, `エラー:${e.message}`); root.dataset.jisTradeChartState = 'error'; } }); })();