kiwoom-mcp-server 0.9.0 → 0.14.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.
package/README.en.md CHANGED
@@ -25,15 +25,22 @@ allowance.
25
25
  |---|---|---|
26
26
  | `search_stock` | Name → code search (KOSPI/KOSDAQ, incl. ETF/ETN) | ka10099 |
27
27
  | `get_stock_price` | Current price / change rate / volume / basic metrics | ka10001 |
28
- | `get_stock_chart` | Daily/weekly/monthly/minute candles (adjusted price) | ka10080~83 |
28
+ | `get_stock_chart` | Daily/weekly/monthly/yearly/minute/tick candles (adjusted price) | ka10079~83, ka10094 |
29
29
  | `get_orderbook` | 10-level ask/bid quotes and sizes | ka10004 |
30
30
  | `get_market_index` | KOSPI/KOSDAQ composite and sector indices | ka20003 |
31
+ | `get_sector_price` | Sector index detail (breadth / 52-week range / intraday trend) | ka20001 |
32
+ | `get_sector_stocks` | Member stocks of a sector with quotes | ka20002 |
31
33
  | `get_ranking` | Top gainers / losers / volume / trading value | ka10027/30/32 |
32
34
  | `get_market_movers` | New highs / new lows / upper & lower limit / surges / plunges | ka10016/17/19 |
35
+ | `get_vi_stocks` | Today's volatility-interruption (VI) triggered stocks (trigger price / disparity / times) | ka10054 |
33
36
  | `get_investor_trend` | Retail / foreign / institutional net-buy trend (period sum + daily) | ka10059, ka10061 |
34
- | `get_etf_info` | ETF tracking index / tax type / quote | ka40002, ka10001 |
37
+ | `get_broker_activity` | Per-stock top-5 buying/selling brokers (member firms) | ka10002 |
38
+ | `get_etf_info` | ETF tracking index / tax type / quote / NAV & disparity | ka40002, ka10001, ka40009 |
39
+ | `get_etf_returns` | ETF period returns (1w/1m/6m/1y) vs a benchmark index | ka40001 |
35
40
  | `get_short_selling` | Per-stock daily short-selling trend (short volume / weight / avg price) | ka10014 |
41
+ | `get_stock_lending` | Securities-lending trend (contracted / repaid / change / balance) — per stock or market-wide | ka10068, ka20068 |
36
42
  | `get_foreign_holding` | Per-stock foreign holding trend (holdings / holding weight / limit-usage rate) | ka10008 |
43
+ | `get_program_trading` | Today's top program-trading net buys / sells (KOSPI/KOSDAQ) | ka90003 |
37
44
 
38
45
  **Watchlist** (interest-stock groups saved in the 영웅문 HTS client — read-only):
39
46
 
package/README.md CHANGED
@@ -23,15 +23,22 @@ Claude Desktop / Claude Code에서 자연어로 국내 주식 시세·차트·
23
23
  |---|---|---|
24
24
  | `search_stock` | 종목명→코드 검색 (코스피/코스닥, ETF/ETN 포함) | ka10099 |
25
25
  | `get_stock_price` | 현재가/등락률/거래량/기본지표 | ka10001 |
26
- | `get_stock_chart` | 일/주/월/분봉 캔들 차트 (수정주가 반영) | ka10080~83 |
26
+ | `get_stock_chart` | 일/주/월/년/분/틱봉 캔들 차트 (수정주가 반영) | ka10079~83, ka10094 |
27
27
  | `get_orderbook` | 10단계 매도/매수 호가·잔량 | ka10004 |
28
28
  | `get_market_index` | 코스피/코스닥 종합·업종 지수 | ka20003 |
29
+ | `get_sector_price` | 업종 지수 현재가 상세 (등락 구성·52주 고저·시간대별 추이) | ka20001 |
30
+ | `get_sector_stocks` | 업종 구성 종목 시세 (현재가·등락률·거래량·고저가) | ka20002 |
29
31
  | `get_ranking` | 상승률/하락률/거래량/거래대금 상위 | ka10027/30/32 |
30
32
  | `get_market_movers` | 신고가/신저가/상한가/하한가/급등/급락 특이 종목 | ka10016/17/19 |
33
+ | `get_vi_stocks` | 당일 VI(변동성완화장치) 발동 종목 (발동가·괴리율·시각) | ka10054 |
31
34
  | `get_investor_trend` | 개인/외국인/기관 순매수 동향 (기간 합계 + 일별) | ka10059, ka10061 |
32
- | `get_etf_info` | ETF 추적지수·과세유형·시세 | ka40002, ka10001 |
35
+ | `get_broker_activity` | 종목별 거래원(증권사) 매수/매도 상위 5 | ka10002 |
36
+ | `get_etf_info` | ETF 추적지수·과세유형·시세·NAV/괴리율 | ka40002, ka10001, ka40009 |
37
+ | `get_etf_returns` | ETF 기간별(1주/1개월/6개월/1년) 수익률 vs 대상지수 | ka40001 |
33
38
  | `get_short_selling` | 종목별 일자별 공매도 추이 (공매도량·비중·평균가) | ka10014 |
39
+ | `get_stock_lending` | 대차거래 추이 (체결·상환·증감·잔고) — 종목별 또는 시장 전체 | ka10068, ka20068 |
34
40
  | `get_foreign_holding` | 종목별 외국인 보유 추이 (보유주식수·보유비중·한도소진률) | ka10008 |
41
+ | `get_program_trading` | 당일 프로그램 매매 순매수/순매도 상위 (코스피/코스닥) | ka90003 |
35
42
 
36
43
  **관심종목** (영웅문 HTS에 저장한 관심 그룹, 읽기 전용):
37
44
 
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { sleep } from "../utils/sleep.js";
3
3
  import { KiwoomApiError } from "./errors.js";
4
- import { accountEvaluationResponseSchema, allIndexResponseSchema, dailyChartItemSchema, depositResponseSchema, etfInfoResponseSchema, foreignHoldingResponseSchema, investorDailyItemSchema, investorTotalItemSchema, limitStockItemSchema, minuteChartItemSchema, newHighLowItemSchema, orderbookResponseSchema, pendingOrdersResponseSchema, priceChangeRankItemSchema, priceJumpItemSchema, realizedPnlResponseSchema, shortSellingResponseSchema, stockInfoResponseSchema, stockListResponseSchema, themeGroupsResponseSchema, tradingJournalResponseSchema, themeStocksResponseSchema, transactionsResponseSchema, valueRankItemSchema, volumeRankItemSchema, watchlistGroupDetailResponseSchema, watchlistGroupsResponseSchema, } from "./types.js";
4
+ import { accountEvaluationResponseSchema, allIndexResponseSchema, brokerActivityResponseSchema, dailyChartItemSchema, depositResponseSchema, etfInfoResponseSchema, etfNavItemSchema, etfReturnItemSchema, foreignHoldingResponseSchema, investorDailyItemSchema, investorTotalItemSchema, lendingTrendResponseSchema, limitStockItemSchema, minuteChartItemSchema, newHighLowItemSchema, orderbookResponseSchema, pendingOrdersResponseSchema, priceChangeRankItemSchema, priceJumpItemSchema, programTradeItemSchema, realizedPnlResponseSchema, sectorPriceResponseSchema, sectorStocksResponseSchema, shortSellingResponseSchema, stockInfoResponseSchema, stockListResponseSchema, themeGroupsResponseSchema, tradingJournalResponseSchema, themeStocksResponseSchema, transactionsResponseSchema, valueRankItemSchema, viStockItemSchema, volumeRankItemSchema, watchlistGroupDetailResponseSchema, watchlistGroupsResponseSchema, } from "./types.js";
5
5
  const STOCK_INFO_PATH = "/api/dostk/stkinfo";
6
6
  const ACCOUNT_PATH = "/api/dostk/acnt";
7
7
  const CHART_PATH = "/api/dostk/chart";
@@ -13,6 +13,7 @@ const WATCHLIST_PATH = "/api/dostk/watchlist";
13
13
  const THEME_PATH = "/api/dostk/thme";
14
14
  const SHORT_PATH = "/api/dostk/shsa";
15
15
  const FOREIGN_PATH = "/api/dostk/frgnistt";
16
+ const SLB_PATH = "/api/dostk/slb";
16
17
  /** Pulls an array out of an already-envelope-checked response body. */
17
18
  function parseArray(json, key, itemSchema) {
18
19
  const value = json[key];
@@ -136,11 +137,13 @@ const CHART_TRS = {
136
137
  day: { apiId: "ka10081", arrayKey: "stk_dt_pole_chart_qry" },
137
138
  week: { apiId: "ka10082", arrayKey: "stk_stk_pole_chart_qry" },
138
139
  month: { apiId: "ka10083", arrayKey: "stk_mth_pole_chart_qry" },
140
+ year: { apiId: "ka10094", arrayKey: "stk_yr_pole_chart_qry" },
139
141
  };
140
142
  /**
141
- * ka10081/82/83 일·주·월봉newest first; first page (240~600 rows) only,
142
- * which is plenty for LLM consumption and avoids pagination rate-limit cost.
143
- * upd_stkpc_tp "1" = 수정주가 반영.
143
+ * ka10081/82/83/94 일·주·월·년봉same item shape, array key differs per TR
144
+ * (년봉 rows carry no pred_pre schema defaults cover it). Newest first;
145
+ * first page (년봉 ~30, others 240~600 rows) only, which is plenty for LLM
146
+ * consumption and avoids pagination rate-limit cost. upd_stkpc_tp "1" = 수정주가 반영.
144
147
  */
145
148
  export async function fetchDailyChart(client, stockCode, period, baseDate) {
146
149
  const { apiId, arrayKey } = CHART_TRS[period];
@@ -160,6 +163,19 @@ export async function fetchMinuteChart(client, stockCode, ticScope) {
160
163
  });
161
164
  return parseArray(res.json, "stk_min_pole_chart_qry", minuteChartItemSchema);
162
165
  }
