bitbank-lab-mcp 0.6.0 → 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 (50) hide show
  1. package/lib/formatter.ts +47 -19
  2. package/lib/indicator-config.ts +7 -0
  3. package/lib/indicator-zones.ts +179 -0
  4. package/package.json +1 -1
  5. package/src/handlers/analyzeIndicatorsHandler.ts +47 -74
  6. package/src/handlers/analyzeMarketSignalHandler.ts +10 -11
  7. package/src/handlers/analyzeMyPortfolioHandler.ts +31 -7
  8. package/src/handlers/detectPatternsDebugView.ts +2 -7
  9. package/src/handlers/detectPatternsViewsHandler.ts +4 -14
  10. package/src/handlers/getTickersJpyHandler.ts +9 -3
  11. package/src/handlers/portfolio/calc.ts +38 -7
  12. package/src/handlers/portfolio/fetch.ts +6 -6
  13. package/src/handlers/portfolio/types.ts +10 -6
  14. package/src/private/schemas.ts +57 -38
  15. package/src/prompts/intermediate.ts +1 -1
  16. package/src/schema/analysis.ts +22 -7
  17. package/src/schema/base.ts +3 -2
  18. package/src/schema/indicators.ts +17 -0
  19. package/src/schema/market-data.ts +6 -14
  20. package/src/schema/patterns.ts +81 -22
  21. package/tools/analyze_bb_snapshot.ts +146 -64
  22. package/tools/analyze_ema_snapshot.ts +5 -4
  23. package/tools/analyze_ichimoku_snapshot.ts +10 -9
  24. package/tools/analyze_indicators.ts +12 -0
  25. package/tools/analyze_market_signal.ts +8 -7
  26. package/tools/analyze_sma_snapshot.ts +23 -11
  27. package/tools/analyze_stoch_snapshot.ts +4 -11
  28. package/tools/chart/render-sub-panels.ts +1 -2
  29. package/tools/detect_patterns.ts +6 -10
  30. package/tools/get_candles.ts +19 -11
  31. package/tools/get_flow_metrics.ts +4 -16
  32. package/tools/get_transactions.ts +1 -5
  33. package/tools/patterns/confidence-text.ts +45 -0
  34. package/tools/patterns/config.ts +0 -7
  35. package/tools/patterns/detect_doubles.ts +10 -13
  36. package/tools/patterns/detect_hs.ts +365 -924
  37. package/tools/patterns/detect_pennants.ts +33 -11
  38. package/tools/patterns/detect_triangles.ts +31 -8
  39. package/tools/patterns/detect_triples.ts +22 -37
  40. package/tools/patterns/detect_wedges.ts +46 -687
  41. package/tools/patterns/helpers.ts +3 -38
  42. package/tools/patterns/index.ts +0 -1
  43. package/tools/patterns/min-bars.ts +2 -13
  44. package/tools/patterns/scoring.ts +42 -1
  45. package/tools/patterns/types.ts +9 -32
  46. package/tools/patterns/wedge-helpers.ts +2 -170
  47. package/tools/private/get_margin_positions.ts +26 -9
  48. package/tools/private/get_margin_status.ts +13 -13
  49. package/tools/private/get_margin_trade_history.ts +2 -2
  50. package/tools/private/get_my_deposit_withdrawal.ts +11 -3
package/lib/formatter.ts CHANGED
@@ -19,6 +19,38 @@ export function timeframeLabel(type: string): string {
19
19
  return map[type] || type;
20
20
  }
21
21
 
22
+ // 本数を暦の長さとして読めるのは日足・週足・月足だけで、それ以外の足は「本」で数える(#431)。
23
+ const CALENDAR_BAR_UNITS: Record<string, { unit: string; per: string; prevChange: string }> = {
24
+ '1day': { unit: '日', per: '日', prevChange: '前日比' },
25
+ '1week': { unit: '週', per: '週', prevChange: '前週比' },
26
+ '1month': { unit: 'か月', per: '月', prevChange: '前月比' },
27
+ };
28
+ const COUNT_BAR_UNIT = { unit: '本', per: '本', prevChange: '前足比' };
29
+
30
+ function barUnit(type: string) {
31
+ return Object.hasOwn(CALENDAR_BAR_UNITS, type) ? CALENDAR_BAR_UNITS[type] : COUNT_BAR_UNIT;
32
+ }
33
+
34
+ export function barsAgoLabel(bars: number, type: string): string {
35
+ return `${bars}${barUnit(type).unit}前`;
36
+ }
37
+
38
+ export function barsAheadLabel(bars: number, type: string): string {
39
+ return `${bars}${barUnit(type).unit}後`;
40
+ }
41
+
42
+ export function barCountLabel(bars: number, type: string): string {
43
+ return `${bars}${barUnit(type).unit}`;
44
+ }
45
+
46
+ export function perBarLabel(type: string): string {
47
+ return `/${barUnit(type).per}`;
48
+ }
49
+
50
+ export function prevBarChangeLabel(type: string): string {
51
+ return barUnit(type).prevChange;
52
+ }
53
+
22
54
  export function formatPair(pair: string): string {
23
55
  return (pair || '').toUpperCase().replace('_', '/');
24
56
  }
@@ -194,34 +226,30 @@ export function formatSummary(
194
226
  };
195
227
 
196
228
  const today = keyPoints.today;
