bitbank-lab-mcp 0.1.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 (147) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +388 -0
  3. package/assets/lightweight-charts.standalone.js +7 -0
  4. package/bin/bitbank-lab-mcp.js +20 -0
  5. package/lib/cache.ts +70 -0
  6. package/lib/candle-utils.ts +48 -0
  7. package/lib/candle-validate.ts +434 -0
  8. package/lib/conversions.ts +25 -0
  9. package/lib/datetime.ts +157 -0
  10. package/lib/depth-analysis.ts +51 -0
  11. package/lib/error.ts +15 -0
  12. package/lib/formatter.ts +296 -0
  13. package/lib/get-depth.ts +111 -0
  14. package/lib/http.ts +132 -0
  15. package/lib/indicator-config.ts +39 -0
  16. package/lib/indicator_buffer.ts +41 -0
  17. package/lib/indicators.ts +579 -0
  18. package/lib/logger.ts +120 -0
  19. package/lib/ma-snapshot-utils.ts +277 -0
  20. package/lib/math.ts +89 -0
  21. package/lib/pattern-diagrams.ts +562 -0
  22. package/lib/result.ts +104 -0
  23. package/lib/validate.ts +154 -0
  24. package/lib/volatility.ts +132 -0
  25. package/package.json +79 -0
  26. package/src/env.ts +4 -0
  27. package/src/handlers/analyzeCandlePatternsHandler.ts +383 -0
  28. package/src/handlers/analyzeFibonacciHandler.ts +54 -0
  29. package/src/handlers/analyzeIndicatorsHandler.ts +682 -0
  30. package/src/handlers/analyzeMarketSignalHandler.ts +272 -0
  31. package/src/handlers/analyzeMyPortfolioHandler.ts +800 -0
  32. package/src/handlers/detectPatternsHandler.ts +77 -0
  33. package/src/handlers/detectPatternsViewsHandler.ts +518 -0
  34. package/src/handlers/getTickersJpyHandler.ts +145 -0
  35. package/src/handlers/getVolatilityMetricsHandler.ts +234 -0
  36. package/src/handlers/portfolio/calc.ts +549 -0
  37. package/src/handlers/portfolio/fetch.ts +318 -0
  38. package/src/handlers/portfolio/types.ts +170 -0
  39. package/src/handlers/renderChartSvgHandler.ts +69 -0
  40. package/src/handlers/runBacktestHandler.ts +70 -0
  41. package/src/http.ts +107 -0
  42. package/src/private/auth.ts +104 -0
  43. package/src/private/client.ts +298 -0
  44. package/src/private/config.ts +25 -0
  45. package/src/private/confirmation.ts +185 -0
  46. package/src/private/schemas.ts +866 -0
  47. package/src/prompts.ts +2296 -0
  48. package/src/resources/app-resources.ts +79 -0
  49. package/src/schema/analysis.ts +942 -0
  50. package/src/schema/backtest.ts +100 -0
  51. package/src/schema/base.ts +88 -0
  52. package/src/schema/candle-validate.ts +135 -0
  53. package/src/schema/chart.ts +399 -0
  54. package/src/schema/index.ts +11 -0
  55. package/src/schema/indicators.ts +125 -0
  56. package/src/schema/market-data.ts +298 -0
  57. package/src/schema/patterns.ts +382 -0
  58. package/src/schema/types.ts +97 -0
  59. package/src/schemas.d.ts +37 -0
  60. package/src/schemas.ts +7 -0
  61. package/src/server.ts +405 -0
  62. package/src/tool-definition.ts +44 -0
  63. package/src/tool-registry.ts +174 -0
  64. package/src/types/express-shim.d.ts +9 -0
  65. package/src/types/schemas.generated.d.ts +23 -0
  66. package/tools/analyze_bb_snapshot.ts +385 -0
  67. package/tools/analyze_candle_patterns.ts +810 -0
  68. package/tools/analyze_currency_strength.ts +273 -0
  69. package/tools/analyze_ema_snapshot.ts +183 -0
  70. package/tools/analyze_fibonacci.ts +530 -0
  71. package/tools/analyze_ichimoku_snapshot.ts +606 -0
  72. package/tools/analyze_indicators.ts +691 -0
  73. package/tools/analyze_market_signal.ts +665 -0
  74. package/tools/analyze_mtf_fibonacci.ts +273 -0
  75. package/tools/analyze_mtf_sma.ts +175 -0
  76. package/tools/analyze_sma_snapshot.ts +146 -0
  77. package/tools/analyze_stoch_snapshot.ts +276 -0
  78. package/tools/analyze_support_resistance.ts +817 -0
  79. package/tools/analyze_volume_profile.ts +546 -0
  80. package/tools/chart/ichimoku-cloud.ts +113 -0
  81. package/tools/chart/render-depth.ts +139 -0
  82. package/tools/chart/render-sub-panels.ts +208 -0
  83. package/tools/chart/svg-utils.ts +102 -0
  84. package/tools/detect_macd_cross.ts +691 -0
  85. package/tools/detect_patterns.ts +424 -0
  86. package/tools/detect_whale_events.ts +181 -0
  87. package/tools/get_candles.ts +487 -0
  88. package/tools/get_flow_metrics.ts +596 -0
  89. package/tools/get_orderbook.ts +540 -0
  90. package/tools/get_ticker.ts +132 -0
  91. package/tools/get_tickers_jpy.ts +240 -0
  92. package/tools/get_transactions.ts +209 -0
  93. package/tools/get_volatility_metrics.ts +302 -0
  94. package/tools/patterns/aftermath.ts +212 -0
  95. package/tools/patterns/config.ts +151 -0
  96. package/tools/patterns/detect_doubles.ts +650 -0
  97. package/tools/patterns/detect_hs.ts +635 -0
  98. package/tools/patterns/detect_pennants.ts +373 -0
  99. package/tools/patterns/detect_triangles.ts +820 -0
  100. package/tools/patterns/detect_triples.ts +633 -0
  101. package/tools/patterns/detect_wedges.ts +1072 -0
  102. package/tools/patterns/helpers.ts +517 -0
  103. package/tools/patterns/index.ts +40 -0
  104. package/tools/patterns/regression.ts +153 -0
  105. package/tools/patterns/smoothing.ts +168 -0
  106. package/tools/patterns/swing.ts +91 -0
  107. package/tools/patterns/types.ts +193 -0
  108. package/tools/prepare_chart_data.ts +294 -0
  109. package/tools/prepare_depth_data.ts +189 -0
  110. package/tools/private/analyze_my_portfolio.ts +21 -0
  111. package/tools/private/cancel_order.ts +127 -0
  112. package/tools/private/cancel_orders.ts +121 -0
  113. package/tools/private/create_order.ts +236 -0
  114. package/tools/private/get_margin_positions.ts +134 -0
  115. package/tools/private/get_margin_status.ts +155 -0
  116. package/tools/private/get_margin_trade_history.ts +156 -0
  117. package/tools/private/get_my_assets.ts +207 -0
  118. package/tools/private/get_my_deposit_withdrawal.ts +500 -0
  119. package/tools/private/get_my_orders.ts +157 -0
  120. package/tools/private/get_my_trade_history.ts +229 -0
  121. package/tools/private/get_order.ts +95 -0
  122. package/tools/private/get_orders_info.ts +90 -0
  123. package/tools/private/preview_cancel_order.ts +172 -0
  124. package/tools/private/preview_cancel_orders.ts +137 -0
  125. package/tools/private/preview_order.ts +292 -0
  126. package/tools/render_candle_pattern_diagram.ts +389 -0
  127. package/tools/render_chart_svg.ts +799 -0
  128. package/tools/render_depth_svg.ts +274 -0
  129. package/tools/trading_process/index.ts +7 -0
  130. package/tools/trading_process/lib/backtest_engine.ts +252 -0
  131. package/tools/trading_process/lib/equity.ts +131 -0
  132. package/tools/trading_process/lib/fetch_candles.ts +181 -0
  133. package/tools/trading_process/lib/sma.ts +62 -0
  134. package/tools/trading_process/lib/strategies/bb_breakout.ts +141 -0
  135. package/tools/trading_process/lib/strategies/index.ts +52 -0
  136. package/tools/trading_process/lib/strategies/macd_cross.ts +256 -0
  137. package/tools/trading_process/lib/strategies/rsi.ts +133 -0
  138. package/tools/trading_process/lib/strategies/sma_cross.ts +214 -0
  139. package/tools/trading_process/lib/strategies/types.ts +118 -0
  140. package/tools/trading_process/lib/svg_to_png.ts +64 -0
  141. package/tools/trading_process/render_backtest_chart_generic.ts +729 -0
  142. package/tools/trading_process/run_backtest.ts +243 -0
  143. package/tools/trading_process/types.ts +85 -0
  144. package/tools/validate_candle_data.ts +260 -0
  145. package/tsconfig.json +17 -0
  146. package/ui/cancel-confirm/dist/cancel-confirm.html +99 -0
  147. package/ui/order-confirm/dist/order-confirm.html +99 -0