166
+ /**
167
+ * ka10079 틱차트 — tic_scope = 캔들당 틱 수 ("1"|"3"|"5"|"10"|"30"). Row shape는
168
+ * ka10080 분봉과 동일(cntr_tm 포함; top-level last_tic_cnt는 미소비). Newest first,
169
+ * first page (900 rows) only.
170
+ */
171
+ export async function fetchTickChart(client, stockCode, ticScope) {
172
+ const res = await client.call({
173
+ path: CHART_PATH,
174
+ apiId: "ka10079",
175
+ body: { stk_cd: stockCode, tic_scope: ticScope, upd_stkpc_tp: "1" },
176
+ });
177
+ return parseArray(res.json, "stk_tic_chart_qry", minuteChartItemSchema);
178
+ }
163
179
  /** ka10004 주식호가 — 10-level orderbook; levels 2-10 live in the loose passthrough. */
164
180
  export async function fetchOrderbook(client, stockCode) {
165
181
  const res = await client.call({
@@ -178,6 +194,35 @@ export async function fetchAllIndices(client, indsCd) {
178
194
  });
179
195
  return allIndexResponseSchema.parse(res.json).all_inds_idex;
180
196
  }
197
+ /**
198
+ * ka20001/ka20002의 mrkt_tp는 inds_cd 선행 자리에서 유도한다
199
+ * (0xx→"0" 코스피, 1xx→"1" 코스닥, 2xx→"2" 코스피200; mock-probed 2026-07-09).
200
+ * inds_cd 자체는 ka20003의 업종코드 공간을 그대로 쓴다.
201
+ */
202
+ function sectorMarketType(indsCd) {
203
+ return indsCd.startsWith("1") ? "1" : indsCd.startsWith("2") ? "2" : "0";
204
+ }
205
+ /** ka20001 업종현재가 — 업종 지수 스냅샷 + 시간대별 추이. */
206
+ export async function fetchSectorPrice(client, indsCd) {
207
+ const res = await client.call({
208
+ path: SECTOR_PATH,
209
+ apiId: "ka20001",
210
+ body: { mrkt_tp: sectorMarketType(indsCd), inds_cd: indsCd },
211
+ });
212
+ return sectorPriceResponseSchema.parse(res.json);
213
+ }
214
+ /**
215
+ * ka20002 업종별주가 — 업종 구성 종목의 시세. 100행/페이지(종목코드순)이며
216
+ * 첫 페이지만 가져온다; 남은 페이지가 있으면 truncated로 알린다.
217
+ */
218
+ export async function fetchSectorStocks(client, indsCd) {
219
+ const res = await client.call({
220
+ path: SECTOR_PATH,
221
+ apiId: "ka20002",
222
+ body: { mrkt_tp: sectorMarketType(indsCd), inds_cd: indsCd, stex_tp: "1" },
223
+ });
224
+ return { items: sectorStocksResponseSchema.parse(res.json).inds_stkpc, truncated: res.hasNext };
225
+ }
181
226
  /** amt_qty_tp: "1"=금액(백만원), "2"=수량(주) — 순매수(trde_tp "0") 기준. */
182
227
  const INVESTOR_UNIT_CODES = { amount: "1", quantity: "2" };
183
228
  /** ka10061 종목별투자자기관종합 — investor net-buy totals over a date range. */
@@ -277,6 +322,45 @@ export async function fetchEtfInfo(client, stockCode) {
277
322
  });
278
323
  return etfInfoResponseSchema.parse(res.json);
279
324
  }
325
+ /** ka40001의 dt(기간) 코드 — 조회 순서대로 4행 테이블을 만든다. */
326
+ export const ETF_RETURN_PERIODS = [
327
+ { dt: "0", label: "1주" },
328
+ { dt: "1", label: "1개월" },
329
+ { dt: "2", label: "6개월" },
330
+ { dt: "3", label: "1년" },
331
+ ];
332
+ /**
333
+ * ka40001 ETF수익율 — 기간(dt)별 ETF 수익률 + 대상지수 수익률. mock-probed
334
+ * 2026-07-09: etfobjt_idex_cd는 필수(빈값 → 1511 오류)지만 ETF와 대조 검증되지
335
+ * 않는 "벤치마크 지수 선택자"다 — cntr_prft_rt가 그 지수의 기간 수익률로 채워진다.
336
+ * 4개 dt를 순차 호출(같은 TR — 레이트리밋 1.1s 간격)해 기간 순서대로 돌려준다.
337
+ */
338
+ export async function fetchEtfReturns(client, stockCode, benchmarkIndexCode) {
339
+ const rows = [];
340
+ for (const [i, period] of ETF_RETURN_PERIODS.entries()) {
341
+ if (i > 0)
342
+ await sleep(PAGE_INTERVAL_MS);
343
+ const res = await client.call({
344
+ path: ETF_PATH,
345
+ apiId: "ka40001",
346
+ body: { stk_cd: stockCode, etfobjt_idex_cd: benchmarkIndexCode, dt: period.dt },
347
+ });
348
+ rows.push(parseArray(res.json, "etfprft_rt_lst", etfReturnItemSchema)[0] ?? null);
349
+ }
350
+ return rows;
351
+ }
352
+ /**
353
+ * ka40009 ETF NAV 추이 — 최신순 배열(etfnavarray)이지만 행에 시각 필드가 없다.
354
+ * mock에서는 NAV 관련 필드가 전부 빈 문자열 — 호출부는 빈값을 허용해야 한다.
355
+ */
356
+ export async function fetchEtfNav(client, stockCode) {
357
+ const res = await client.call({
358
+ path: ETF_PATH,
359
+ apiId: "ka40009",
360
+ body: { stk_cd: stockCode },
361
+ });
362
+ return parseArray(res.json, "etfnavarray", etfNavItemSchema);
363
+ }
280
364
  /**
281
365
  * ka01300 관심종목 그룹 리스트 조회 — HTS에 저장된 관심종목 그룹 목록 (읽기 전용).
282
366
  * 응답 배열 키는 nofi. 편집(추가/삭제) TR은 키움 REST에 존재하지 않는다.
@@ -356,6 +440,88 @@ export async function fetchForeignHolding(client, stockCode) {
356
440
  });
357
441
  return foreignHoldingResponseSchema.parse(res.json).stk_frgnr;
358
442
  }
443
+ const VI_DIRECTION_CODES = { all: "0", up: "1", down: "2" };
444
+ const VI_TYPE_CODES = { all: "0", static: "1", dynamic: "2" };
445
+ /**
446
+ * ka10054 변동성완화장치(VI) 발동종목 — mock-probed 2026-07-10. 필터 12종 중
447
+ * 거래량/거래대금 필터는 미사용("0"), skip_stk "000000000" = 전종목 포함.
448
+ * stockCode 지정 시 해당 종목의 당일 발동 내역만 (미발동이면 빈 배열).
449
+ */
450
+ export async function fetchViStocks(client, market, direction, viType, stockCode) {
451
+ const res = await client.call({
452
+ path: STOCK_INFO_PATH,
453
+ apiId: "ka10054",
454
+ body: {
455
+ mrkt_tp: RANKING_MARKET_CODES[market],
456
+ bf_mkrt_tp: "0",
457
+ stk_cd: stockCode ?? "",
458
+ motn_tp: VI_TYPE_CODES[viType],
459
+ skip_stk: "000000000",
460
+ trde_qty_tp: "0",
461
+ min_trde_qty: "0",
462
+ max_trde_qty: "0",
463
+ trde_prica_tp: "0",
464
+ min_trde_prica: "0",
465
+ max_trde_prica: "0",
466
+ motn_drc: VI_DIRECTION_CODES[direction],
467
+ stex_tp: "1",
468
+ },
469
+ });
470
+ return parseArray(res.json, "motn_stk", viStockItemSchema);
471
+ }
472
+ /** ka10002 주식거래원 — 상위 5 매도/매수 거래원 (flat 37 fields, mock-probed 2026-07-10). */
473
+ export async function fetchBrokerActivity(client, stockCode) {
474
+ const res = await client.call({
475
+ path: STOCK_INFO_PATH,
476
+ apiId: "ka10002",
477
+ body: { stk_cd: stockCode },
478
+ });
479
+ return brokerActivityResponseSchema.parse(res.json);
480
+ }
481
+ /**
482
+ * ka10068(전체)/ka20068(종목별) 대차거래추이 — securities-lending daily trend.
483
+ * 두 TR은 배열 키(dbrt_trde_trnsn)와 행 구조가 동일하다 (mock-probed 2026-07-10).
484
+ * stockCode 지정 시 ka20068 (all_tp "0" = 입력종목만), 미지정 시 ka10068 시장 전체
485
+ * (all_tp "1" = 전체표시). Rows newest-first.
486
+ */
487
+ export async function fetchLendingTrend(client, stockCode, fromDate, toDate) {
488
+ const res = await client.call(stockCode
489
+ ? {
490
+ path: SLB_PATH,
491
+ apiId: "ka20068",
492
+ body: { stk_cd: stockCode, all_tp: "0", strt_dt: fromDate, end_dt: toDate },
493
+ }
494
+ : {
495
+ path: SLB_PATH,
496
+ apiId: "ka10068",
497
+ body: { all_tp: "1", strt_dt: fromDate, end_dt: toDate },
498
+ });
499
+ return lendingTrendResponseSchema.parse(res.json).dbrt_trde_trnsn;
500
+ }
501
+ /** ka90003만 쓰는 P-접두 시장코드 — 전체(all) 옵션이 없는 TR이다. */
502
+ const PROGRAM_MARKET_CODES = {
503
+ kospi: "P00101",
504
+ kosdaq: "P10102",
505
+ };
506
+ /**
507
+ * ka90003 프로그램순매수상위50 — program-trading net buy/sell top-50 for the day.
508
+ * trde_upper_tp "1"=순매도, "2"=순매수; amt_qty_tp는 투자자 TR과 동일 코드
509
+ * (1=금액 백만원, 2=수량 주)이며 prm_* 필드의 단위가 이를 따른다. 장 시작 전에는
510
+ * rc=0 + 빈 배열이 온다 (mock-probed 2026-07-10 08:30 KST).
511
+ */
512
+ export async function fetchProgramTrades(client, direction, unit, market) {
513
+ const res = await client.call({
514
+ path: STOCK_INFO_PATH,
515
+ apiId: "ka90003",
516
+ body: {
517
+ trde_upper_tp: direction === "net_sell" ? "1" : "2",
518
+ amt_qty_tp: INVESTOR_UNIT_CODES[unit],
519
+ mrkt_tp: PROGRAM_MARKET_CODES[market],
520
+ stex_tp: "1",
521
+ },
522
+ });
523
+ return parseArray(res.json, "prm_netprps_upper_50", programTradeItemSchema);
524
+ }
359
525
  /**
360
526
  * ka10170 당일매매일지요청 — the day's trading journal (per-stock realized P&L). Account-scoped.
361
527
  * Returns the full response (period totals + return_msg) so callers can surface the
@@ -195,6 +195,57 @@ export const allIndexResponseSchema = z.looseObject({
195
195
  ...envelope,
196
196
  all_inds_idex: z.array(indexItemSchema).default([]),
197
197
  });
198
+ // ── ka20001: 업종현재가 (subset) ──
199
+ /** 시간대별 행 (`*_n` suffix). tm_n "999999"/"888888"은 장마감 집계 센티널 — 표시 시 필터. */
200
+ export const sectorTimeRowSchema = z.looseObject({
201
+ tm_n: str(),
202
+ cur_prc_n: str(),
203
+ pred_pre_n: str(),
204
+ flu_rt_n: str(),
205
+ acc_trde_qty_n: str(), // 누적 거래량 (천주)
206
+ });
207
+ export const sectorPriceResponseSchema = z.looseObject({
208
+ ...envelope,
209
+ cur_prc: str(), // 지수 (소수점, 부호 접두)
210
+ pred_pre: str(),
211
+ flu_rt: str(),
212
+ trde_qty: str(), // 천주 (ka20003과 동일 단위)
213
+ trde_prica: str(), // 백만원
214
+ trde_frmatn_stk_num: str(), // 거래형성 종목수
215
+ trde_frmatn_rt: str(), // 거래형성 비율(%), 부호 접두
216
+ open_pric: str(),
217
+ high_pric: str(),
218
+ low_pric: str(),
219
+ upl: str(), // 상한 종목수
220
+ rising: str(),
221
+ stdns: str(), // 보합
222
+ fall: str(),
223
+ lst: str(), // 하한 종목수
224
+ "52wk_hgst_pric": str(),
225
+ "52wk_hgst_pric_dt": str(), // yyyyMMdd
226
+ "52wk_hgst_pric_pre_rt": str(), // 현재가의 52주 최고 대비 등락률
227
+ "52wk_lwst_pric": str(),
228
+ "52wk_lwst_pric_dt": str(),
229
+ "52wk_lwst_pric_pre_rt": str(),
230
+ inds_cur_prc_tm: z.array(sectorTimeRowSchema).default([]),
231
+ });
232
+ // ── ka20002: 업종별주가 (subset) ──
233
+ export const sectorStockItemSchema = z.looseObject({
234
+ stk_cd: str(),
235
+ stk_nm: str(),
236
+ cur_prc: str(),
237
+ pred_pre_sig: str(),
238
+ pred_pre: str(),
239
+ flu_rt: str(),
240
+ now_trde_qty: str(),
241
+ open_pric: str(),
242
+ high_pric: str(),
243
+ low_pric: str(),
244
+ });
245
+ export const sectorStocksResponseSchema = z.looseObject({
246
+ ...envelope,
247
+ inds_stkpc: z.array(sectorStockItemSchema).default([]),
248
+ });
198
249
  // ── ka10059/ka10061: 종목별 투자자·기관 (13-field investor breakdown) ──
