bitbank-lab-mcp 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/lib/asset-code.ts +2 -42
  2. package/lib/bounded-expiring-set.ts +12 -156
  3. package/lib/cache.ts +0 -14
  4. package/lib/calendar.ts +11 -110
  5. package/lib/candle-fetch.ts +5 -84
  6. package/lib/candle-utils.ts +0 -15
  7. package/lib/candle-validate.ts +6 -88
  8. package/lib/conversions.ts +1 -19
  9. package/lib/datetime.ts +6 -109
  10. package/lib/depth-analysis.ts +1 -14
  11. package/lib/error.ts +1 -17
  12. package/lib/fees.ts +6 -71
  13. package/lib/formatter.ts +86 -125
  14. package/lib/get-depth.ts +11 -20
  15. package/lib/http.ts +7 -70
  16. package/lib/indicator-config.ts +8 -13
  17. package/lib/indicator-zones.ts +179 -0
  18. package/lib/indicators.ts +19 -207
  19. package/lib/logger.ts +7 -47
  20. package/lib/ma-snapshot-utils.ts +4 -8
  21. package/lib/math.ts +1 -45
  22. package/lib/pair-code.ts +4 -70
  23. package/lib/pairs.ts +9 -133
  24. package/lib/pattern-diagrams.ts +16 -85
  25. package/lib/price.ts +46 -22
  26. package/lib/provisional-bar.ts +3 -32
  27. package/lib/result.ts +2 -32
  28. package/lib/tickers.ts +3 -26
  29. package/lib/trigger-price.ts +1 -11
  30. package/lib/tx-archive.ts +2 -43
  31. package/lib/tx-fetch.ts +41 -259
  32. package/lib/validate.ts +4 -32
  33. package/lib/volatility.ts +0 -64
  34. package/lib/warning-propagation.ts +0 -32
  35. package/package.json +5 -5
  36. package/src/env.ts +2 -9
  37. package/src/handlers/analyzeCandlePatternsHandler.ts +16 -34
  38. package/src/handlers/analyzeFibonacciHandler.ts +0 -2
  39. package/src/handlers/analyzeIndicatorsHandler.ts +78 -128
  40. package/src/handlers/analyzeMarketSignalHandler.ts +19 -38
  41. package/src/handlers/analyzeMyPortfolioHandler.ts +946 -1484
  42. package/src/handlers/detectPatternsDebugView.ts +402 -0
  43. package/src/handlers/detectPatternsHandler.ts +11 -22
  44. package/src/handlers/detectPatternsViewsHandler.ts +109 -1000
  45. package/src/handlers/getTickersJpyHandler.ts +9 -8
  46. package/src/handlers/getVolatilityMetricsHandler.ts +10 -60
  47. package/src/handlers/portfolio/calc.ts +173 -858
  48. package/src/handlers/portfolio/calendar.ts +1 -36
  49. package/src/handlers/portfolio/fetch.ts +31 -379
  50. package/src/handlers/portfolio/holdings.ts +471 -0
  51. package/src/handlers/portfolio/pagination.ts +83 -0
  52. package/src/handlers/portfolio/types.ts +31 -426
  53. package/src/handlers/renderChartSvgHandler.ts +0 -4
  54. package/src/handlers/runBacktestHandler.ts +0 -1
  55. package/src/lib/bitbank-errors.ts +1 -18
  56. package/src/mcp-apps-hydration.ts +7 -83
  57. package/src/mcp-apps-meta.ts +3 -29
  58. package/src/private/auth.ts +2 -37
  59. package/src/private/client.ts +53 -84
  60. package/src/private/config.ts +3 -33
  61. package/src/private/confirmation.ts +14 -137
  62. package/src/private/elicitation.ts +16 -277
  63. package/src/private/execute-gate.ts +27 -0
  64. package/src/private/preview-confirmation.ts +67 -0
  65. package/src/private/request-state.ts +8 -116
  66. package/src/private/schemas.ts +71 -317
  67. package/src/private/tool-error.ts +1 -38
  68. package/src/prompts/intermediate.ts +1 -28
  69. package/src/prompts/shared.ts +0 -1
  70. package/src/resources/app-resources.ts +1 -37
  71. package/src/schema/analysis.ts +52 -83
  72. package/src/schema/backtest.ts +0 -4
  73. package/src/schema/base.ts +25 -117
  74. package/src/schema/candle-validate.ts +0 -6
  75. package/src/schema/chart.ts +18 -39
  76. package/src/schema/index.ts +0 -2
  77. package/src/schema/indicators.ts +26 -13
  78. package/src/schema/market-data.ts +23 -64
  79. package/src/schema/pairs.ts +0 -7
  80. package/src/schema/patterns.ts +135 -239
  81. package/src/schema/types.ts +0 -11
  82. package/src/schema/ui.ts +1 -7
  83. package/src/schemas.ts +0 -5
  84. package/src/server.ts +13 -76
  85. package/src/tool-definition.ts +2 -39
  86. package/src/tool-registry.ts +5 -62
  87. package/src/ui-snapshot-cache.ts +7 -80
  88. package/tools/analyze_bb_snapshot.ts +147 -76
  89. package/tools/analyze_candle_patterns.ts +12 -158
  90. package/tools/analyze_currency_strength.ts +2 -27
  91. package/tools/analyze_ema_snapshot.ts +5 -9
  92. package/tools/analyze_fibonacci.ts +4 -59
  93. package/tools/analyze_ichimoku_snapshot.ts +37 -69
  94. package/tools/analyze_indicators.ts +50 -61
  95. package/tools/analyze_market_signal.ts +14 -47
  96. package/tools/analyze_mtf_fibonacci.ts +2 -29
  97. package/tools/analyze_mtf_sma.ts +1 -13
  98. package/tools/analyze_sma_snapshot.ts +24 -16
  99. package/tools/analyze_stoch_snapshot.ts +5 -17
  100. package/tools/analyze_support_resistance.ts +7 -59
  101. package/tools/analyze_volume_profile.ts +52 -115
  102. package/tools/chart/depth-paths.ts +37 -0
  103. package/tools/chart/ichimoku-cloud.ts +0 -17
  104. package/tools/chart/render-depth.ts +16 -52
  105. package/tools/chart/render-sub-panels.ts +2 -9
  106. package/tools/chart/svg-utils.ts +0 -18
  107. package/tools/detect_macd_cross.ts +1 -19
  108. package/tools/detect_patterns.ts +162 -228
  109. package/tools/detect_whale_events.ts +1 -8
  110. package/tools/get_candles.ts +89 -323
  111. package/tools/get_flow_metrics.ts +22 -197
  112. package/tools/get_orderbook.ts +28 -88
  113. package/tools/get_ticker.ts +0 -11
  114. package/tools/get_tickers_jpy.ts +12 -20
  115. package/tools/get_transactions.ts +9 -56
  116. package/tools/get_ui_snapshot.ts +4 -30
  117. package/tools/get_volatility_metrics.ts +7 -44
  118. package/tools/patterns/aftermath.ts +7 -27
  119. package/tools/patterns/bar-thresholds.ts +6 -97
  120. package/tools/patterns/candidate-filter.ts +5 -70
  121. package/tools/patterns/confidence-text.ts +45 -0
  122. package/tools/patterns/config.ts +111 -512
  123. package/tools/patterns/detect_doubles.ts +294 -1271
  124. package/tools/patterns/detect_hs.ts +436 -1608
  125. package/tools/patterns/detect_pennants.ts +55 -176
  126. package/tools/patterns/detect_triangles.ts +80 -243
  127. package/tools/patterns/detect_triples.ts +498 -1774
  128. package/tools/patterns/detect_wedges.ts +425 -992
  129. package/tools/patterns/helpers.ts +39 -495
  130. package/tools/patterns/index.ts +1 -10
  131. package/tools/patterns/min-bars.ts +7 -91
  132. package/tools/patterns/mutual-exclusion.ts +10 -121
  133. package/tools/patterns/period.ts +7 -50
  134. package/tools/patterns/ranking.ts +1 -39
  135. package/tools/patterns/regression.ts +38 -42
  136. package/tools/patterns/reversal-gate.ts +6 -90
  137. package/tools/patterns/scan-window.ts +4 -95
  138. package/tools/patterns/scoring.ts +44 -46
  139. package/tools/patterns/smoothing.ts +3 -52
  140. package/tools/patterns/structural.ts +138 -992
  141. package/tools/patterns/structure-diagnostics.ts +36 -0
  142. package/tools/patterns/swing.ts +25 -66
  143. package/tools/patterns/target-confounders.ts +12 -100
  144. package/tools/patterns/target-reach.ts +22 -364
  145. package/tools/patterns/types.ts +20 -178
  146. package/tools/patterns/wedge-helpers.ts +90 -0
  147. package/tools/prepare_chart_data.ts +20 -67
  148. package/tools/prepare_depth_data.ts +12 -49
  149. package/tools/private/analyze_my_portfolio.ts +0 -9
  150. package/tools/private/cancel_order.ts +4 -46
  151. package/tools/private/cancel_orders.ts +4 -42
  152. package/tools/private/create_order.ts +9 -72
  153. package/tools/private/get_margin_positions.ts +31 -31
  154. package/tools/private/get_margin_status.ts +14 -29
  155. package/tools/private/get_margin_trade_history.ts +4 -59
  156. package/tools/private/get_my_assets.ts +1 -19
  157. package/tools/private/get_my_deposit_withdrawal.ts +47 -140
  158. package/tools/private/get_my_orders.ts +2 -25
  159. package/tools/private/get_my_trade_history.ts +4 -35
  160. package/tools/private/get_order.ts +1 -13
  161. package/tools/private/get_orders_info.ts +2 -14
  162. package/tools/private/preview_cancel_order.ts +21 -111
  163. package/tools/private/preview_cancel_orders.ts +17 -83
  164. package/tools/private/preview_order.ts +20 -102
  165. package/tools/refresh_pairs_cache.ts +1 -9
  166. package/tools/render_candle_pattern_diagram.ts +5 -64
  167. package/tools/render_chart_svg.ts +15 -102
  168. package/tools/render_depth_svg.ts +32 -62
  169. package/tools/trading_process/index.ts +0 -4
  170. package/tools/trading_process/lib/backtest_engine.ts +12 -122
  171. package/tools/trading_process/lib/equity.ts +2 -60
  172. package/tools/trading_process/lib/fetch_candles.ts +3 -56
  173. package/tools/trading_process/lib/resolve_fee.ts +3 -36
  174. package/tools/trading_process/lib/sma.ts +1 -49
  175. package/tools/trading_process/lib/strategies/bb_breakout.ts +4 -26
  176. package/tools/trading_process/lib/strategies/filters.ts +30 -0
  177. package/tools/trading_process/lib/strategies/index.ts +0 -20
  178. package/tools/trading_process/lib/strategies/macd_cross.ts +13 -91
  179. package/tools/trading_process/lib/strategies/rsi.ts +2 -31
  180. package/tools/trading_process/lib/strategies/sma_cross.ts +6 -73
  181. package/tools/trading_process/lib/strategies/types.ts +2 -58
  182. package/tools/trading_process/lib/svg_to_png.ts +1 -22
  183. package/tools/trading_process/render_backtest_chart_generic.ts +10 -75
  184. package/tools/trading_process/run_backtest.ts +5 -54
  185. package/tools/trading_process/types.ts +4 -21
  186. package/tools/validate_candle_data.ts +0 -16
  187. package/ui/cancel-confirm/dist/cancel-confirm.html +61 -64
  188. package/ui/order-confirm/dist/order-confirm.html +61 -64