@@ -0,0 +1,185 @@
1
+ /**
2
+ * HITL (Human-in-the-Loop) 確認トークン — 取引操作の2ステップ確認。
3
+ *
4
+ * preview_order / preview_cancel_order / preview_cancel_orders が発行した
5
+ * 確認トークンを、create_order / cancel_order / cancel_orders が検証する。
6
+ * トークンは HMAC-SHA256(BITBANK_API_SECRET, payload) で生成し、
7
+ * パラメータ一致 + 有効期限を検証する。
8
+ */
9
+
10
+ import { createHmac, timingSafeEqual } from 'node:crypto';
11
+
12
+ /** デフォルト有効期限: 60秒 */
13
+ const DEFAULT_TTL_MS = 60_000;
14
+
15
+ /** TTL 上限: 5分 */
16
+ const MAX_TTL_MS = 300_000;
17
+
18
+ /** 使用済みトークンのセット(再利用防止) */
19
+ const usedTokens = new Map<string, number>(); // token → expiresAt
20
+
21
+ /** クリーンアップ間隔: 60秒 */
22
+ const CLEANUP_INTERVAL_MS = 60_000;
23
+
24
+ let cleanupTimerId: ReturnType<typeof setInterval> | null = null;
25
+
26
+ /** TTL 超過分の使用済みトークンを除去する */
27
+ export function purgeExpiredTokens(nowMs: number = Date.now()): number {
28
+ let purged = 0;
29
+ for (const [token, expiresAt] of usedTokens) {
30
+ if (nowMs > expiresAt) {
31
+ usedTokens.delete(token);
32
+ purged++;
33
+ }
34
+ }
35
+ return purged;
36
+ }
37
+
38
+ /** 定期クリーンアップを開始する(重複起動しない) */
39
+ export function startCleanupTimer(): void {
40
+ if (cleanupTimerId != null) return;
41
+ cleanupTimerId = setInterval(() => purgeExpiredTokens(), CLEANUP_INTERVAL_MS);
42
+ // プロセス終了をブロックしないよう unref
43
+ if (typeof cleanupTimerId === 'object' && 'unref' in cleanupTimerId) {
44
+ cleanupTimerId.unref();
45
+ }
46
+ }
47
+
48
+ /** 定期クリーンアップを停止する(テスト用) */
49
+ export function stopCleanupTimer(): void {
50
+ if (cleanupTimerId != null) {
51
+ clearInterval(cleanupTimerId);
52
+ cleanupTimerId = null;
53
+ }
54
+ }
55
+
56
+ /** 使用済みトークンセットをクリアする(テスト用) */
57
+ export function _resetUsedTokens(): void {
58
+ usedTokens.clear();
59
+ }
60
+
61
+ /** 使用済みトークン数を返す(テスト用) */
62
+ export function _usedTokenCount(): number {
63
+ return usedTokens.size;
64
+ }
65
+
66
+ /** クリーンアップタイマーが動作中かどうか(テスト用) */
67
+ export function _isCleanupTimerActive(): boolean {
68
+ return cleanupTimerId != null;
69
+ }
70
+
71
+ function getTtlMs(): number {
72
+ const env = process.env.ORDER_CONFIRM_TTL_MS;
73
+ if (env) {
74
+ const n = Number(env);
75
+ if (Number.isFinite(n) && n > 0) return Math.min(n, MAX_TTL_MS);
76
+ }
77
+ return DEFAULT_TTL_MS;
78
+ }
79
+
80
+ function getSecret(): string {
81
+ const secret = process.env.BITBANK_API_SECRET;
82
+ if (!secret) throw new Error('BITBANK_API_SECRET is not configured');
83
+ return secret;
84
+ }
85
+
86
+ /**
87
+ * トークンペイロードを正規化する。
88
+ * オブジェクトのキーをソートし、undefined を除外して JSON 文字列化する。
89
+ */
90
+ function canonicalize(params: Record<string, unknown>): string {
91
+ const sorted = Object.keys(params)
92
+ .sort()
93
+ .reduce<Record<string, unknown>>((acc, key) => {
94
+ if (params[key] !== undefined) {
95
+ acc[key] = params[key];
96
+ }
97
+ return acc;
98
+ }, {});
99
+ return JSON.stringify(sorted);
100
+ }
101
+
102
+ /** HMAC-SHA256 を計算する */
103
+ function hmac(secret: string, data: string): string {
104
+ return createHmac('sha256', secret).update(data).digest('hex');
105
+ }
106
+
107
+ export interface ConfirmationToken {
108
+ token: string;
109
+ expiresAt: number;
110
+ }
111
+
112
+ /** validateToken のエラー分類 */
113
+ export type TokenErrorCode = 'token_expired' | 'token_already_used' | 'token_invalid';
114
+
115
+ export interface TokenValidationError {
116
+ message: string;
117
+ code: TokenErrorCode;
118
+ }
119
+
120
+ /**
121
+ * 確認トークンを生成する。
122
+ *
123
+ * @param action - 操作種別 ('create_order' | 'cancel_order' | 'cancel_orders')
124
+ * @param params - 操作パラメータ(注文内容やキャンセル対象)
125
+ * @param nowMs - 現在時刻(テスト用にオーバーライド可能)
126
+ */
127
+ export function generateToken(
128
+ action: string,
129
+ params: Record<string, unknown>,
130
+ nowMs: number = Date.now(),
131
+ ): ConfirmationToken {
132
+ const ttl = getTtlMs();
133
+ const expiresAt = nowMs + ttl;
134
+ const payload = canonicalize({ action, ...params, expiresAt });
135
+ const token = hmac(getSecret(), payload);
136
+ return { token, expiresAt };
137
+ }
138
+
139
+ /**
140
+ * 確認トークンを検証する。
141
+ *
142
+ * 検証成功時は usedTokens に登録され、同一トークンの再利用は
143
+ * `token_already_used` で拒否される(ワンショット制約)。
144
+ *
145
+ * @returns null なら検証成功、エラー時はメッセージとコードを返す
146
+ */
147
+ export function validateToken(
148
+ token: string,
149
+ action: string,
150
+ params: Record<string, unknown>,
151
+ expiresAt: number,
152
+ nowMs: number = Date.now(),
153
+ ): TokenValidationError | null {
154
+ // 有効期限チェック
155
+ if (nowMs > expiresAt) {
156
+ return {
157
+ message: '確認トークンの有効期限が切れています。preview を再実行してください',
158
+ code: 'token_expired',
159
+ };
160
+ }
161
+
162
+ // 使用済みチェック(ワンショット)
163
+ if (usedTokens.has(token)) {
164
+ return {
165
+ message: '確認トークンは既に使用されています。preview を再実行してください',
166
+ code: 'token_already_used',
167
+ };
168
+ }
169
+
170
+ // HMAC 再計算で検証
171
+ const payload = canonicalize({ action, ...params, expiresAt });
172
+ const expected = hmac(getSecret(), payload);
173
+
174
+ if (token.length !== expected.length || !timingSafeEqual(Buffer.from(token), Buffer.from(expected))) {
175
+ return {
176
+ message: '確認トークンが無効です。パラメータが変更された可能性があります。preview を再実行してください',
177
+ code: 'token_invalid',
178
+ };
179
+ }
180
+
181
+ // 検証成功 → 使用済みとして登録(ワンショット)
182
+ usedTokens.set(token, expiresAt);
183
+
184
+ return null;
185
+ }