199
250
  // amt_qty_tp "1"=금액(백만원), "2"=수량(주) — cross-checked live against volume.
200
251
  const investorFields = {
@@ -259,6 +310,26 @@ export const etfInfoResponseSchema = z.looseObject({
259
310
  etftxon_type: str(), // ETF 과세유형 ("비과세" 등)
260
311
  etntxon_type: str(),
261
312
  });
313
+ // ── ka40001: ETF수익율 (array key etfprft_rt_lst; mock-probed 2026-07-09) ──
314
+ // NOTE: cntr_prft_rt is the period return of the index selected by the
315
+ // etfobjt_idex_cd REQUEST field (not validated against the ETF) — probed:
316
+ // same code → same value regardless of stk_cd; bogus code → "0.00".
317
+ export const etfReturnItemSchema = z.looseObject({
318
+ etfprft_rt: str(), // ETF 기간 수익률(%)
319
+ cntr_prft_rt: str(), // 대상지수(etfobjt_idex_cd) 기간 수익률(%)
320
+ for_netprps_qty: str(), // 외인 순매수량
321
+ orgn_netprps_qty: str(), // 기관 순매수량 (mock: blank)
322
+ });
323
+ // ── ka40009: ETF NAV 추이 (array key etfnavarray, newest first, no time field) ──
324
+ // Rows carry NO timestamp; NAV/괴리율/추적오차 fields arrive blank on mock —
325
+ // only stkcnt/base_pric are populated there. Callers must tolerate blanks.
326
+ export const etfNavItemSchema = z.looseObject({
327
+ nav: str(),
328
+ navpred_pre: str(), // NAV 전일대비
329
+ navflu_rt: str(), // NAV 등락률(%)
330
+ trace_eor_rt: str(), // 추적오차율(%)
331
+ dispty_rt: str(), // 괴리율(%)
332
+ });
262
333
  // ── ka01300/ka01301: 관심종목 그룹 (HTS 저장 그룹, live-verified 2026-07-06) ──
263
334
  // NOTE: array keys are nofi(그룹)/nofj(종목); item fields are terse (gcod/name,
264
335
  // cod2/bgb) and differ from the usual snake_case TRs. The response also carries
@@ -350,6 +421,80 @@ export const foreignHoldingResponseSchema = z.looseObject({
350
421
  ...envelope,
351
422
  stk_frgnr: z.array(foreignHoldingItemSchema).default([]),
352
423
  });
424
+ // ── ka10068(전체)/ka20068(종목별): 대차거래추이 — /api/dostk/slb ──
425
+ // Both TRs share the array key AND the row shape (mock-probed 2026-07-10).
426
+ // 당일 행은 집계 전이라 전부 "0"으로 올 수 있다.
427
+ export const lendingTrendItemSchema = z.looseObject({
428
+ dt: str(), // 일자 yyyyMMdd
429
+ dbrt_trde_cntrcnt: str(), // 대차거래 체결주수 (주)
430
+ dbrt_trde_rpy: str(), // 대차거래 상환주수 (주)
431
+ dbrt_trde_irds: str(), // 대차거래 증감 (주, 부호) = 체결 − 상환
432
+ rmnd: str(), // 잔고주수 (주)
433
+ remn_amt: str(), // 잔고금액 (백만원)
434
+ });
435
+ export const lendingTrendResponseSchema = z.looseObject({
436
+ ...envelope,
437
+ dbrt_trde_trnsn: z.array(lendingTrendItemSchema).default([]),
438
+ });
439
+ // ── ka10054: 변동성완화장치(VI) 발동종목 — /api/dostk/stkinfo ──
440
+ // 정적 VI 행은 dynm_* 필드가 "0"/"0.00"으로 온다; virelis_time "000000" = 미해제.
441
+ export const viStockItemSchema = z.looseObject({
442
+ stk_cd: str(),
443
+ stk_nm: str(),
444
+ acc_trde_qty: str(), // 누적거래량 (주)
445
+ motn_pric: str(), // 발동가격 (원)
446
+ dynm_dispty_rt: str(), // 동적괴리율(%)
447
+ trde_cntr_proc_time: str(), // 매매체결처리시각 HHmmss
448
+ virelis_time: str(), // VI해제시각 HHmmss ("000000" = 미해제)
449
+ viaplc_tp: str(), // VI적용구분 ("정적"/"동적" 등)
450
+ dynm_stdpc: str(), // 동적기준가격 (원)
451
+ static_stdpc: str(), // 정적기준가격 (원)
452
+ static_dispty_rt: str(), // 정적괴리율(%)
453
+ open_pric_pre_flu_rt: str(), // 시가대비등락률(%)
454
+ vimotn_cnt: str(), // VI발동횟수
455
+ });
456
+ // ── ka10002: 주식거래원 — /api/dostk/stkinfo (flat, 상위 5 매도/매수 거래원) ──
457
+ // 수량은 부호 접두 (매도 음수/매수 양수 — 방향 중복이라 표시할 땐 절대값).
458
+ export const brokerActivityResponseSchema = z.looseObject({
459
+ ...envelope,
460
+ stk_cd: str(),
461
+ stk_nm: str(),
462
+ cur_prc: str(), // 현재가 (부호 방향)
463
+ flu_rt: str(), // 등락률(%)
464
+ sel_trde_ori_nm_1: str(), // 매도거래원명1
465
+ sel_trde_qty_1: str(), // 매도거래량1 (주, 부호 접두)
466
+ sel_trde_ori_nm_2: str(),
467
+ sel_trde_qty_2: str(),
468
+ sel_trde_ori_nm_3: str(),
469
+ sel_trde_qty_3: str(),
470
+ sel_trde_ori_nm_4: str(),
471
+ sel_trde_qty_4: str(),
472
+ sel_trde_ori_nm_5: str(),
473
+ sel_trde_qty_5: str(),
474
+ buy_trde_ori_nm_1: str(), // 매수거래원명1
475
+ buy_trde_qty_1: str(), // 매수거래량1 (주, 부호 접두)
476
+ buy_trde_ori_nm_2: str(),
477
+ buy_trde_qty_2: str(),
478
+ buy_trde_ori_nm_3: str(),
479
+ buy_trde_qty_3: str(),
480
+ buy_trde_ori_nm_4: str(),
481
+ buy_trde_qty_4: str(),
482
+ buy_trde_ori_nm_5: str(),
483
+ buy_trde_qty_5: str(),
484
+ });
485
+ // ── ka90003: 프로그램순매수상위50 — /api/dostk/stkinfo ──
486
+ // prm_* 필드의 단위는 요청의 amt_qty_tp를 따른다 (1=금액 백만원, 2=수량 주).
487
+ export const programTradeItemSchema = z.looseObject({
488
+ rank: str(), // 순위
489
+ stk_cd: str(),
490
+ stk_nm: str(),
491
+ cur_prc: str(), // 현재가 (부호 방향)
492
+ flu_rt: str(), // 등락률(%)
493
+ acc_trde_qty: str(), // 누적거래량 (주)
494
+ prm_sell_amt: str(), // 프로그램 매도
495
+ prm_buy_amt: str(), // 프로그램 매수
496
+ prm_netprps_amt: str(), // 프로그램 순매수 (부호)
497
+ });
353
498
  // ── ka10170: 당일매매일지 — /api/dostk/acnt (live-verified 2026-07-07) ──
354
499
  // NOTE: an empty trading day returns ONE all-blank row (not an empty array) — callers
355
500
  // must filter blank rows (empty stk_cd/stk_nm). A base_dt beyond ~2 months returns
package/dist/server.js CHANGED
@@ -2,7 +2,9 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { isIsaEnabled } from "./config.js";
3
3
  import { registerAccountBalanceTool } from "./tools/account-balance.js";
4
4
  import { registerAccountHoldingsTool } from "./tools/account-holdings.js";
5
+ import { registerBrokerActivityTool } from "./tools/broker-activity.js";
5
6
  import { registerEtfInfoTool } from "./tools/etf-info.js";
7
+ import { registerEtfReturnsTool } from "./tools/etf-returns.js";
6
8
  import { registerForeignHoldingTool } from "./tools/foreign-holding.js";
7
9
  import { registerInvestorTrendTool } from "./tools/investor-trend.js";
8
10
  import { registerIsaTaxStatusTool } from "./tools/isa-tax-status.js";
@@ -11,17 +13,21 @@ import { registerMarketMoversTool } from "./tools/market-movers.js";
11
13
  import { registerOrderbookTool } from "./tools/orderbook.js";
12
14
  import { registerPendingOrdersTool } from "./tools/pending-orders.js";
13
15
  import { registerPingTool } from "./tools/ping.js";
16
+ import { registerProgramTradingTool } from "./tools/program-trading.js";
14
17
  import { registerRankingTool } from "./tools/ranking.js";
18
+ import { registerSectorPriceTool, registerSectorStocksTool } from "./tools/sector.js";
15
19
  import { registerShortSellingTool } from "./tools/short-selling.js";
16
20
  import { registerStockChartTool } from "./tools/stock-chart.js";
21
+ import { registerStockLendingTool } from "./tools/stock-lending.js";
17
22
  import { registerStockPriceTool } from "./tools/stock-price.js";
18
23
  import { registerStockSearchTool } from "./tools/stock-search.js";
19
24
  import { registerThemeGroupsTool, registerThemeStocksTool } from "./tools/theme.js";
20
25
  import { registerTradingJournalTool } from "./tools/trading-journal.js";
21
26
  import { registerTransactionsTool } from "./tools/transactions.js";
27
+ import { registerViStocksTool } from "./tools/vi-stocks.js";
22
28
  import { registerWatchlistGroupsTool, registerWatchlistTool } from "./tools/watchlist.js";
23
29
  export const SERVER_NAME = "kiwoom-mcp-server";
24
- export const SERVER_VERSION = "0.9.0";
30
+ export const SERVER_VERSION = "0.14.0";
25
31
  export function createServer() {
26
32
  const server = new McpServer({
27
33
  name: SERVER_NAME,
@@ -34,12 +40,19 @@ export function createServer() {
34
40
  registerStockChartTool(server);
35
41
  registerOrderbookTool(server);
36
42
  registerMarketIndexTool(server);
43
+ registerSectorPriceTool(server);
44
+ registerSectorStocksTool(server);
37
45
  registerRankingTool(server);
38
46
  registerMarketMoversTool(server);
47
+ registerViStocksTool(server);
39
48
  registerInvestorTrendTool(server);
49
+ registerBrokerActivityTool(server);
40
50
  registerEtfInfoTool(server);
51
+ registerEtfReturnsTool(server);
41
52
  registerShortSellingTool(server);
53
+ registerStockLendingTool(server);
42
54
  registerForeignHoldingTool(server);
55
+ registerProgramTradingTool(server);
43
56
  // Watchlist (HTS 저장 관심종목 — read-only; ka01300/ka01301)
44
57
  registerWatchlistGroupsTool(server);
45
58
  registerWatchlistTool(server);
@@ -0,0 +1,57 @@
1
+ import { z } from "zod";
2
+ import { getKiwoomContext } from "../context.js";
3
+ import { fetchBrokerActivity } from "../kiwoom/api.js";
4
+ import { formatKRW, formatNumber, formatPercent, parseKiwoomNumber, parseKiwoomPrice } from "../utils/num.js";
5
+ import { runTool, textResult } from "./helpers.js";
6
+ export function formatBrokerActivity(data, stockCode, modeLabel) {
7
+ // (매수명, 매수량, 매도명, 매도량) 순위 1~5 — 이름이 전부 비면 데이터 없음.
8
+ const slots = [
9
+ [data.buy_trde_ori_nm_1, data.buy_trde_qty_1, data.sel_trde_ori_nm_1, data.sel_trde_qty_1],
10
+ [data.buy_trde_ori_nm_2, data.buy_trde_qty_2, data.sel_trde_ori_nm_2, data.sel_trde_qty_2],
11
+ [data.buy_trde_ori_nm_3, data.buy_trde_qty_3, data.sel_trde_ori_nm_3, data.sel_trde_qty_3],
12
+ [data.buy_trde_ori_nm_4, data.buy_trde_qty_4, data.sel_trde_ori_nm_4, data.sel_trde_qty_4],
13
+ [data.buy_trde_ori_nm_5, data.buy_trde_qty_5, data.sel_trde_ori_nm_5, data.sel_trde_qty_5],
14
+ ];
15
+ const filled = slots.filter(([buyNm, , selNm]) => buyNm || selNm);
16
+ if (filled.length === 0) {
17
+ return `[${modeLabel}] ${stockCode}의 거래원 정보가 없습니다. 종목코드를 확인해 주세요.`;
18
+ }
19
+ const n = parseKiwoomNumber;
20
+ const title = data.stk_nm ? `${data.stk_nm} (${stockCode})` : stockCode;
21
+ const lines = [
22
+ `[${modeLabel}] ${title} 거래원 상위 — 현재가 ${formatKRW(parseKiwoomPrice(data.cur_prc))} (${formatPercent(n(data.flu_rt))})`,
23
+ "",
24
+ "| 순위 | 매수 거래원 | 매수량(주) | 매도 거래원 | 매도량(주) |",
25
+ "|---:|---|---:|---|---:|",
26
+ ];
27
+ filled.forEach(([buyNm, buyQty, selNm, selQty], i) => {
28
+ // 수량 부호는 매수/매도 방향 중복이라 절대값으로 표시.
29
+ const cells = [
30
+ String(i + 1),
31
+ buyNm || "-",
32
+ formatNumber(parseKiwoomPrice(buyQty)),
33
+ selNm || "-",
34
+ formatNumber(parseKiwoomPrice(selQty)),
35
+ ];
36
+ lines.push(`| ${cells.join(" | ")} |`);
37
+ });
38
+ lines.push("", "※ 당일 거래원(증권사)별 누적 매수/매도 수량 상위 5개사입니다.");
39
+ return lines.join("\n");
40
+ }
41
+ export function registerBrokerActivityTool(server) {
42
+ server.registerTool("get_broker_activity", {
43
+ title: "거래원 동향 조회",
44
+ description: "특정 종목의 당일 거래원(증권사)별 매수/매도 상위 5개사를 조회합니다 (키움 ka10002). " +
45
+ "어느 증권사 창구에서 많이 사고팔았는지 보여줍니다. 종목코드를 모르면 search_stock으로 먼저 찾으세요.",
46
+ inputSchema: {
47
+ stock_code: z
48
+ .string()
49
+ .regex(/^\d{6}$/, "6자리 종목코드여야 합니다")
50
+ .describe("조회할 6자리 종목코드"),
51
+ },
52
+ }, async ({ stock_code }) => runTool(async () => {
53
+ const { client, config } = getKiwoomContext();
54
+ const data = await fetchBrokerActivity(client, stock_code);
55
+ return textResult(formatBrokerActivity(data, stock_code, config.modeLabel));
56
+ }));
57
+ }
@@ -1,9 +1,9 @@
1
1
  import { z } from "zod";
2
2
  import { getKiwoomContext } from "../context.js";
3
- import { fetchEtfInfo, fetchStockInfo } from "../kiwoom/api.js";
4
- import { formatKRW, formatPercent, formatQuantity, parseKiwoomNumber, parseKiwoomPrice } from "../utils/num.js";
3
+ import { fetchEtfInfo, fetchEtfNav, fetchStockInfo } from "../kiwoom/api.js";
4
+ import { formatKRW, formatPercent, formatQuantity, formatRatioPercent, formatSigned, parseKiwoomNumber, parseKiwoomPrice, } from "../utils/num.js";
5
5
  import { runTool, textResult } from "./helpers.js";
6
- export function formatEtfInfo(etf, quote, stockCode, modeLabel) {
6
+ export function formatEtfInfo(etf, quote, nav, stockCode, modeLabel) {
7
7
  if (!etf.stk_nm) {
8
8
  return `[${modeLabel}] ${stockCode}의 ETF 정보가 없습니다. ETF 종목코드인지 확인해 주세요.`;
9
9
  }
@@ -16,14 +16,21 @@ export function formatEtfInfo(etf, quote, stockCode, modeLabel) {
16
16
  if (quote) {
17
17
  lines.push(`- 현재가: ${formatKRW(parseKiwoomPrice(quote.cur_prc))} (${formatPercent(parseKiwoomNumber(quote.flu_rt))})`, `- 거래량: ${formatQuantity(parseKiwoomNumber(quote.trde_qty))}`);
18
18
  }
19
+ // ka40009 NAV — 필드가 빈값으로 오는 환경(mock 확인)이 있어 값이 있을 때만 표시.
20
+ const navValue = parseKiwoomPrice(nav?.nav);
21
+ if (nav && navValue !== null) {
22
+ lines.push(`- NAV: ${formatKRW(navValue)} (전일대비 ${formatSigned(parseKiwoomNumber(nav.navpred_pre))}, ` +
23
+ `${formatPercent(parseKiwoomNumber(nav.navflu_rt))})`, `- 괴리율: ${formatPercent(parseKiwoomNumber(nav.dispty_rt))} · ` +
24
+ `추적오차율: ${formatRatioPercent(parseKiwoomNumber(nav.trace_eor_rt))}`);
25
+ }
19
26
  lines.push("", "※ 과세유형은 키움 표기 기준입니다. 매매차익 과세 방식(국내주식형 비과세 vs 배당소득 과세)은 " +
20
- "계좌 유형에 따라 달라질 수 있습니다.");
27
+ "계좌 유형에 따라 달라질 수 있습니다.", "※ 기간별(1주/1개월/6개월/1년) 수익률은 get_etf_returns로 조회할 수 있습니다.");
21
28
  return lines.join("\n");
22
29
  }
23
30
  export function registerEtfInfoTool(server) {
24
31
  server.registerTool("get_etf_info", {
25
32
  title: "ETF 정보 조회",
26
- description: "ETF의 추적지수, 과세유형, 현재 시세를 조회합니다 (키움 ka40002+ka10001). " +
33
+ description: "ETF의 추적지수, 과세유형, 현재 시세, NAV·괴리율을 조회합니다 (키움 ka40002+ka10001+ka40009). " +
27
34
  "종목코드를 모르면 search_stock으로 먼저 찾으세요.",
28
35
  inputSchema: {
29
36
  stock_code: z
@@ -34,11 +41,12 @@ export function registerEtfInfoTool(server) {
34
41
  }, async ({ stock_code }) => runTool(async () => {
35
42
  const { client, config } = getKiwoomContext();
36
43
  const code = stock_code.toUpperCase();
37
- // Different TRs — parallel is fine; the quote is best-effort garnish.
38
- const [etf, quote] = await Promise.all([
44
+ // Different TRs — parallel is fine; quote and NAV are best-effort garnish.
45
+ const [etf, quote, navRows] = await Promise.all([
39
46
  fetchEtfInfo(client, code),
40
47
  fetchStockInfo(client, code).catch(() => null),
48
+ fetchEtfNav(client, code).catch(() => null),
41
49
  ]);
42
- return textResult(formatEtfInfo(etf, quote, code, config.modeLabel));
50
+ return textResult(formatEtfInfo(etf, quote, navRows?.[0] ?? null, code, config.modeLabel));
43
51
  }));
44
52
  }
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { getKiwoomContext } from "../context.js";
3
+ import { ETF_RETURN_PERIODS, fetchEtfInfo, fetchEtfReturns } from "../kiwoom/api.js";
4
+ import { formatPercent, formatSigned, parseKiwoomNumber } from "../utils/num.js";
5
+ import { runTool, textResult } from "./helpers.js";
6
+ import { sectorLabel } from "./sector.js";
7
+ /** ka40001의 etfobjt_idex_cd는 필수 — 지정이 없으면 KOSPI200(201)을 기본 벤치마크로 쓴다. */
8
+ const DEFAULT_BENCHMARK = "201";
9
+ /**
10
+ * 비ETF 가드 안내 (2026-07-10 GUI 테스트 발견 대응): ka40001은 일반 종목 코드에도
11
+ * 수익률을 돌려주므로 ka40002로 선별한다 — 비ETF는 stk_nm은 있지만 추적지수명이
12
+ * 빈값, 존재하지 않는 코드는 둘 다 빈값 (mock-probed 2026-07-10).
13
+ */
14
+ export function formatNonEtfNotice(stockName, stockCode, modeLabel) {
15
+ if (stockName) {
16
+ return (`[${modeLabel}] ${stockName} (${stockCode})은(는) ETF가 아니어서 ETF 기간 수익률을 제공하지 않습니다. ` +
17
+ `일반 종목 시세는 get_stock_price / get_stock_chart를 이용하세요.`);
18
+ }
19
+ return (`[${modeLabel}] ${stockCode}의 ETF 정보를 찾을 수 없습니다. ` +
20
+ `ETF 종목코드인지 확인해 주세요 (search_stock으로 검색 가능).`);
21
+ }
22
+ export function formatEtfReturns(rows, etfName, stockCode, benchmarkCode, modeLabel) {
23
+ const n = parseKiwoomNumber;
24
+ if (rows.every((r) => r === null || n(r.etfprft_rt) === null)) {
25
+ return (`[${modeLabel}] ${stockCode}의 ETF 수익률 데이터가 없습니다. ` +
26
+ `ETF 종목코드인지 확인해 주세요 (search_stock으로 검색 가능).`);
27
+ }
28
+ const title = etfName ? `${etfName} (${stockCode})` : stockCode;
29
+ const lines = [
30
+ `[${modeLabel}] ${title} ETF 기간 수익률`,
31
+ "",
32
+ "| 기간 | ETF 수익률 | 대상지수 수익률 | 외인 순매수량 | 기관 순매수량 |",
33
+ "|---|---:|---:|---:|---:|",
34
+ ];
35
+ for (const [i, period] of ETF_RETURN_PERIODS.entries()) {
36
+ const row = rows[i] ?? null;
37
+ lines.push(`| ${period.label} | ${formatPercent(n(row?.etfprft_rt))} | ${formatPercent(n(row?.cntr_prft_rt))} | ` +
38
+ `${formatSigned(n(row?.for_netprps_qty), 0)} | ${formatSigned(n(row?.orgn_netprps_qty), 0)} |`);
39
+ }
40
+ lines.push("", `※ 대상지수: ${benchmarkCode} (${sectorLabel(benchmarkCode)}) — benchmark_index_code로 변경할 수 ` +
41
+ `있습니다 (get_market_index의 '코드' 값).`);
42
+ return lines.join("\n");
43
+ }
44
+ export function registerEtfReturnsTool(server) {
45
+ server.registerTool("get_etf_returns", {
46
+ title: "ETF 기간 수익률 조회",
47
+ description: "ETF의 기간별(1주/1개월/6개월/1년) 수익률을 대상지수 수익률과 나란히 조회합니다 (키움 ka40001). " +
48
+ `대상지수는 benchmark_index_code로 지정하며 기본값은 ${DEFAULT_BENCHMARK}(KOSPI200)입니다 — ` +
49
+ "코드는 get_market_index의 '코드' 값을 사용하세요 (001 코스피 종합, 101 코스닥 종합 등). " +
50
+ "종목코드를 모르면 search_stock으로 먼저 찾으세요.",
51
+ inputSchema: {
52
+ stock_code: z
53
+ .string()
54
+ .regex(/^[0-9A-Z]{6}$/i, "6자리 종목코드여야 합니다")
55
+ .describe("6자리 ETF 종목코드 (예: 069500)"),
56
+ benchmark_index_code: z
57
+ .string()
58
+ .regex(/^\d{3}$/)
59
+ .optional()
60
+ .describe(`비교할 지수 코드 3자리 (기본값 ${DEFAULT_BENCHMARK} KOSPI200 — get_market_index의 '코드' 값)`),
61
+ },
62
+ }, async ({ stock_code, benchmark_index_code }) => runTool(async () => {
63
+ const { client, config } = getKiwoomContext();
64
+ const code = stock_code.toUpperCase();
65
+ const benchmark = benchmark_index_code ?? DEFAULT_BENCHMARK;
66
+ // Non-ETF guard BEFORE the 4-call loop — best-effort: a flaky ka40002
67
+ // lookup must not block a real ETF, so only a successful blank-index
68
+ // response refuses (and it also saves the 4 wasted ka40001 calls).
69
+ const etf = await fetchEtfInfo(client, code).catch(() => null);
70
+ if (etf && !etf.etfobjt_idex_nm) {
71
+ return textResult(formatNonEtfNotice(etf.stk_nm, code, config.modeLabel));
72
+ }
73
+ const rows = await fetchEtfReturns(client, code, benchmark);
74
+ return textResult(formatEtfReturns(rows, etf?.stk_nm || null, code, benchmark, config.modeLabel));
75
+ }));
76
+ }
@@ -11,21 +11,23 @@ export function formatIndices(items, market, modeLabel) {
11
11
  const lines = [
12
12
  `[${modeLabel}] ${MARKET_LABELS[market]} 업종 지수 (${items.length}개)`,
13
13
  "",
14
- "| 지수 | 현재 | 전일대비 | 등락률 | 상승/보합/하락 |",
15
- "|---|---:|---:|---:|---:|",
14
+ "| 지수 | 코드 | 현재 | 전일대비 | 등락률 | 상승/보합/하락 |",
15
+ "|---|---|---:|---:|---:|---:|",
16
16
  ];
17
17
  for (const item of items) {
18
- lines.push(`| ${item.stk_nm} | ${formatNumber(parseKiwoomPrice(item.cur_prc))} | ` +
18
+ lines.push(`| ${item.stk_nm} | ${item.stk_cd || "-"} | ${formatNumber(parseKiwoomPrice(item.cur_prc))} | ` +
19
19
  `${formatSigned(parseKiwoomNumber(item.pred_pre))} | ${formatPercent(parseKiwoomNumber(item.flu_rt))} | ` +
20
20
  `${parseKiwoomNumber(item.rising) ?? "-"}/${parseKiwoomNumber(item.stdns) ?? "-"}/${parseKiwoomNumber(item.fall) ?? "-"} |`);
21
21
  }
22
+ lines.push("", "※ 업종 상세·구성종목은 get_sector_price / get_sector_stocks에 '코드' 값을 넣어 조회하세요.");
22
23
  return lines.join("\n");
23
24
  }
24
25
  export function registerMarketIndexTool(server) {
25
26
  server.registerTool("get_market_index", {
26
27
  title: "시장 지수 조회",
27
28
  description: "코스피/코스닥 종합지수와 업종별 지수를 조회합니다 (키움 ka20003). " +
28
- "첫 행이 시장 종합지수, 이후는 업종 지수입니다.",
29
+ "첫 행이 시장 종합지수, 이후는 업종 지수입니다. 각 행의 '코드'는 " +
30
+ "get_sector_price / get_sector_stocks의 sector_code로 사용할 수 있습니다.",
29
31
  inputSchema: {
30
32
  market: z
31
33
  .enum(["kospi", "kosdaq"])
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { getKiwoomContext } from "../context.js";
3
+ import { fetchProgramTrades } from "../kiwoom/api.js";
4
+ import { formatNumber, formatPercent, formatSigned, parseKiwoomNumber, parseKiwoomPrice } from "../utils/num.js";
5
+ import { runTool, textResult } from "./helpers.js";
6
+ const DEFAULT_TOP = 20;
7
+ const MAX_TOP = 50;
8
+ const DIRECTION_LABELS = {
9
+ net_buy: "프로그램 순매수 상위",
10
+ net_sell: "프로그램 순매도 상위",
11
+ };
12
+ const MARKET_LABELS = {
13
+ kospi: "코스피",
14
+ kosdaq: "코스닥",
15
+ };
16
+ const UNIT_LABELS = {
17
+ amount: "백만원",
18
+ quantity: "주",
19
+ };
20
+ export function formatProgramTrades(items, direction, unit, market, top, modeLabel) {
21
+ const title = `${MARKET_LABELS[market]} ${DIRECTION_LABELS[direction]}`;
22
+ const shown = items.slice(0, top);
23
+ if (shown.length === 0) {
24
+ return `[${modeLabel}] ${title} 데이터가 없습니다 (장 시작 전이거나 당일 집계 전일 수 있습니다).`;
25
+ }
26
+ const n = parseKiwoomNumber;
27
+ const lines = [
28
+ `[${modeLabel}] ${title} (상위 ${shown.length}종목, 단위: ${UNIT_LABELS[unit]})`,
29
+ "",
30
+ "| 순위 | 종목명 | 코드 | 현재가 | 등락률 | 프로그램 매수 | 프로그램 매도 | 순매수 |",
31
+ "|---:|---|---|---:|---:|---:|---:|---:|",
32
+ ];
33
+ shown.forEach((item, i) => {
34
+ const cells = [
35
+ String(i + 1),
36
+ item.stk_nm,
37
+ item.stk_cd,
38
+ formatNumber(parseKiwoomPrice(item.cur_prc)),
39
+ formatPercent(n(item.flu_rt)),
40
+ formatNumber(n(item.prm_buy_amt)),
41
+ formatNumber(n(item.prm_sell_amt)),
42
+ formatSigned(n(item.prm_netprps_amt), 0),
43
+ ];
44
+ lines.push(`| ${cells.join(" | ")} |`);
45
+ });
46
+ return lines.join("\n");
47
+ }
48
+ export function registerProgramTradingTool(server) {
49
+ server.registerTool("get_program_trading", {
50
+ title: "프로그램 매매 상위 조회",
51
+ description: "당일 프로그램 매매 순매수/순매도 상위 종목을 조회합니다 (키움 ka90003). " +
52
+ "direction: net_buy(순매수, 기본)/net_sell(순매도). unit: amount(금액 백만원, 기본)/" +
53
+ "quantity(수량 주). market: kospi(기본)/kosdaq — 이 TR에는 전체(all) 옵션이 없습니다.",
54
+ inputSchema: {
55
+ direction: z.enum(["net_buy", "net_sell"]).optional().describe("순매수/순매도 (기본값: net_buy)"),
56
+ unit: z.enum(["amount", "quantity"]).optional().describe("금액/수량 기준 (기본값: amount)"),
57
+ market: z.enum(["kospi", "kosdaq"]).optional().describe("시장 구분 (기본값: kospi)"),
58
+ top: z
59
+ .number()
60
+ .int()
61
+ .min(1)
62
+ .max(MAX_TOP)
63
+ .optional()
64
+ .describe(`표시할 종목 수 (기본값 ${DEFAULT_TOP}, 최대 ${MAX_TOP})`),
65
+ },
66
+ }, async ({ direction, unit, market, top }) => runTool(async () => {
67
+ const { client, config } = getKiwoomContext();
68
+ const d = direction ?? "net_buy";
69
+ const u = unit ?? "amount";
70
+ const m = market ?? "kospi";
71
+ const items = await fetchProgramTrades(client, d, u, m);
72
+ return textResult(formatProgramTrades(items, d, u, m, top ?? DEFAULT_TOP, config.modeLabel));
73
+ }));
74
+ }
@@ -0,0 +1,135 @@
1
+ import { z } from "zod";
2
+ import { getKiwoomContext } from "../context.js";
3
+ import { fetchSectorPrice, fetchSectorStocks } from "../kiwoom/api.js";
4
+ import { formatDateDashed } from "../utils/date.js";
5
+ import { formatNumber, formatPercent, formatRatioPercent, formatSigned, parseKiwoomNumber, parseKiwoomPrice, } from "../utils/num.js";
6
+ import { runTool, textResult } from "./helpers.js";
7
+ const DEFAULT_STOCK_LIMIT = 30;
8
+ const MAX_STOCK_LIMIT = 100;
9
+ const TIME_ROWS_SHOWN = 10;
10
+ /** 잘 알려진 업종 코드 라벨 — 전체 코드 목록은 get_market_index로 조회. */
11
+ const SECTOR_LABELS = {
12
+ "001": "코스피 종합",
13
+ "002": "코스피 대형주",
14
+ "101": "코스닥 종합",
15
+ "201": "KOSPI200",
16
+ };
17
+ export const sectorLabel = (code) => SECTOR_LABELS[code] ?? `업종 ${code}`;
18
+ /** "153220" → "15:32:20"; 시각이 아닌 값(장마감 센티널 999999/888888 등)은 null. */
19
+ function formatSectorTime(tm) {
20
+ if (!/^\d{6}$/.test(tm) || Number(tm.slice(0, 2)) > 23)
21
+ return null;
22
+ return `${tm.slice(0, 2)}:${tm.slice(2, 4)}:${tm.slice(4, 6)}`;
23
+ }
24
+ const dashedOr = (yyyymmdd) => /^\d{8}$/.test(yyyymmdd) ? formatDateDashed(yyyymmdd) : "-";
25
+ export function formatSectorPrice(res, sectorCode, modeLabel) {
26
+ const n = parseKiwoomNumber;
27
+ const p = parseKiwoomPrice;
28
+ const index = p(res.cur_prc);
29
+ if (index === null) {
30
+ return (`[${modeLabel}] 업종 ${sectorCode}의 시세 데이터가 없습니다. ` +
31
+ `업종 코드를 확인하세요 (get_market_index의 '코드' 값).`);
32
+ }
33
+ const lines = [
34
+ `[${modeLabel}] 업종 현재가 — ${sectorLabel(sectorCode)} (${sectorCode})`,
35
+ "",
36
+ `지수 ${formatNumber(index)} (전일대비 ${formatSigned(n(res.pred_pre))}, ${formatPercent(n(res.flu_rt))})`,
37
+ `시가 ${formatNumber(p(res.open_pric))} · 고가 ${formatNumber(p(res.high_pric))} · 저가 ${formatNumber(p(res.low_pric))}`,
38
+ `거래량 ${formatNumber(n(res.trde_qty), 0)}천주 · 거래대금 ${formatNumber(n(res.trde_prica), 0)}백만원`,
39
+ `등락 구성: 상한 ${n(res.upl) ?? "-"} · 상승 ${n(res.rising) ?? "-"} · 보합 ${n(res.stdns) ?? "-"} · ` +
40
+ `하락 ${n(res.fall) ?? "-"} · 하한 ${n(res.lst) ?? "-"} ` +
41
+ `(거래형성 ${formatNumber(n(res.trde_frmatn_stk_num), 0)}종목, ${formatRatioPercent(p(res.trde_frmatn_rt))})`,
42
+ `52주 최고 ${formatNumber(p(res["52wk_hgst_pric"]))} (${dashedOr(res["52wk_hgst_pric_dt"])}, ` +
43
+ `현재 대비 ${formatPercent(n(res["52wk_hgst_pric_pre_rt"]))}) · ` +
44
+ `최저 ${formatNumber(p(res["52wk_lwst_pric"]))} (${dashedOr(res["52wk_lwst_pric_dt"])}, ` +
45
+ `현재 대비 ${formatPercent(n(res["52wk_lwst_pric_pre_rt"]))})`,
46
+ ];
47
+ const timeRows = [];
48
+ for (const row of res.inds_cur_prc_tm) {
49
+ const time = formatSectorTime(row.tm_n);
50
+ if (time)
51
+ timeRows.push({ time, row });
52
+ if (timeRows.length >= TIME_ROWS_SHOWN)
53
+ break;
54
+ }
55
+ if (timeRows.length > 0) {
56
+ lines.push("", `시간대별 추이 (최근 ${timeRows.length}건)`, "", "| 시각 | 지수 | 전일대비 | 등락률 | 누적거래량(천주) |", "|---|---:|---:|---:|---:|");
57
+ for (const { time, row } of timeRows) {
58
+ lines.push(`| ${time} | ${formatNumber(p(row.cur_prc_n))} | ${formatSigned(n(row.pred_pre_n))} | ` +
59
+ `${formatPercent(n(row.flu_rt_n))} | ${formatNumber(n(row.acc_trde_qty_n), 0)} |`);
60
+ }
61
+ }
62
+ lines.push("", "※ 구성 종목별 시세는 get_sector_stocks에 같은 업종 코드를 넣어 조회하세요.");
63
+ return lines.join("\n");
64
+ }
65
+ export function formatSectorStocks(items, truncated, sectorCode, limit, modeLabel) {
66
+ if (items.length === 0) {
67
+ return (`[${modeLabel}] ${sectorLabel(sectorCode)} (${sectorCode})의 구성 종목이 없습니다. ` +
68
+ `업종 코드를 확인하세요 (get_market_index의 '코드' 값).`);
69
+ }
70
+ const n = parseKiwoomNumber;
71
+ const p = parseKiwoomPrice;
72
+ const shown = items.slice(0, limit);
73
+ const lines = [
74
+ `[${modeLabel}] 업종별 주가 — ${sectorLabel(sectorCode)} (${sectorCode}), ${shown.length}종목 (종목코드순)`,
75
+ "",
76
+ "| 종목명 | 코드 | 현재가 | 전일대비 | 등락률 | 거래량 | 고가 | 저가 |",
77
+ "|---|---|---:|---:|---:|---:|---:|---:|",
78
+ ];
79
+ for (const item of shown) {
80
+ lines.push(`| ${item.stk_nm || "-"} | ${item.stk_cd || "-"} | ${formatNumber(p(item.cur_prc), 0)} | ` +
81
+ `${formatSigned(n(item.pred_pre), 0)} | ${formatPercent(n(item.flu_rt))} | ` +
82
+ `${formatNumber(n(item.now_trde_qty), 0)} | ${formatNumber(p(item.high_pric), 0)} | ` +
83
+ `${formatNumber(p(item.low_pric), 0)} |`);
84
+ }
85
+ const notes = [];
86
+ if (items.length > shown.length) {
87
+ notes.push(`※ 첫 ${shown.length}종목만 표시했습니다 (limit으로 최대 ${MAX_STOCK_LIMIT}개까지 조정 가능).`);
88
+ }
89
+ if (truncated) {
90
+ notes.push("※ 구성 종목이 더 있습니다 — 이 조회는 첫 페이지(종목코드순 100종목)만 가져옵니다.");
91
+ }
92
+ if (notes.length > 0)
93
+ lines.push("", ...notes);
94
+ return lines.join("\n");
95
+ }
96
+ const sectorCodeSchema = z
97
+ .string()
98
+ .regex(/^\d{3}$/)
99
+ .describe("업종 코드 3자리 (예: 001 코스피 종합, 101 코스닥 종합 — get_market_index의 '코드' 값)");
100
+ export function registerSectorPriceTool(server) {
101
+ server.registerTool("get_sector_price", {
102
+ title: "업종 현재가 조회",
103
+ description: "업종(섹터) 지수의 현재가 상세를 조회합니다 (키움 ka20001) — 지수·시/고/저가·거래량·" +
104
+ "상승/하락 종목수·52주 고저·시간대별 추이. sector_code는 get_market_index가 보여주는 " +
105
+ "업종 코드입니다 (001 코스피 종합, 002 코스피 대형주, 101 코스닥 종합, 201 KOSPI200 등).",
106
+ inputSchema: {
107
+ sector_code: sectorCodeSchema,
108
+ },
109
+ }, async ({ sector_code }) => runTool(async () => {
110
+ const { client, config } = getKiwoomContext();
111
+ const res = await fetchSectorPrice(client, sector_code);
112
+ return textResult(formatSectorPrice(res, sector_code, config.modeLabel));
113
+ }));
114
+ }
115
+ export function registerSectorStocksTool(server) {
116
+ server.registerTool("get_sector_stocks", {
117
+ title: "업종별 종목 시세 조회",
118
+ description: "특정 업종에 속한 종목들의 시세를 조회합니다 (키움 ka20002). 종목코드순 정렬이며 " +
119
+ "첫 페이지(최대 100종목)만 가져옵니다. sector_code는 get_market_index의 업종 코드입니다.",
120
+ inputSchema: {
121
+ sector_code: sectorCodeSchema,
122
+ limit: z
123
+ .number()
124
+ .int()
125
+ .min(1)
126
+ .max(MAX_STOCK_LIMIT)
127
+ .optional()
128
+ .describe(`표시할 종목 수 (기본값 ${DEFAULT_STOCK_LIMIT}, 최대 ${MAX_STOCK_LIMIT})`),
129
+ },
130
+ }, async ({ sector_code, limit }) => runTool(async () => {
131
+ const { client, config } = getKiwoomContext();
132
+ const { items, truncated } = await fetchSectorStocks(client, sector_code);
133
+ return textResult(formatSectorStocks(items, truncated, sector_code, limit ?? DEFAULT_STOCK_LIMIT, config.modeLabel));
134
+ }));
135
+ }
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { getKiwoomContext } from "../context.js";
3
- import { fetchDailyChart, fetchMinuteChart } from "../kiwoom/api.js";
3
+ import { fetchDailyChart, fetchMinuteChart, fetchTickChart } from "../kiwoom/api.js";
4
4
  import { formatDateDashed, todayInKst } from "../utils/date.js";
5
5
  import { formatNumber, parseKiwoomNumber, parseKiwoomPrice } from "../utils/num.js";
6
6
  import { runTool, textResult } from "./helpers.js";
@@ -10,7 +10,7 @@ const PERIOD_LABELS = {
10
10
  day: "일봉",
11
11
  week: "주봉",
12
12
  month: "월봉",
13
- minute: "분봉",
13
+ year: "년봉",
14
14
  };
15
15
  /** "20260703153000" → "2026-07-03 15:30" */
16
16
  function formatMinuteTime(cntrTm) {
@@ -37,13 +37,14 @@ export function formatDailyChart(items, stockCode, period, count, modeLabel) {
37
37
  ];
38
38
  return lines.join("\n");
39
39
  }
40
- export function formatMinuteChart(items, stockCode, ticScope, count, modeLabel) {
40
+ /** 분봉과 틱봉이 같은 행 구조(cntr_tm)를 공유 scopeLabel은 "5분"/"30틱" 형태. */
41
+ export function formatMinuteChart(items, stockCode, scopeLabel, count, modeLabel) {
41
42
  if (items.length === 0) {
42
- return `[${modeLabel}] ${stockCode} 분봉 데이터가 없습니다. 종목코드를 확인해 주세요.`;
43
+ return `[${modeLabel}] ${stockCode} ${scopeLabel}봉 데이터가 없습니다. 종목코드를 확인해 주세요.`;
43
44
  }
44
45
  const shown = items.slice(0, count).reverse();
45
46
  const lines = [
46
- `[${modeLabel}] ${stockCode} ${ticScope}분봉 차트 (최근 ${shown.length}개, 수정주가 반영)`,
47
+ `[${modeLabel}] ${stockCode} ${scopeLabel} 차트 (최근 ${shown.length}개, 수정주가 반영)`,
47
48
  "",
48
49
  "| 시각 | 시가 | 고가 | 저가 | 종가 | 거래량 |",
49
50
  "|---|---:|---:|---:|---:|---:|",
@@ -53,17 +54,18 @@ export function formatMinuteChart(items, stockCode, ticScope, count, modeLabel)
53
54
  }
54
55
  export function registerStockChartTool(server) {
55
56
  server.registerTool("get_stock_chart", {
56
- title: "주식 차트 조회 (일/주/월/분봉)",
57
- description: "종목의 캔들 차트 데이터를 조회합니다 (키움 ka10080~ka10083, 수정주가 반영). " +
58
- "period: day(일봉, 기본)/week(주봉)/month(월봉)/minute(분봉). 분봉은 minute_scope로 " +
59
- "분 단위를 지정합니다. 종목코드를 모르면 search_stock으로 먼저 찾으세요.",
57
+ title: "주식 차트 조회 (일/주/월/년/분/틱봉)",
58
+ description: "종목의 캔들 차트 데이터를 조회합니다 (키움 ka10079~ka10083/ka10094, 수정주가 반영). " +
59
+ "period: day(일봉, 기본)/week(주봉)/month(월봉)/year(년봉)/minute(분봉)/tick(틱봉). " +
60
+ "분봉은 minute_scope로 단위를, 틱봉은 tick_scope로 캔들당 수를 지정합니다. " +
61
+ "종목코드를 모르면 search_stock으로 먼저 찾으세요.",
60
62
  inputSchema: {
61
63
  stock_code: z
62
64
  .string()
63
65
  .regex(/^[0-9A-Z]{6}$/i, "6자리 종목코드여야 합니다")
64
66
  .describe("6자리 종목코드 (예: 005930)"),
65
67
  period: z
66
- .enum(["day", "week", "month", "minute"])
68
+ .enum(["day", "week", "month", "year", "minute", "tick"])
67
69
  .optional()
68
70
  .describe("봉 주기 (기본값: day)"),
69
71
  count: z
@@ -77,15 +79,22 @@ export function registerStockChartTool(server) {
77
79
  .enum(["1", "3", "5", "10", "15", "30", "45", "60"])
78
80
  .optional()
79
81
  .describe("period=minute일 때 분 단위 (기본값: 5)"),
82
+ tick_scope: z
83
+ .enum(["1", "3", "5", "10", "30"])
84
+ .optional()
85
+ .describe("period=tick일 때 캔들당 틱 수 (기본값: 30)"),
80
86
  },
81
- }, async ({ stock_code, period, count, minute_scope }) => runTool(async () => {
87
+ }, async ({ stock_code, period, count, minute_scope, tick_scope }) => runTool(async () => {
82
88
  const { client, config } = getKiwoomContext();
83
89
  const code = stock_code.toUpperCase();
84
90
  const n = count ?? DEFAULT_COUNT;
85
- if (period === "minute") {
86
- const scope = minute_scope ?? "5";
87
- const items = await fetchMinuteChart(client, code, scope);
88
- return textResult(formatMinuteChart(items, code, scope, n, config.modeLabel));
91
+ if (period === "minute" || period === "tick") {
92
+ const isTick = period === "tick";
93
+ const scope = isTick ? (tick_scope ?? "30") : (minute_scope ?? "5");
94
+ const items = isTick
95
+ ? await fetchTickChart(client, code, scope)
96
+ : await fetchMinuteChart(client, code, scope);
97
+ return textResult(formatMinuteChart(items, code, `${scope}${isTick ? "틱" : "분"}`, n, config.modeLabel));
89
98
  }
90
99
  const p = period ?? "day";
91
100
  const items = await fetchDailyChart(client, code, p, todayInKst());
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ import { getKiwoomContext } from "../context.js";
3
+ import { fetchLendingTrend } from "../kiwoom/api.js";
4
+ import { assertDateRange, formatDateDashed, kstDaysAgo, todayInKst } from "../utils/date.js";
5
+ import { formatNumber, formatSigned, parseKiwoomNumber } from "../utils/num.js";
6
+ import { runTool, textResult } from "./helpers.js";
7
+ const DEFAULT_LOOKBACK_DAYS = 30;
8
+ export function formatLendingTrend(rows, query, modeLabel) {
9
+ const scope = query.stockCode ? `종목 ${query.stockCode}` : "시장 전체";
10
+ const period = `${formatDateDashed(query.fromDate)} ~ ${formatDateDashed(query.toDate)}`;
11
+ if (rows.length === 0) {
12
+ return `[${modeLabel}] 대차거래 추이가 없습니다 (${scope}, ${period}).`;
13
+ }
14
+ const n = parseKiwoomNumber;
15
+ const lines = [
16
+ `[${modeLabel}] 대차거래 추이 — ${scope} (${period}, ${rows.length}일)`,
17
+ "",
18
+ "| 일자 | 체결(주) | 상환(주) | 증감(주) | 잔고(주) | 잔고금액(백만원) |",
19
+ "|---|---:|---:|---:|---:|---:|",
20
+ ];
21
+ for (const r of rows) {
22
+ const cells = [
23
+ formatDateDashed(r.dt),
24
+ formatNumber(n(r.dbrt_trde_cntrcnt)),
25
+ formatNumber(n(r.dbrt_trde_rpy)),
26
+ formatSigned(n(r.dbrt_trde_irds), 0),
27
+ formatNumber(n(r.rmnd)),
28
+ formatNumber(n(r.remn_amt)),
29
+ ];
30
+ lines.push(`| ${cells.join(" | ")} |`);
31
+ }
32
+ lines.push("", "※ 증감 = 체결 − 상환. 당일 행은 집계 확정 전이라 0으로 표시될 수 있습니다.");
33
+ return lines.join("\n");
34
+ }
35
+ export function registerStockLendingTool(server) {
36
+ server.registerTool("get_stock_lending", {
37
+ title: "대차거래 추이 조회",
38
+ description: "일자별 대차거래(주식 대여) 추이를 조회합니다 — 체결·상환·증감 주수와 대차잔고, 잔고금액 " +
39
+ "(키움 ka10068/ka20068). stock_code를 지정하면 해당 종목, 생략하면 시장 전체 집계입니다. " +
40
+ "기본 조회 기간은 최근 30일이며 from_date/to_date로 변경할 수 있습니다. " +
41
+ "공매도 흐름과 함께 보려면 get_short_selling을 참고하세요.",
42
+ inputSchema: {
43
+ stock_code: z
44
+ .string()
45
+ .regex(/^\d{6}$/, "6자리 종목코드여야 합니다")
46
+ .optional()
47
+ .describe("6자리 종목코드 (생략 시 시장 전체 대차 추이)"),
48
+ from_date: z
49
+ .string()
50
+ .regex(/^\d{4}-?\d{2}-?\d{2}$/, "yyyy-MM-dd 또는 yyyyMMdd 형식이어야 합니다")
51
+ .optional()
52
+ .describe("조회 시작일 (기본값: 30일 전)"),
53
+ to_date: z
54
+ .string()
55
+ .regex(/^\d{4}-?\d{2}-?\d{2}$/, "yyyy-MM-dd 또는 yyyyMMdd 형식이어야 합니다")
56
+ .optional()
57
+ .describe("조회 종료일 (기본값: 오늘)"),
58
+ },
59
+ }, async ({ stock_code, from_date, to_date }) => runTool(async () => {
60
+ const { client, config } = getKiwoomContext();
61
+ const query = {
62
+ stockCode: stock_code,
63
+ fromDate: (from_date ?? kstDaysAgo(DEFAULT_LOOKBACK_DAYS)).replaceAll("-", ""),
64
+ toDate: (to_date ?? todayInKst()).replaceAll("-", ""),
65
+ };
66
+ assertDateRange(query.fromDate, query.toDate);
67
+ const rows = await fetchLendingTrend(client, query.stockCode, query.fromDate, query.toDate);
68
+ return textResult(formatLendingTrend(rows, query, config.modeLabel));
69
+ }));
70
+ }
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+ import { getKiwoomContext } from "../context.js";
3
+ import { fetchViStocks } from "../kiwoom/api.js";
4
+ import { formatNumber, formatPercent, parseKiwoomNumber, parseKiwoomPrice } from "../utils/num.js";
5
+ import { runTool, textResult } from "./helpers.js";
6
+ const DEFAULT_TOP = 20;
7
+ const MAX_TOP = 50;
8
+ const MARKET_LABELS = {
9
+ all: "전체",
10
+ kospi: "코스피",
11
+ kosdaq: "코스닥",
12
+ };
13
+ const DIRECTION_LABELS = {
14
+ all: "",
15
+ up: "상승 ",
16
+ down: "하락 ",
17
+ };
18
+ const TYPE_LABELS = {
19
+ all: "",
20
+ static: "정적 ",
21
+ dynamic: "동적 ",
22
+ };
23
+ /** "133301" → "13:33:01"; "000000"(미해제)과 그 외 비정상 값은 "-". */
24
+ function formatHms(hms) {
25
+ if (hms.length !== 6 || hms === "000000")
26
+ return "-";
27
+ return `${hms.slice(0, 2)}:${hms.slice(2, 4)}:${hms.slice(4, 6)}`;
28
+ }
29
+ export function formatViStocks(items, market, direction, viType, stockCode, top, modeLabel) {
30
+ const scope = stockCode
31
+ ? `종목 ${stockCode}`
32
+ : `${MARKET_LABELS[market]} ${DIRECTION_LABELS[direction]}${TYPE_LABELS[viType]}`.trimEnd();
33
+ const shown = items.slice(0, top);
34
+ if (shown.length === 0) {
35
+ return `[${modeLabel}] ${scope} VI 발동 내역이 없습니다 (당일 기준).`;
36
+ }
37
+ const n = parseKiwoomNumber;
38
+ const lines = [
39
+ `[${modeLabel}] ${scope} VI 발동 종목 (${shown.length}건)`,
40
+ "",
41
+ "| 종목명 | 코드 | 구분 | 발동가 | 괴리율 | 시가대비 | 발동시각 | 해제시각 | 횟수 |",
42
+ "|---|---|---|---:|---:|---:|---|---|---:|",
43
+ ];
44
+ for (const item of shown) {
45
+ // 정적 VI 행은 dynm_* 필드가 "0"으로 오므로 적용구분에 맞는 괴리율을 고른다.
46
+ const dispty = item.viaplc_tp.includes("동적") ? item.dynm_dispty_rt : item.static_dispty_rt;
47
+ const cells = [
48
+ item.stk_nm,
49
+ item.stk_cd,
50
+ item.viaplc_tp || "-",
51
+ formatNumber(parseKiwoomPrice(item.motn_pric)),
52
+ formatPercent(n(dispty)),
53
+ formatPercent(n(item.open_pric_pre_flu_rt)),
54
+ formatHms(item.trde_cntr_proc_time),
55
+ formatHms(item.virelis_time),
56
+ formatNumber(n(item.vimotn_cnt)),
57
+ ];
58
+ lines.push(`| ${cells.join(" | ")} |`);
59
+ }
60
+ lines.push("", "※ VI(변동성완화장치) = 급등락 시 단일가 매매로 전환되는 안전장치. 해제시각 '-'는 아직 해제되지 않았거나 기록이 없는 경우입니다.");
61
+ return lines.join("\n");
62
+ }
63
+ export function registerViStocksTool(server) {
64
+ server.registerTool("get_vi_stocks", {
65
+ title: "VI 발동 종목 조회",
66
+ description: "당일 변동성완화장치(VI)가 발동된 종목을 조회합니다 — 발동가격·괴리율·시가대비등락률·발동/해제 " +
67
+ "시각·발동횟수 (키움 ka10054). market: all(기본)/kospi/kosdaq, direction: all(기본)/up(상승)/" +
68
+ "down(하락), vi_type: all(기본)/static(정적)/dynamic(동적). stock_code를 지정하면 해당 종목의 " +
69
+ "당일 발동 내역만 조회합니다.",
70
+ inputSchema: {
71
+ market: z.enum(["all", "kospi", "kosdaq"]).optional().describe("시장 구분 (기본값: all)"),
72
+ direction: z.enum(["all", "up", "down"]).optional().describe("발동 방향 (기본값: all)"),
73
+ vi_type: z.enum(["all", "static", "dynamic"]).optional().describe("VI 유형 (기본값: all)"),
74
+ stock_code: z
75
+ .string()
76
+ .regex(/^\d{6}$/, "6자리 종목코드여야 합니다")
77
+ .optional()
78
+ .describe("특정 종목의 발동 내역만 조회 (생략 시 전체)"),
79
+ top: z
80
+ .number()
81
+ .int()
82
+ .min(1)
83
+ .max(MAX_TOP)
84
+ .optional()
85
+ .describe(`표시할 건수 (기본값 ${DEFAULT_TOP}, 최대 ${MAX_TOP})`),
86
+ },
87
+ }, async ({ market, direction, vi_type, stock_code, top }) => runTool(async () => {
88
+ const { client, config } = getKiwoomContext();
89
+ const m = market ?? "all";
90
+ const d = direction ?? "all";
91
+ const t = vi_type ?? "all";
92
+ const items = await fetchViStocks(client, m, d, t, stock_code);
93
+ return textResult(formatViStocks(items, m, d, t, stock_code, top ?? DEFAULT_TOP, config.modeLabel));
94
+ }));
95
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kiwoom-mcp-server",
3
- "version": "0.9.0",
3
+ "version": "0.14.0",
4
4
  "description": "Read-only MCP server exposing the Kiwoom Securities REST API (market data, account inquiry, ISA tax-allowance calculator) to Claude Desktop / Claude Code.",
5
5
  "private": false,
6
6
  "type": "module",