@@ -1,29 +1,17 @@
1
- /**
2
- * /candlestick エンドポイントの chunk fetcher と merge ロジック。
3
- *
4
- * - `fetchCandleChunk` は単一 chunk(年単位 YYYY / 日単位 YYYYMMDD)の取得。
5
- * 通信エラーは throw せず result.error にラップ、success:0 は UpstreamApiError として記録する。
6
- * - `mergeChunks` は複数 chunk を並列 / バッチ並列で取得し、timestamp 昇順でマージする。
7
- * 失敗ハンドリング(full / majority / partial)は呼び出し側に委ねる — 集計に必要な情報を返す。
8
- */
1
+ // 失敗の扱い(full / majority / partial)は呼び出し側に委ねる。集計に必要な情報だけを返す。
9
2
 
10
3
  import { BITBANK_API_BASE, DEFAULT_RETRIES, fetchJsonWithRateLimit, type RateLimitInfo } from './http.js';
11
4
 
12
5
  /** /candlestick エンドポイントが返す 1 行([open, high, low, close, volume, timestamp]) */
13
6
  export type OhlcvRow = [unknown, unknown, unknown, unknown, unknown, unknown];
14
7
 
15
- /** chunk fetcher が返す結果 */
16
8
  export interface FetchChunkResult {
17
9
  rows: OhlcvRow[];
18
10
  rateLimit: RateLimitInfo | null;
19
11
  error?: unknown;
20
12
  }