197
- summary += `\n- 今日 (${today.date || '不明'}, data[${today.index}]): ${formatPrice(today.close)}`;
198
-
199
- if (keyPoints.sevenDaysAgo) {
200
- const sd = keyPoints.sevenDaysAgo;
201
- summary += `\n- 7日前 (${sd.date || '不明'}, data[${sd.index}]): ${formatPrice(sd.close)}${fmtChange(sd.changePct)}`;
202
- }
203
-
204
- if (keyPoints.thirtyDaysAgo) {
205
- const td = keyPoints.thirtyDaysAgo;
206
- summary += `\n- 30日前 (${td.date || '不明'}, data[${td.index}]): ${formatPrice(td.close)}${fmtChange(td.changePct)}`;
207
- }
208
-
209
- if (keyPoints.ninetyDaysAgo) {
210
- const nd = keyPoints.ninetyDaysAgo;
211
- summary += `\n- 90日前 (${nd.date || '不明'}, data[${nd.index}]): ${formatPrice(nd.close)}${fmtChange(nd.changePct)}`;
229
+ const tfType = timeframe ?? '';
230
+ summary += `\n- 最新 (${today.date || '不明'}, data[${today.index}]): ${formatPrice(today.close)}`;
231
+
232
+ // 本数が 90 本に満たないとき ninetyDaysAgo は最古の足を指すので、ラベルは添字の差から付け、同じ足は 2 度出さない。
233
+ const shown = new Set([today.index]);
234
+ for (const point of [keyPoints.sevenDaysAgo, keyPoints.thirtyDaysAgo, keyPoints.ninetyDaysAgo]) {
235
+ if (!point || shown.has(point.index)) continue;
236
+ shown.add(point.index);
237
+ const label = barsAgoLabel(today.index - point.index, tfType);
238
+ summary += `\n- ${label} (${point.date || '不明'}, data[${point.index}]): ${formatPrice(point.close)}${fmtChange(point.changePct)}`;
212
239
  }
213
240
 
214
241
  if (volumeStats) {
215
242
  // 出来高の単位は pair の base 通貨から導出する(規約元6ツール・OBV と同じ書式)。
216
243
  const baseCcy = (pair ?? '').split('_')[0]?.toUpperCase() ?? '';
244
+ const per = perBarLabel(tfType);
217
245
  summary += '\n\n【出来高推移】';
218
- summary += `\n- 直近7日間の平均: ${volumeStats.recent7DaysAvg.toFixed(0)} ${baseCcy}/日`;
219
- summary += `\n- その前7日間の平均: ${volumeStats.previous7DaysAvg.toFixed(0)} ${baseCcy}/日`;
246
+ summary += `\n- 直近${barCountLabel(7, tfType)}の平均: ${volumeStats.recent7DaysAvg.toFixed(0)} ${baseCcy}${per}`;
247
+ summary += `\n- その前${barCountLabel(7, tfType)}の平均: ${volumeStats.previous7DaysAvg.toFixed(0)} ${baseCcy}${per}`;
220
248
  if (typeof volumeStats.last30DaysAvg === 'number') {
221
- summary += `\n- 過去30日間の平均: ${volumeStats.last30DaysAvg.toFixed(0)} ${baseCcy}/日`;
249
+ summary += `\n- 過去${barCountLabel(30, tfType)}の平均: ${volumeStats.last30DaysAvg.toFixed(0)} ${baseCcy}${per}`;
222
250
  }
223
251
  if (volumeStats.changePct === null) {
224
- summary += '\n- 出来高変化率: N/A(前7日間の出来高ゼロ)';
252
+ summary += `\n- 出来高変化率: N/A(その前${barCountLabel(7, tfType)}の出来高ゼロ)`;
225
253
  } else {
226
254
  summary += `\n- 出来高変化率: ${volumeStats.changePct >= 0 ? '+' : ''}${volumeStats.changePct}%`;
227
255
  }
@@ -3,9 +3,14 @@
3
3
  export const RSI_PERIOD = 14;
4
4
  export const RSI_OVERBOUGHT = 70;
5
5
  export const RSI_OVERSOLD = 30;
6
+ export const RSI_MIDLINE = 50;
6
7
 
7
8
  export const BB_PERIOD = 20;
8
9
  export const BB_STDDEV = 2;
10
+ export const BB_WIDTH_RANK_WINDOW = 120;
11
+ export const BB_WIDTH_SQUEEZE_BELOW_PCTL = 20;
12
+ export const BB_WIDTH_NORMAL_BELOW_PCTL = 80;
13
+ export const BB_WIDTH_EXPANDING_BELOW_PCTL = 95;
9
14
 
10
15
  export const SMA_DEFAULT_PERIOD = 25;
11
16
 
@@ -16,6 +21,8 @@ export const MACD_SIGNAL = 9;
16
21
  export const STOCH_PERIOD = 14;
17
22
  export const STOCH_SMOOTH_K = 3;
18
23
  export const STOCH_SMOOTH_D = 3;
24
+ export const STOCH_OVERBOUGHT = 80;
25
+ export const STOCH_OVERSOLD = 20;
19
26
 
20
27
  export const OBV_SMA_PERIOD = 20;
21
28
  export const OBV_TREND_THRESHOLD = 0.02;
@@ -0,0 +1,179 @@
1
+ import {
2
+ BB_PERIOD,
3
+ BB_STDDEV,
4
+ BB_WIDTH_EXPANDING_BELOW_PCTL,
5
+ BB_WIDTH_NORMAL_BELOW_PCTL,
6
+ BB_WIDTH_RANK_WINDOW,
7
+ BB_WIDTH_SQUEEZE_BELOW_PCTL,
8
+ RSI_MIDLINE,
9
+ RSI_OVERBOUGHT,
10
+ RSI_OVERSOLD,
11
+ STOCH_OVERBOUGHT,
12
+ STOCH_OVERSOLD,
13
+ } from './indicator-config.js';
14
+
15
+ // 値の種類はここだけに置き、スキーマ(src/schema/indicators.ts の z.enum)もここから作る(#436)。
16
+ export const RSI_ZONES = ['oversold', 'below_midline', 'above_midline', 'overbought'] as const;
17
+ export type RsiZone = (typeof RSI_ZONES)[number];
18
+
19
+ export function rsiZone(rsi: number | null | undefined): RsiZone | null {
20
+ if (rsi == null || !Number.isFinite(rsi)) return null;
21
+ if (rsi <= RSI_OVERSOLD) return 'oversold';
22
+ if (rsi >= RSI_OVERBOUGHT) return 'overbought';
23
+ return rsi < RSI_MIDLINE ? 'below_midline' : 'above_midline';
24
+ }
25
+
26
+ // 「反発の可能性」のような先の値動きを示す言葉は付けない(#431)。
27
+ const RSI_ZONE_LABELS: Record<RsiZone, string> = {
28
+ oversold: `売られすぎ圏(${RSI_OVERSOLD}以下)`,
29
+ below_midline: `中立圏(${RSI_MIDLINE}未満)`,
30
+ above_midline: `中立圏(${RSI_MIDLINE}以上)`,
31
+ overbought: `買われすぎ圏(${RSI_OVERBOUGHT}以上)`,
32
+ };
33
+
34
+ export function rsiZoneLabel(rsi: number | null | undefined): string | null {
35
+ const zone = rsiZone(rsi);
36
+ return zone ? RSI_ZONE_LABELS[zone] : null;
37
+ }
38
+
39
+ export const STOCH_ZONES = ['oversold', 'neutral', 'overbought'] as const;
40
+ export type StochZone = (typeof STOCH_ZONES)[number];
41
+
42
+ export function stochZone(k: number | null | undefined): StochZone | null {
43
+ if (k == null || !Number.isFinite(k)) return null;
44
+ if (k >= STOCH_OVERBOUGHT) return 'overbought';
45
+ if (k <= STOCH_OVERSOLD) return 'oversold';
46
+ return 'neutral';
47
+ }
48
+
49
+ const STOCH_ZONE_LABELS: Record<StochZone, string> = {
50
+ oversold: `売られすぎ圏(${STOCH_OVERSOLD}以下)`,
51
+ neutral: '中立圏',
52
+ overbought: `買われすぎ圏(${STOCH_OVERBOUGHT}以上)`,
53
+ };
54
+
55
+ export function stochZoneLabel(zone: StochZone): string {
56
+ return STOCH_ZONE_LABELS[zone];
57
+ }
58
+
59
+ // 上下のバンドは中心から ±BB_STDDEV σ なので、バンドの全幅を 2 × BB_STDDEV で割ると σ になる。
60
+ export function bbZScore(
61
+ close: number | null | undefined,
62
+ middle: number | null | undefined,
63
+ upper: number | null | undefined,
64
+ lower: number | null | undefined,
65
+ ): number | null {
66
+ if (close == null || middle == null || upper == null || lower == null) return null;
67
+ const sigma = (upper - lower) / (2 * BB_STDDEV);
68
+ if (!Number.isFinite(close) || !Number.isFinite(middle) || !(sigma > 0)) return null;
69
+ return (close - middle) / sigma;
70
+ }
71
+
72
+ export const BB_POSITIONS = ['at_lower', 'lower_zone', 'near_middle', 'upper_zone', 'at_upper'] as const;
73
+ export type BbPosition = (typeof BB_POSITIONS)[number];
74
+
75
+ export function bbPosition(zScore: number | null | undefined): BbPosition | null {
76
+ if (zScore == null || !Number.isFinite(zScore)) return null;
77
+ if (zScore >= BB_STDDEV) return 'at_upper';
78
+ if (zScore <= -BB_STDDEV) return 'at_lower';
79
+ if (Math.abs(zScore) <= 1) return 'near_middle';
80
+ return zScore > 0 ? 'upper_zone' : 'lower_zone';
81
+ }
82
+
83
+ const BB_POSITION_LABELS: Record<BbPosition, string> = {
84
+ at_upper: `買われすぎ圏(+${BB_STDDEV}σ以上)`,
85
+ upper_zone: `中心より上(+1σ〜+${BB_STDDEV}σ)`,
86
+ near_middle: '中心付近(±1σ以内)',
87
+ lower_zone: `中心より下(-1σ〜-${BB_STDDEV}σ)`,
88
+ at_lower: `売られすぎ圏(-${BB_STDDEV}σ以下)`,
89
+ };
90
+
91
+ export function bbPositionLabel(position: BbPosition): string {
92
+ return BB_POSITION_LABELS[position];
93
+ }
94
+
95
+ export interface BbWidthRank {
96
+ // 丸める前の値。区切りはこの値で判定し、表示だけ丸める。
97
+ percentile: number;
98
+ sampleSize: number;
99
+ }
100
+
101
+ type Series = ReadonlyArray<number | null | undefined>;
102
+
103
+ // 幅の水準は足の種類で大きく違う(4 時間足は数 %、週足は数十 %)ので、固定値ではなく同じ足の過去の幅と比べる(#437)。
104
+ export function bbWidthRank(
105
+ upper: Series,
106
+ middle: Series,
107
+ lower: Series,
108
+ window: number = BB_WIDTH_RANK_WINDOW,
109
+ ): BbWidthRank | null {
110
+ const n = Math.min(upper.length, middle.length, lower.length);
111
+ const widths: number[] = [];
112
+ for (let i = n - 1; i >= 0 && widths.length < window; i--) {
113
+ const u = upper[i];
114
+ const m = middle[i];
115
+ const l = lower[i];
116
+ const valid = u != null && m != null && l != null && Number.isFinite(u) && Number.isFinite(l) && m > 0;
117
+ if (!valid) {
118
+ if (i === n - 1) return null;
119
+ continue;
120
+ }
121
+ widths.push(((u - l) / m) * 100);
122
+ }
123
+ if (widths.length < BB_PERIOD) return null;
124
+ const current = widths[0];
125
+ const below = widths.filter((w) => w < current).length;
126
+ const equal = widths.filter((w) => w === current).length;
127
+ // 同じ値は半分ずつ数える(幅が一定のとき 50%)。下回る数だけだと、一定の幅がスクイーズに化ける。
128
+ return { percentile: ((below + equal / 2) / widths.length) * 100, sampleSize: widths.length };
129
+ }
130
+
131
+ export const BB_WIDTH_STATES = ['squeeze', 'normal', 'expanding', 'wide'] as const;
132
+ export type BbWidthState = (typeof BB_WIDTH_STATES)[number];
133
+
134
+ export function bbWidthState(rank: BbWidthRank | null | undefined): BbWidthState | null {
135
+ if (rank == null || !Number.isFinite(rank.percentile)) return null;
136
+ if (rank.percentile < BB_WIDTH_SQUEEZE_BELOW_PCTL) return 'squeeze';
137
+ if (rank.percentile < BB_WIDTH_NORMAL_BELOW_PCTL) return 'normal';
138
+ if (rank.percentile < BB_WIDTH_EXPANDING_BELOW_PCTL) return 'expanding';
139
+ return 'wide';
140
+ }
141
+
142
+ const BB_WIDTH_STATE_NAMES: Record<BbWidthState, string> = {
143
+ squeeze: 'スクイーズ',
144
+ normal: '標準',
145
+ expanding: '拡大',
146
+ wide: '大きく拡大',
147
+ };
148
+
149
+ export function bbWidthStateLabel(state: BbWidthState, rank: BbWidthRank): string {
150
+ return `${BB_WIDTH_STATE_NAMES[state]}(直近${rank.sampleSize}本の幅の中で下から${Math.round(rank.percentile)}%)`;
151
+ }
152
+
153
+ export interface IndicatorZones {
154
+ rsi: RsiZone | null;
155
+ stochRsi: StochZone | null;
156
+ bbPosition: BbPosition | null;
157
+ bbWidth: BbWidthState | null;
158
+ }
159
+
160
+ export interface IndicatorZoneInputs {
161
+ close: number | null | undefined;
162
+ rsi: number | null | undefined;
163
+ stochRsiK: number | null | undefined;
164
+ bbMiddle: number | null | undefined;
165
+ bbUpper: number | null | undefined;
166
+ bbLower: number | null | undefined;
167
+ bbSeries: { upper: Series; middle: Series; lower: Series } | null | undefined;
168
+ }
169
+
170
+ // analyze_indicators の本文のラベルと同じ値・同じ関数から出す。
171
+ export function indicatorZones(input: IndicatorZoneInputs): IndicatorZones {
172
+ const { close, rsi, stochRsiK, bbMiddle, bbUpper, bbLower, bbSeries } = input;
173
+ return {
174
+ rsi: rsiZone(rsi),
175
+ stochRsi: stochZone(stochRsiK),
176
+ bbPosition: bbPosition(bbZScore(close, bbMiddle, bbUpper, bbLower)),
177
+ bbWidth: bbSeries ? bbWidthState(bbWidthRank(bbSeries.upper, bbSeries.middle, bbSeries.lower)) : null,
178
+ };
179
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bitbank-lab-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Experimental MCP server for bitbank — botters lab community edition. Market data, technical analysis, charting, and Private API trading tools.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,14 +1,29 @@
1
1
  import type { z } from 'zod';
2
2
  import { nowIso, resolveTz, toDisplayTime } from '../../lib/datetime.js';
3
3
  import {
4
+ barCountLabel,
5
+ barsAgoLabel,
4
6
  formatDeviation,
5
7
  formatExactPrice,
6
8
  formatPercent,
7
9
  formatPriceAtLevel,
8
10
  formatPriceJPY,
9
11
  formatTrendSymbol,
12
+ prevBarChangeLabel,
10
13
  } from '../../lib/formatter.js';
11
- import { ICHIMOKU_SHIFT, RSI_OVERBOUGHT, RSI_OVERSOLD } from '../../lib/indicator-config.js';
14
+ import { ICHIMOKU_SHIFT, RSI_MIDLINE } from '../../lib/indicator-config.js';
15
+ import {
16
+ type BbWidthRank,
17
+ bbPosition,
18
+ bbPositionLabel,
19
+ bbWidthRank,
20
+ bbWidthState,
21
+ bbWidthStateLabel,
22
+ bbZScore,
23
+ rsiZoneLabel,
24
+ stochZone,
25
+ stochZoneLabel,
26
+ } from '../../lib/indicator-zones.js';
12
27
  import { currentCloudSpans, lastCrossover } from '../../lib/indicators.js';
13
28
  import { EPSILON } from '../../lib/math.js';
14
29
  import { prependProvisionalNote } from '../../lib/provisional-bar.js';
@@ -30,7 +45,6 @@ export interface BuildIndicatorsTextInput {
30
45
  trend: string;
31
46
  rsi: number | null;
32
47
  recentRsiFormatted: string[];
33
- rsiUnitLabel: string;
34
48
  macdLine: number | null;
35
49
  macdSignal: number | null;
36
50
  macdHist: number | null;
@@ -49,6 +63,7 @@ export interface BuildIndicatorsTextInput {
49
63
  bbLo: number | null;
50
64
  sigmaZ: number | null;
51
65
  bandWidthPct: number | null;
66
+ bandWidthRank?: BbWidthRank | null;
52
67
  bwTrend: string | null;
53
68
  sigmaHistory: Array<{ off: number; z: number } | null> | null;
54
69
  tenkan: number | null;
@@ -89,7 +104,6 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
89
104
  trend,
90
105
  rsi,
91
106
  recentRsiFormatted,
92
- rsiUnitLabel,
93
107
  macdLine,
94
108
  macdSignal,
95
109
  macdHist,
@@ -108,6 +122,7 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
108
122
  bbLo,
109
123
  sigmaZ,
110
124
  bandWidthPct,
125
+ bandWidthRank = null,
111
126
  bwTrend,
112
127
  sigmaHistory,
113
128
  tenkan,
@@ -136,13 +151,6 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
136
151
  } = input;
137
152
 
138
153
  const vsCurPct = (ref?: number | null) => formatDeviation(close, ref);
139
- const rsiInterp = (val: number | null) => {
140
- if (val == null) return '—';
141
- if (val <= RSI_OVERSOLD) return '売られすぎ圏(反発の可能性)';
142
- if (val < 50) return '弱め(反発余地)';
143
- if (val < RSI_OVERBOUGHT) return '中立〜強め';
144
- return '買われすぎ圏(反落の可能性)';
145
- };
146
154
 
147
155
  const lines: string[] = [];
148
156
  lines.push(`=== ${String(pair).toUpperCase()} ${String(type)} 分析 ===`);
@@ -154,26 +162,20 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
154
162
  lines.push('【総合判定】');
155
163
  const trendText =
156
164
  trend === 'strong_downtrend' ? '強い下降トレンド ⚠️' : trend === 'uptrend' ? '上昇トレンド' : '中立/レンジ';
157
- const rsiHint =
158
- rsi == null
159
- ? '—'
160
- : Number(rsi) <= RSI_OVERSOLD
161
- ? '売られすぎ'
162
- : Number(rsi) >= RSI_OVERBOUGHT
163
- ? '買われすぎ'
164
- : '中立圏';
165
- const bwState =
166
- bandWidthPct == null ? '—' : bandWidthPct < 8 ? 'スクイーズ' : bandWidthPct > 20 ? 'エクスパンション' : '標準';
165
+ const rsiLabel = rsiZoneLabel(rsi) ?? '—';
166
+ const widthState = bbWidthState(bandWidthRank);
167
+ const bwState = widthState && bandWidthRank ? bbWidthStateLabel(widthState, bandWidthRank) : '—';
168
+ const position = bbPosition(sigmaZ);
167
169
  lines.push(` トレンド: ${trendText}`);
168
- lines.push(` 勢い: RSI=${rsi ?? 'n/a'} → ${rsiHint}`);
170
+ lines.push(` 勢い: RSI=${rsi ?? 'n/a'} → ${rsiLabel}`);
169
171
  lines.push(
170
- ` リスク: BB幅=${bandWidthPct != null ? `${bandWidthPct}%` : 'n/a'} → ${bwState}${bwTrend ? `(${bwTrend})` : ''}`,
172
+ ` リスク: BB幅=${bandWidthPct != null ? `${Number(bandWidthPct.toFixed(2))}%` : 'n/a'} → ${bwState}${bwTrend ? `(${bwTrend})` : ''}`,
171
173
  );
172
174
  lines.push('');
173
175
  lines.push('【モメンタム】');
174
- lines.push(` RSI(14): ${rsi ?? 'n/a'} → ${rsiInterp(rsi)}`);
176
+ lines.push(` RSI(14): ${rsi ?? 'n/a'} → ${rsiLabel}`);
175
177
  if (recentRsiFormatted.length >= 2) {
176
- lines.push(` 【RSI推移(直近${recentRsiFormatted.length}${rsiUnitLabel})】`);
178
+ lines.push(` 【RSI推移(直近${barCountLabel(recentRsiFormatted.length, type)})】`);
177
179
  lines.push('');
178
180
  lines.push(` ${recentRsiFormatted.join(' → ')}`);
179
181
  }
@@ -200,19 +202,19 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
200
202
  lines.push('');
201
203
  lines.push('【ボラティリティ(ボリンジャーバンド±2σ)】');
202
204
  lines.push(
203
- ` 現在位置: ${sigmaZ != null ? `${sigmaZ}σ` : 'n/a'} → ${sigmaZ != null ? (sigmaZ <= -1 ? '売られすぎ' : sigmaZ >= 1 ? '買われすぎ' : '中立') : '—'}`,
205
+ ` 現在位置: ${sigmaZ != null ? `${Number(sigmaZ.toFixed(2))}σ` : 'n/a'} → ${position ? bbPositionLabel(position) : '—'}`,
204
206
  );
205
207
  lines.push(` middle: ${formatPriceJPY(bbMid)} (${vsCurPct(bbMid)})`);
206
208
  lines.push(` upper: ${formatPriceJPY(bbUp)} (${vsCurPct(bbUp)})`);
207
209
  lines.push(
208
210
  ` lower: ${formatPriceJPY(bbLo)} (${vsCurPct(bbLo)})${bbLo != null && close != null && Number(bbLo) < Number(close) ? '' : ' ← 現在価格に近い'}`,
209
211
  );
210
- if (bandWidthPct != null) lines.push(` バンド幅: ${bandWidthPct}% → ${bwTrend ?? '—'}`);
212
+ if (bandWidthPct != null) lines.push(` バンド幅: ${Number(bandWidthPct.toFixed(2))}% → ${bwTrend ?? '—'}`);
211
213
  if (sigmaHistory?.[0] && sigmaHistory[1]) {
212
214
  const ago5 = sigmaHistory[0]?.z;
213
215
  const curZ = sigmaHistory[1]?.z;
214
216
  lines.push(' 過去推移:');
215
- if (ago5 != null) lines.push(` ・5日前: ${ago5}σ`);
217
+ if (ago5 != null) lines.push(` ・${barsAgoLabel(5, type)}: ${ago5}σ`);
216
218
  if (curZ != null) lines.push(` ・現在: ${curZ}σ`);
217
219
  }
218
220
  lines.push('');
@@ -244,10 +246,8 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
244
246
  lines.push('【ストキャスティクスRSI】');
245
247
  if (stochK != null && stochD != null) {
246
248
  lines.push(` %K: ${Number(stochK).toFixed(1)} %D: ${Number(stochD).toFixed(1)}`);
247
- const stochZone = Number(stochK) <= 20 ? '売られすぎゾーン' : Number(stochK) >= 80 ? '買われすぎゾーン' : '中立圏';
248
- const stochStrength =
249
- Number(stochK) <= 10 ? '(強い売られすぎ)' : Number(stochK) >= 90 ? '(強い買われすぎ)' : '';
250
- lines.push(` 判定: ${stochZone}${stochStrength}`);
249
+ const zone = stochZone(Number(stochK));
250
+ lines.push(` 判定: ${zone ? stochZoneLabel(zone) : '—'}`);
251
251
  if (stochPrevK != null && stochPrevD != null) {
252
252
  const prevBelow = Number(stochPrevK) < Number(stochPrevD);
253
253
  const curAbove = Number(stochK) > Number(stochD);
@@ -300,7 +300,7 @@ export function buildIndicatorsText(input: BuildIndicatorsTextInput): string {
300
300
  lines.push('');
301
301
  lines.push('【次に確認すべきこと】');
302
302
  lines.push(' ・より詳しく: analyze_bb_snapshot / analyze_ichimoku_snapshot / analyze_sma_snapshot');
303
- lines.push(' ・転換サイン例: RSI>40, MACDヒストグラムのプラ転, 25日線の明確な上抜け');
303
+ lines.push(` ・転換サイン例: RSIの${RSI_MIDLINE}超え, MACDヒストグラムのプラ転, SMA25の明確な上抜け`);
304
304
  lines.push('');
305
305
  lines.push('詳細は structuredContent.data.indicators / chart を参照。');
306
306
  return lines.join('\n');
@@ -313,16 +313,6 @@ function calcDeltaPrev(close: number | null, prev: number | null): { amt: number
313
313
  return { amt, pct };
314
314
  }
315
315
 
316
- function calcDeltaLabel(type: string): string {
317
- const t = String(type ?? '').toLowerCase();
318
- if (t.includes('day')) return '前日比';
319
- if (t.includes('week')) return '前週比';
320
- if (t.includes('month')) return '前月比';
321
- if (t.includes('hour')) return '前時間比';
322
- if (t.includes('min')) return '前足比';
323
- return '前回比';
324
- }
325
-
326
316
  function extractRecentRsi(rsiSeries: unknown[] | null, count: number): (number | null)[] {
327
317
  if (!Array.isArray(rsiSeries) || rsiSeries.length === 0) return [];
328
318
  return rsiSeries.slice(-count).map((v: unknown) => {
@@ -331,16 +321,6 @@ function extractRecentRsi(rsiSeries: unknown[] | null, count: number): (number |
331
321
  });
332
322
  }
333
323
 
334
- function calcRsiUnitLabel(type: string): string {
335
- const t = String(type ?? '').toLowerCase();
336
- if (t.includes('day')) return '日';
337
- if (t.includes('week')) return '週';
338
- if (t.includes('month')) return '月';
339
- if (t.includes('hour')) return '時間';
340
- if (t.includes('min')) return '本';
341
- return '本';
342
- }
343
-
344
324
  function detectDivergence(
345
325
  candles: Array<{ close?: number }>,
346
326
  histSeries: number[] | null,
@@ -366,9 +346,9 @@ function detectDivergence(
366
346
  function calcSmaArrangement(curNum: number, s25n: number, s75n: number, s200n: number): string {
367
347
  const pts: Array<{ label: string; v: number }> = [];
368
348
  if (Number.isFinite(curNum)) pts.push({ label: '価格', v: curNum });
369
- if (Number.isFinite(s25n)) pts.push({ label: '25日', v: s25n });
370
- if (Number.isFinite(s75n)) pts.push({ label: '75日', v: s75n });
371
- if (Number.isFinite(s200n)) pts.push({ label: '200日', v: s200n });
349
+ if (Number.isFinite(s25n)) pts.push({ label: 'SMA25', v: s25n });
350
+ if (Number.isFinite(s75n)) pts.push({ label: 'SMA75', v: s75n });
351
+ if (Number.isFinite(s200n)) pts.push({ label: 'SMA200', v: s200n });
372
352
  if (pts.length < 3) return 'n/a';
373
353
  pts.sort((a, b) => a.v - b.v);
374
354
  return pts.map((p) => p.label).join(' < ');
@@ -396,21 +376,17 @@ function calcBandWidthTrend(bbSeries: {
396
376
 
397
377
  function calcSigmaHistory(
398
378
  candles: Array<{ close?: number }>,
399
- bbSeries: { upper: number[] | null; middle: number[] | null },
379
+ bbSeries: { upper: number[] | null; middle: number[] | null; lower: number[] | null },
400
380
  ): Array<{ off: number; z: number } | null> | null {
401
381
  try {
402
- if (!bbSeries.upper || !bbSeries.middle) return null;
403
- const L = Math.min(candles.length, bbSeries.upper.length, bbSeries.middle.length);
382
+ if (!bbSeries.upper || !bbSeries.middle || !bbSeries.lower) return null;
383
+ const L = Math.min(candles.length, bbSeries.upper.length, bbSeries.middle.length, bbSeries.lower.length);
404
384
  if (L < 6) return null;
405
- const { upper, middle } = bbSeries;
385
+ const { upper, middle, lower } = bbSeries;
406
386
  const idxs = [-6, -1];
407
387
  const vals = idxs.map((off) => {
408
- const c = Number(candles.at(off)?.close ?? NaN);
409
- const m = Number(middle.at(off) ?? NaN);
410
- const u = Number(upper.at(off) ?? NaN);
411
- if (![c, m, u].every(Number.isFinite)) return null;
412
- const z = Number(((2 * (c - m)) / Math.max(EPSILON, u - m)).toFixed(2));
413
- return { off, z };
388
+ const z = bbZScore(candles.at(off)?.close, middle.at(off), upper.at(off), lower.at(off));
389
+ return z == null ? null : { off, z: Number(z.toFixed(2)) };
414
390
  });
415
391
  return vals;
416
392
  } catch {
@@ -489,24 +465,20 @@ export const toolDef: ToolDefinition = {
489
465
  const anchoredTime = date && Number.isFinite(latestTimestamp) ? toDisplayTime(latestTimestamp, effectiveTz) : null;
490
466
  const timeContext = date ? `${anchoredTime ?? date} 時点(終端 date=${date} 指定)` : undefined;
491
467
  const deltaPrev = calcDeltaPrev(close, prev);
492
- const deltaLabel = calcDeltaLabel(type);
468
+ const deltaLabel = prevBarChangeLabel(type);
493
469
  const rsi = ind.RSI_14 ?? null;
494
470
  const rsiSeries = Array.isArray(res?.data?.indicators?.RSI_14_series) ? res.data.indicators.RSI_14_series : null;
495
471
  const recentRsiRaw = extractRecentRsi(rsiSeries, 7);
496
472
  const recentRsiFormatted = recentRsiRaw.map((v) => (v == null ? 'n/a' : Number(v).toFixed(1)));
497
- const rsiUnitLabel = calcRsiUnitLabel(type);
498
473
  const sma25 = ind.SMA_25 ?? null;
499
474
  const sma75 = ind.SMA_75 ?? null;
500
475
  const sma200 = ind.SMA_200 ?? null;
501
476
  const bbMid = ind.BB_middle ?? ind.BB2_middle ?? null;
502
477
  const bbUp = ind.BB_upper ?? ind.BB2_upper ?? null;
503
478
  const bbLo = ind.BB_lower ?? ind.BB2_lower ?? null;
504
- const sigmaZ =
505
- close != null && bbMid != null && bbUp != null && bbUp - bbMid !== 0
506
- ? Number(((2 * (close - bbMid)) / (bbUp - bbMid)).toFixed(2))
507
- : null;
508
- const bandWidthPct =
509
- bbUp != null && bbLo != null && bbMid ? Number((((bbUp - bbLo) / bbMid) * 100).toFixed(2)) : null;
479
+ // 丸めるのは表示だけ。丸めてから区切ると、境目の近くで analyze_bb_snapshot と位置・幅の状態が食い違う。
480
+ const sigmaZ = bbZScore(close, bbMid, bbUp, bbLo);
481
+ const bandWidthPct = bbUp != null && bbLo != null && bbMid ? ((bbUp - bbLo) / bbMid) * 100 : null;
510
482
  const macdLine = ind.MACD_line ?? null;
511
483
  const macdSignal = ind.MACD_signal ?? null;
512
484
  const macdHist = ind.MACD_hist ?? null;
@@ -569,6 +541,7 @@ export const toolDef: ToolDefinition = {
569
541
  middle: series.BB_middle,
570
542
  };
571
543
  const bwTrend = calcBandWidthTrend(bbSeries);
544
+ const bandWidthRank = bbWidthRank(bbSeries.upper ?? [], bbSeries.middle ?? [], bbSeries.lower ?? []);
572
545
  const sigmaHistory = calcSigmaHistory(candles, bbSeries);
573
546
  const cloudThickness = cloudTop != null && cloudBot != null ? cloudTop - cloudBot : null;
574
547
  const cloudThicknessPct =
@@ -600,7 +573,6 @@ export const toolDef: ToolDefinition = {
600
573
  trend,
601
574
  rsi,
602
575
  recentRsiFormatted,
603
- rsiUnitLabel,
604
576
  macdLine,
605
577
  macdSignal,
606
578
  macdHist,
@@ -619,6 +591,7 @@ export const toolDef: ToolDefinition = {
619
591
  bbLo,
620
592
  sigmaZ,
621
593
  bandWidthPct,
594
+ bandWidthRank,
622
595
  bwTrend,
623
596
  sigmaHistory,
624
597
  tenkan,
@@ -1,5 +1,6 @@
1
1
  import type { z } from 'zod';
2
- import { formatExactPrice, formatPriceAtLevel } from '../../lib/formatter.js';
2
+ import { barsAgoLabel, formatExactPrice, formatPriceAtLevel } from '../../lib/formatter.js';
3
+ import { rsiZoneLabel } from '../../lib/indicator-zones.js';
3
4
  import { currentCloudSpans } from '../../lib/indicators.js';
4
5
  import { extractUpstreamWarning, prependWarnings } from '../../lib/warning-propagation.js';
5
6
  import analyzeMarketSignal from '../../tools/analyze_market_signal.js';
@@ -85,18 +86,18 @@ export function buildMarketSignalHandlerText(input: BuildMarketSignalHandlerText
85
86
  const s25 = v.sma25 != null && Number.isFinite(v.sma25) ? formatPriceAtLevel(v.sma25) : 'n/a';
86
87
  const s75 = v.sma75 != null && Number.isFinite(v.sma75) ? formatPriceAtLevel(v.sma75) : 'n/a';
87
88
  const s200 = v.sma200 != null && Number.isFinite(v.sma200) ? formatPriceAtLevel(v.sma200) : 'n/a';
88
- lines.push(`- 短期(25日): ${s25}円(今の価格より ${fmtVs(dev.vs25)} ${dir(dev.vs25)}に位置)`);
89
- lines.push(`- 中期(75日): ${s75}円(今の価格より ${fmtVs(dev.vs75)} ${dir(dev.vs75)}に位置)`);
90
- lines.push(`- 長期(200日): ${s200}円(今の価格より ${fmtVs(dev.vs200)} ${dir(dev.vs200)}に位置)`);
89
+ lines.push(`- 短期(SMA25): ${s25}円(今の価格より ${fmtVs(dev.vs25)} ${dir(dev.vs25)}に位置)`);
90
+ lines.push(`- 中期(SMA75): ${s75}円(今の価格より ${fmtVs(dev.vs75)} ${dir(dev.vs75)}に位置)`);
91
+ lines.push(`- 長期(SMA200): ${s200}円(今の価格より ${fmtVs(dev.vs200)} ${dir(dev.vs200)}に位置)`);
91
92
  const curVal = Number.isFinite(sma.current) ? Number(sma.current) : null;
92
93
  const v25 = Number.isFinite(v.sma25) ? Number(v.sma25) : null;
93
94
  const v75 = Number.isFinite(v.sma75) ? Number(v.sma75) : null;
94
95
  const v200 = Number.isFinite(v.sma200) ? Number(v.sma200) : null;
95
96
  const pts: Array<{ label: string; value: number }> = [];
96
97
  if (curVal != null) pts.push({ label: '価格', value: curVal });
97
- if (v25 != null) pts.push({ label: '25日', value: v25 });
98
- if (v75 != null) pts.push({ label: '75日', value: v75 });
99
- if (v200 != null) pts.push({ label: '200日', value: v200 });
98
+ if (v25 != null) pts.push({ label: 'SMA25', value: v25 });
99
+ if (v75 != null) pts.push({ label: 'SMA75', value: v75 });
100
+ if (v200 != null) pts.push({ label: 'SMA200', value: v200 });
100
101
  if (pts.length >= 3) {
101
102
  const order = [...pts]
102
103
  .sort((a, b) => b.value - a.value)
@@ -112,10 +113,8 @@ export function buildMarketSignalHandlerText(input: BuildMarketSignalHandlerText
112
113
  if (sma.recentCross?.pair === '25/75') {
113
114
  const crossJp = sma.recentCross.type === 'golden_cross' ? 'ゴールデンクロス' : 'デッドクロス';
114
115
  const ago = Number(sma.recentCross.barsAgo ?? 0);
115
- const isDaily = String(type || '').includes('day');
116
- const unit = isDaily ? '日前' : '本前';
117
116
  const verb = sma.recentCross.type === 'golden_cross' ? '上抜け' : '下抜け';
118
- lines.push(`直近クロス: ${ago}${unit} 25日線が75日線を${verb}(${crossJp})`);
117
+ lines.push(`直近クロス: ${barsAgoLabel(ago, String(type || '1day'))} SMA25がSMA75を${verb}(${crossJp})`);
119
118
  }
120
119
  }
121
120
  }
@@ -127,7 +126,7 @@ export function buildMarketSignalHandlerText(input: BuildMarketSignalHandlerText
127
126
  lines.push('【補足指標】');
128
127
  if (rsiVal != null && Number.isFinite(rsiVal)) {
129
128
  const rsiRounded = Number(rsiVal).toFixed(2);
130
- const rsiLabel = rsiVal < 30 ? '売られすぎ' : rsiVal > 70 ? '買われすぎ' : '中立圏';
129
+ const rsiLabel = rsiZoneLabel(rsiVal);
131
130
  lines.push(`RSI(14): ${rsiRounded}(${rsiLabel})`);
132
131
  }
133
132
  const curPx = sma?.current;