21
13
 
22
- /**
23
- * chunk fetcher が success:0 を検出したときに記録するエラー。
24
- * 全チャンク失敗時に network ではなく upstream として明示分類するため
25
- * instanceof で判定する。
26
- */
14
+ /** 全 chunk 失敗時に network ではなく upstream に分類するため instanceof で判定する。 */
27
15
  export class UpstreamApiError extends Error {
28
16
  constructor(message: string) {
29
17
  super(message);
@@ -31,13 +19,6 @@ export class UpstreamApiError extends Error {
31
19
  }
32
20
  }
33
21
 
34
- /**
35
- * /candlestick エンドポイントのレスポンス body を OHLCV 行に正規化する。
36
- * - success !== 1 → UpstreamApiError をエラーとして埋め込んで返す(空 rows)
37
- * - success === 1 → ohlcv 配列を返す(存在しなければ空)
38
- *
39
- * 純粋関数で fetch をモックせず単独でテスト可能。
40
- */
41
22
  export function parseCandleChunk(json: unknown, rateLimit: RateLimitInfo | null): FetchChunkResult {
42
23
  const jsonObj = json as {
43
24
  success?: number;
@@ -54,24 +35,11 @@ export function parseCandleChunk(json: unknown, rateLimit: RateLimitInfo | null)
54
35
  }
55
36
 
56
37
  export interface FetchCandleChunkOptions {
57
- /** チャンク取得のタイムアウト (ms) */
58
38
  timeoutMs?: number;
59
- /** リトライ回数(初回 + N 回) */
60
39
  retries?: number;
61
40
  }
62
41
 
63
- /**
64
- * /candlestick の単一 chunk を取得する。
65
- *
66
- * @param pair 例: "btc_jpy"
67
- * @param type 例: "1day", "1hour"
68
- * @param key 年単位なら "2024"、日単位なら "20240101"
69
- *
70
- * 戻り値の semantics:
71
- * - 成功: rows に OHLCV 行
72
- * - success:0: rows=[], error=UpstreamApiError(呼び出し側で全 chunk 失敗時に upstream 分類)
73
- * - 通信エラー / 例外: rows=[], error=原因となった例外(throw しない)
74
- */
42
+ // throw しない。通信エラーも success:0 も rows=[] と error で返し、分類は呼び出し側で行う。
75
43
  export async function fetchCandleChunk(
76
44
  pair: string,
77
45
  type: string,
@@ -91,36 +59,16 @@ export async function fetchCandleChunk(
91
59
  }
92
60
 
93
61
  export interface MergeChunksOptions {
94
- /**
95
- * 指定時はバッチ並列で取得する(bitbank API レート制限対策)。
96
- * - concurrency: バッチ内の最大同時リクエスト数
97
- * - batchDelayMs: バッチ間に挟む遅延(先頭バッチ前は挟まない)
98
- * 未指定なら全 chunk を `Promise.all` で一括並列実行する。
99
- */
100
62
  batched?: { concurrency: number; batchDelayMs: number };
101
63
  }
102
64
 
103
65
  export interface MergedChunkResult {
104
- /** 全 chunk の OHLCV を timestamp 昇順でマージ・ソートした結果 */
105
66
  rows: OhlcvRow[];
106
- /** keys と同じ順序の per-chunk 結果 */
107
67
  results: FetchChunkResult[];
108
- /** 最後に得た非 null の rateLimit(last-wins) */
109
68
  lastRateLimit: RateLimitInfo | null;
110
- /** 失敗した chunk の key 一覧(keys の元順序を保つ) */
111
69
  failedKeys: string[];
112
70
  }
113
71
 
114
- /**
115
- * 複数 chunk を fetcher に流して結果をマージする。
116
- *
117
- * - 取得失敗(full / majority / partial)の判定は呼び出し側に委ねる。
118
- * そのため `results` と `failedKeys` を返すが、自前で fail を生成しない。
119
- * - `rows` は timestamp 昇順でソート済み。
120
- *
121
- * @param keys 各 chunk の URL 末尾要素(年/日)
122
- * @param fetcher key を受け取って FetchChunkResult を返す関数
123
- */
124
72
  export async function mergeChunks(
125
73
  keys: string[],
126
74
  fetcher: (key: string) => Promise<FetchChunkResult>,
@@ -153,20 +101,13 @@ export async function mergeChunks(
153
101
  rows.push(...r.rows);
154
102
  }
155
103
 
156
- // timestamp (index 5) 昇順でソート。Number 変換失敗時は 0 にフォールバック。
157
104
  rows.sort((a, b) => (Number(a[5]) || 0) - (Number(b[5]) || 0));
158
105
 
159
106
  const failedKeys = keys.filter((_, i) => results[i].error != null);
160
107
  return { rows, results, lastRateLimit, failedKeys };
161
108
  }
162
109
 
163
- /**
164
- * 失敗した chunk を「key(エラー内容)」形式で列挙する(診断用メッセージ向け)。
165
- * 例: "20260708(HTTP 404 Not Found), 20260707(bitbank API error (code: 10000))"
166
- *
167
- * 「N日中M日失敗」だけではどの日付が何の理由で落ちたか判別できず調査不能になるため、
168
- * 過半数失敗 fail / 部分失敗 warning のメッセージには必ずこれを含めること。
169
- */
110
+ // どの日付が何の理由で落ちたか調査できるよう、過半数失敗 / 部分失敗のメッセージには必ずこれを含める。
170
111
  export function describeFailedChunks(
171
112
  keys: string[],
172
113
  results: FetchChunkResult[],
@@ -187,12 +128,6 @@ function isOhlcAllZero(row: OhlcvRow): boolean {
187
128
  return Number(row[0]) === 0 && Number(row[1]) === 0 && Number(row[2]) === 0 && Number(row[3]) === 0;
188
129
  }
189
130
 
190
- /**
191
- * 同一 ts 内で curr を採用すべきかを判定する。
192
- * - a) 全 0 OHLC プレースホルダを除外
193
- * - b) volume が大きい行を優先
194
- * - c) タイなら後勝ち(配列上で後の行)
195
- */
196
131
  function shouldPreferCurr(prev: OhlcvRow, curr: OhlcvRow): boolean {
197
132
  const prevAllZero = isOhlcAllZero(prev);
198
133
  const currAllZero = isOhlcAllZero(curr);
@@ -207,21 +142,7 @@ function shouldPreferCurr(prev: OhlcvRow, curr: OhlcvRow): boolean {
207
142
  return true;
208
143
  }
209
144
 
210
- /**
211
- * 同一 timestamp の重複行を排除する純関数。
212
- *
213
- * /candlestick レスポンスで観測される同一 ts 重複(一方は全 0 OHLC のプレースホルダ)を排除し、
214
- * インジケーター・パターン検出・バックテストへの副作用を防ぐ。
215
- *
216
- * 前提: 入力は timestamp 昇順ソート済み。
217
- *
218
- * 採用ルール(上から順に評価):
219
- * a) OHLC の全てが 0 ではない行を優先(全 0 プレースホルダ行を除外)
220
- * b) 上記タイで残ったら volume が大きい行を優先
221
- * c) さらにタイなら後勝ち(配列上で後の行を採用)
222
- *
223
- * timestamp が NaN/<=0 の行は dedupe 対象外で素通し(後段の row validation で upstream 分類される)。
224
- */
145
+ // /candlestick で同一 ts の重複(一方は全 0 OHLC のプレースホルダ)が観測されるので排除する。timestamp が不正な行は素通しし、後段の row validation で upstream に分類させる。
225
146
  export function dedupeByTimestamp(rows: OhlcvRow[]): OhlcvRow[] {
226
147
  if (rows.length === 0) return [];
227
148
  const result: OhlcvRow[] = [];
@@ -1,48 +1,33 @@
1
- /**
2
- * ローソク足ヘルパー関数
3
- *
4
- * isBullish / isBearish / bodySize / bodyTop / bodyBottom を提供。
5
- * analyze_candle_patterns.ts から抽出。他ツールでも再利用可能。
6
- */
7
-
8
1
  import type { Candle } from '../src/schemas.js';
9
2
 
10
- /** ローソク足が陽線かどうか */
11
3
  export function isBullish(c: Candle): boolean {
12
4
  return c.close > c.open;
13
5
  }
14
6
 
15
- /** ローソク足が陰線かどうか */
16
7
  export function isBearish(c: Candle): boolean {
17
8
  return c.close < c.open;
18
9
  }
19
10
 
20
- /** 実体の大きさを取得 */
21
11
  export function bodySize(c: Candle): number {
22
12
  return Math.abs(c.close - c.open);
23
13
  }
24
14
 
25
- /** 実体の上端 */
26
15
  export function bodyTop(c: Candle): number {
27
16
  return Math.max(c.open, c.close);
28
17
  }
29
18
 
30
- /** 実体の下端 */
31
19
  export function bodyBottom(c: Candle): number {
32
20
  return Math.min(c.open, c.close);
33
21
  }
34
22
 
35
- /** 上ヒゲの長さ */
36
23
  export function upperShadow(c: Candle): number {
37
24
  return c.high - bodyTop(c);
38
25
  }
39
26
 
40
- /** 下ヒゲの長さ */
41
27
  export function lowerShadow(c: Candle): number {
42
28
  return bodyBottom(c) - c.low;
43
29
  }
44
30
 
45
- /** ローソク足全体のレンジ(高値 - 安値) */
46
31
  export function totalRange(c: Candle): number {
47
32
  return c.high - c.low;
48
33
  }
@@ -1,24 +1,8 @@
1
- /**
2
- * lib/candle-validate.ts — ローソク足データの品質検証ロジック
3
- *
4
- * Vol.01(データ取得とクレンジング)のバリデーション手法をベースに、
5
- * OHLCV データの完全性・整合性・異常値を検出する純粋関数群。
6
- *
7
- * 【暗号資産ドメイン考慮】
8
- * - ファットテール分布: σ閾値は株式より広め(Vol.01 の教え)
9
- * - 出来高ゼロ: 「取引がなかった」= 正常(Vol.01 の補完戦略: 0埋め)
10
- * - ペアティア: major/mid/minor で流動性・スプレッドが大きく異なる
11
- *
12
- * 【共通仕様】
13
- * - 入力: CandleRow[](古い順、isoTime 付き)
14
- * - 出力: 各検証結果オブジェクト
15
- * - 副作用なし
16
- */
1
+ // 暗号資産はファットテールなので σ 閾値は株式より広めにする(Vol.01)。
17
2
 
18
3
  import { dayjs } from './datetime.js';
19
4
  import { avg, stddev } from './math.js';
20
5
 
21
- /** 検証対象のローソク足行 */
22
6
  export interface CandleRow {
23
7
  open: number;
24
8
  high: number;
@@ -28,9 +12,7 @@ export interface CandleRow {
28
12
  isoTime?: string | null;
29
13
  }
30
14
 
31
- // ── ペアティア分類 ──
32
- // 参考: bitbank-cli-skills pair-classification.md
33
- // 24h出来高シェア(JPY建て売買代金割合)に基づく分類
15
+ // 24h 出来高シェア(JPY 建て売買代金の割合)による分類(bitbank-cli-skills の pair-classification.md)。
34
16
 
35
17
  export type PairTier = 'major' | 'mid' | 'minor';
36
18
 
@@ -48,12 +30,7 @@ const MID_PAIRS = new Set([
48
30
  'link_jpy',
49
31
  ]);
50
32
 
51
- /**
52
- * ペア名からティアを判定する。
53
- * major: 出来高シェア10%以上(板が厚く、スプレッド狭い)
54
- * mid: 出来高シェア1-10%(深夜帯は板が薄くなることがある)
55
- * minor: 出来高シェア1%未満(出来高ゼロが散発、スプレッド広い、ヒゲが出やすい)
56
- */
33
+ // major は出来高シェア 10% 以上、mid は 1〜10%、minor は 1% 未満。
57
34
  export function classifyPairTier(pair: string): PairTier {
58
35
  const normalized = pair.toLowerCase();
59
36
  if (MAJOR_PAIRS.has(normalized)) return 'major';
@@ -61,21 +38,9 @@ export function classifyPairTier(pair: string): PairTier {
61
38
  return 'minor';
62
39
  }
63
40
 
64
- /**
65
- * ティアに応じたデフォルト閾値を返す。
66
- *
67
- * Vol.01 の教え:
68
- * - 暗号資産はファットテール → σ閾値は広めが妥当
69
- * - 出来高ゼロ = 取引がなかった(正常)
70
- *
71
- * ペア分類の教え:
72
- * - minor は出来高ゼロが日常的、スプレッド由来のヒゲも頻出
73
- * - major は板が厚く、異常値はより信号として意味がある
74
- */
75
41
  export interface TierDefaults {
76
42
  priceSigma: number;
77
43
  volumeMultiplier: number;
78
- /** 出来高ゼロを品質スコアで減点する重み (0=減点なし, 1=フル減点) */
79
44
  zeroVolumePenaltyWeight: number;
80
45
  }
81
46
 
@@ -90,8 +55,6 @@ export function getTierDefaults(tier: PairTier): TierDefaults {
90
55
  }
91
56
  }
92
57
 
93
- // ── 時間足ごとのインターバル(ミリ秒) ──
94
-
95
58
  const INTERVAL_MS: Record<string, number> = {
96
59
  '1min': 60_000,
97
60
  '5min': 300_000,
@@ -104,8 +67,6 @@ const INTERVAL_MS: Record<string, number> = {
104
67
  '1day': 86_400_000,
105
68
  };
106
69
 
107
- // ── 1. 完全性チェック ──
108
-
109
70
  export interface CompletenessResult {
110
71
  expected: number;
111
72
  actual: number;
@@ -114,16 +75,10 @@ export interface CompletenessResult {
114
75
  ratio: number; // 0–1
115
76
  }
116
77
 
117
- /**
118
- * タイムスタンプの歯抜けを検出する。
119
- * Vol.01 の「expected_index との差分」パターン。
120
- *
121
- * 1week / 1month は間隔が不規則なのでスキップ(ratio: 1 を返す)。
122
- */
78
+ // 1week / 1month は間隔が不規則なのでスキップする(ratio: 1)。
123
79
  export function checkCompleteness(candles: CandleRow[], candleType: string): CompletenessResult {
124
80
  const intervalMs = INTERVAL_MS[candleType];
125
81
 
126
- // 不規則間隔の時間足はスキップ
127
82
  if (!intervalMs || candles.length < 2) {
128
83
  return { expected: candles.length, actual: candles.length, missing: 0, missingTimestamps: [], ratio: 1 };
129
84
  }
@@ -156,8 +111,6 @@ export function checkCompleteness(candles: CandleRow[], candleType: string): Com
156
111
  };
157
112
  }
158
113
 
159
- // ── 2. 重複チェック ──
160
-
161
114
  export interface DuplicatesResult {
162
115
  count: number;
163
116
  timestamps: string[];
@@ -180,8 +133,6 @@ export function checkDuplicates(candles: CandleRow[]): DuplicatesResult {
180
133
  return { count: duplicates.length, timestamps: duplicates.slice(0, 50) };
181
134
  }
182
135
 
183
- // ── 3. OHLCV 整合性チェック ──
184
-
185
136
  export interface IntegrityIssue {
186
137
  index: number;
187
138
  isoTime: string | null;
@@ -194,13 +145,6 @@ export interface IntegrityResult {
194
145
  issues: IntegrityIssue[];
195
146
  }
196
147
 
197
- /**
198
- * OHLCV の論理整合性を検証。
199
- * - high >= low
200
- * - high >= max(open, close)
201
- * - low <= min(open, close)
202
- * - volume >= 0
203
- */
204
148
  export function checkIntegrity(candles: CandleRow[]): IntegrityResult {
205
149
  const issues: IntegrityIssue[] = [];
206
150
 
@@ -233,8 +177,6 @@ export function checkIntegrity(candles: CandleRow[]): IntegrityResult {
233
177
  };
234
178
  }
235
179
 
236
- // ── 4. 価格異常値検出 ──
237
-
238
180
  export interface PriceAnomaly {
239
181
  index: number;
240
182
  isoTime: string | null;
@@ -249,16 +191,11 @@ export interface PriceAnomalyResult {
249
191
  stats: { mean: number; stddev: number; threshold: number } | null;
250
192
  }
251
193
 
252
- /**
253
- * 前足比の変化率(pct_change)が ±N σ を超えるバーを検出。
254
- * Vol.01 の `ret.describe()` + 外れ値検出パターン。
255
- */
256
194
  export function checkPriceAnomalies(candles: CandleRow[], sigmaThreshold: number): PriceAnomalyResult {
257
195
  if (candles.length < 3) {
258
196
  return { totalBars: candles.length, anomalyCount: 0, anomalies: [], stats: null };
259
197
  }
260
198
 
261
- // リターン(変化率)を計算
262
199
  const returns: number[] = [];
263
200
  for (let i = 1; i < candles.length; i++) {
264
201
  const prev = candles[i - 1].close;
@@ -302,8 +239,6 @@ export function checkPriceAnomalies(candles: CandleRow[], sigmaThreshold: number
302
239
  };
303
240
  }
304
241
 
305
- // ── 5. 出来高異常値検出 ──
306
-
307
242
  export interface VolumeAnomaly {
308
243
  index: number;
309
244
  isoTime: string | null;
@@ -321,9 +256,6 @@ export interface VolumeAnomalyResult {
321
256
  stats: { avgVolume: number; threshold: number } | null;
322
257
  }
323
258
 
324
- /**
325
- * 出来高ゼロ、または移動平均の N 倍超のスパイクを検出。
326
- */
327
259
  export function checkVolumeAnomalies(candles: CandleRow[], multiplierThreshold: number): VolumeAnomalyResult {
328
260
  const volumes = candles.map((c) => c.volume ?? 0);
329
261
 
@@ -331,8 +263,7 @@ export function checkVolumeAnomalies(candles: CandleRow[], multiplierThreshold:
331
263
  return { totalBars: 0, anomalyCount: 0, zeroCount: 0, spikeCount: 0, anomalies: [], stats: null };
332
264
  }
333
265
 
334
- // スパイク検出のベースラインはゼロ出来高を除外して算出
335
- // Vol.01: 出来高ゼロ = 「取引がなかった」なのでベースラインに含めるべきではない
266
+ // スパイクのベースラインはゼロ出来高を除いて算出する(ゼロは取引が無かっただけ)。
336
267
  const nonZeroVolumes = volumes.filter((v) => v > 0);
337
268
  const avgVol = avg(nonZeroVolumes) ?? 0;
338
269
  const anomalies: VolumeAnomaly[] = [];
@@ -367,8 +298,6 @@ export function checkVolumeAnomalies(candles: CandleRow[], multiplierThreshold:
367
298
  };
368
299
  }
369
300
 
370
- // ── 6. 総合品質スコア ──
371
-
372
301
  export interface QualityScore {
373
302
  score: number; // 0–100
374
303
  breakdown: {
@@ -380,14 +309,7 @@ export interface QualityScore {
380
309
  grade: 'A' | 'B' | 'C' | 'D' | 'F';
381
310
  }
382
311
 
383
- /**
384
- * 各チェック結果を総合して 0–100 の品質スコアを算出。
385
- *
386
- * @param zeroVolumePenaltyWeight 出来高ゼロの減点重み (0–1)。
387
- * Vol.01: 出来高ゼロ = 「取引がなかった」= 正常な解釈。
388
- * minor ペアでは日常的に発生するため 0(減点なし)、
389
- * major ペアでは異常の可能性があるため 1(フル減点)。
390
- */
312
+ // minor は出来高ゼロが日常的なので減点 0、major は異常の可能性があるので 1 を渡す。
391
313
  export function computeQualityScore(
392
314
  completeness: CompletenessResult,
393
315
  integrity: IntegrityResult,
@@ -395,19 +317,15 @@ export function computeQualityScore(
395
317
  volumeAnomalies: VolumeAnomalyResult,
396
318
  zeroVolumePenaltyWeight = 1,
397
319
  ): QualityScore {
398
- // 完全性(30点): 欠損率に応じて減点
399
320
  const completenessScore = Math.round(completeness.ratio * 30);
400
321
 
401
- // 整合性(25点): 不正レコード率に応じて減点
402
322
  const integrityRatio = integrity.totalChecked > 0 ? 1 - integrity.invalidCount / integrity.totalChecked : 1;
403
323
  const integrityScore = Math.round(integrityRatio * 25);
404
324
 
405
- // 価格安定性(25点): 異常値率に応じて減点
406
325
  const priceRatio =
407
326
  priceAnomalies.totalBars > 1 ? 1 - Math.min(priceAnomalies.anomalyCount / (priceAnomalies.totalBars - 1), 1) : 1;
408
327
  const priceScore = Math.round(priceRatio * 25);
409
328
 
410
- // 出来高健全性(20点): ゼロ率(重み付き)とスパイク率で減点
411
329
  const zeroRatio = volumeAnomalies.totalBars > 0 ? volumeAnomalies.zeroCount / volumeAnomalies.totalBars : 0;
412
330
  const spikeRatio = volumeAnomalies.totalBars > 0 ? volumeAnomalies.spikeCount / volumeAnomalies.totalBars : 0;
413
331
  const volumeScore = Math.round((1 - Math.min(zeroRatio * zeroVolumePenaltyWeight + spikeRatio, 1)) * 20);
@@ -1,22 +1,4 @@
1
- /**
2
- * API レスポンスの文字列→数値変換ユーティリティ
3
- *
4
- * bitbank API は価格・数量等を文字列で返す。
5
- * 各ツールで散在していた `d.x != null ? Number(d.x) : null` を統一する。
6
- */
7
-
8
- /**
9
- * unknown 値を有限な number に変換する。
10
- * null / undefined / NaN / Infinity は null を返す。
11
- *
12
- * @example
13
- * toNum("12345.67") // 12345.67
14
- * toNum(null) // null
15
- * toNum(undefined) // null
16
- * toNum("") // null (Number("") === 0 だが意図しない変換を防ぐ)
17
- * toNum("abc") // null
18
- * toNum(Infinity) // null
19
- */
1
+ // "" は Number("") === 0 だが、意図しない 0 変換を防ぐため null にする。
20
2
  export function toNum(v: unknown): number | null {
21
3
  if (v == null) return null;
22
4
  if (typeof v === 'string' && v.trim() === '') return null;