### Clone and Setup Project Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Commands to clone the repository and install dependencies for local development. ```bash git clone https://github.com/koreainvestment/open-trading-api.git cd "open-trading-api/MCP/KIS Code Assistant MCP" ``` ```bash uv sync ``` -------------------------------- ### Manually initialize and run the backtester Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Manual commands for installing dependencies, setting up Lean data, and starting the backend and frontend servers individually. ```bash # Python 의존성 설치 uv sync # Lean 데이터 환경 설정 bash scripts/setup_lean_data.sh # Backend (터미널 1) uv run uvicorn backend.main:app --reload --port 8002 # Frontend (터미널 2) cd frontend npm install npm run dev ``` -------------------------------- ### Manual Server Execution Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/README.md Commands to manually install dependencies and start the backend and frontend services separately. ```bash # Python 의존성 설치 uv sync # Backend (터미널 1) uv run uvicorn backend.main:app --reload --port 8000 # Frontend (터미널 2) cd frontend npm install npm run dev ``` -------------------------------- ### Start the backtester server Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Starts both the backend and frontend services simultaneously. Automatically triggers setup_lean_data.sh if necessary. ```bash cd backtester ./start.sh ``` -------------------------------- ### Execute YAML strategy examples via CLI Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Runs various pre-defined strategy examples using the uv package manager. ```bash uv run python examples/yaml_strategy.py --example basic uv run python examples/yaml_strategy.py --example param_override uv run python examples/yaml_strategy.py --example custom_yaml uv run python examples/yaml_strategy.py --example export uv run python examples/yaml_strategy.py --example bollinger uv run python examples/yaml_strategy.py --example all ``` -------------------------------- ### Install Package Dependencies Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Use these commands to set up the environment for the backtester. ```bash cd backtester uv sync ``` -------------------------------- ### Start the MCP Server Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Execute the shell script to start the MCP server, which will be available at http://127.0.0.1:3846/mcp. ```bash bash scripts/start_mcp.sh # http://127.0.0.1:3846/mcp ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Use these commands to install the uv package manager on Windows, macOS, or Linux. ```bash # Windows (PowerShell) powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # macOS/Linux curl -LsSf https://astral.sh/uv/install.sh | sh # 설치 확인 uv --version # uv 0.x.x ... -> 설치 완료 ``` -------------------------------- ### Verify Docker Installation on Windows Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands to verify the Docker installation on Windows. ```cmd docker --version docker run hello-world ``` -------------------------------- ### Start Strategy Builder Server Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/README.md Executes the startup script to launch both the backend and frontend services simultaneously. ```bash cd strategy_builder ./start.sh ``` -------------------------------- ### Prompt Function Examples Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Examples of input formats for detailed and natural language code generation requests. ```text stock_code: "005930" # 종목코드 (필수) task: "주식 현재가 조회" # 작업 내용 (필수) category: "국내주식" # 카테고리 선택 ``` ```text user_request: "삼성전자 주가 확인하고 싶어" # 자연어 요청 (필수) ``` -------------------------------- ### Install Docker on macOS Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands to install Docker on macOS using Homebrew. ```bash # Homebrew 사용 (권장) brew install --cask docker # 또는 공식 인스톨러 다운로드 # https://www.docker.com/products/docker-desktop/ ``` -------------------------------- ### Install Docker on Linux Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands to install Docker on Ubuntu/Debian systems and add the current user to the docker group. ```bash # 공식 스크립트 사용 (권장) curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh # 사용자를 docker 그룹에 추가 sudo usermod -aG docker $USER ``` -------------------------------- ### Directory Structure Overview Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Displays the file organization of the examples directory. ```text examples/ ├── README.md # 이 파일 ├── basic_backtest.py # 기본 백테스트 ├── rule_builder.py # RuleBuilder DSL ├── yaml_strategy.py # YAML 전략 ├── strategy_generation.py # 프리셋 전략 ├── portfolio_analysis.py # 포트폴리오 ├── optimization.py # 최적화 (실전투자 계좌 권장) ├── expert_strategies.py # Expert 전략 ├── live_trading.py # 실시간 매매 └── output/ # 실행 결과 └─── reports/ # HTML 리포트 예시 ``` -------------------------------- ### Run Server Locally Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Commands to start the server using stdio or HTTP modes. ```bash uv run server.py --stdio ``` ```bash uv run server.py ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Clone the project repository and use uv to synchronize dependencies. ```bash # 저장소 클론 git clone https://github.com/koreainvestment/open-trading-api cd open-trading-api # uv를 사용한 의존성 설치 - 한줄로 끝 uv sync ``` -------------------------------- ### Websocket Domestic Stock Example Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Example script for subscribing to real-time stock quotes using the Websocket API. ```python # 웹소켓 호출 예제 - domestic_stock_examples_ws.py import sys import logging import pandas as pd sys.path.extend(['..', '.']) import kis_auth as ka from domestic_stock_functions_ws import * # 로깅 설정 logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s') logger = logging.getLogger(__name__) # 인증 ka.auth() ka.auth_ws() trenv = ka.getTREnv() # 웹소켓 선언 kws = ka.KISWebSocket(api_url="/tryitout") # 삼성전자, sk하이닉스 실시간 호가 구독 kws.subscribe(request=asking_price_krx, data=["005930", "000660"]) ``` -------------------------------- ### REST API Domestic Stock Example Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Example script for querying current stock prices using the REST API. Requires authentication via kis_auth. ```python # REST API 호출 예제 - domestic_stock_examples.py import sys import logging import pandas as pd sys.path.extend(['..', '.']) import kis_auth as ka from domestic_stock_functions import * # 로깅 설정 logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s') logger = logging.getLogger(__name__) # 인증 ka.auth() trenv = ka.getTREnv() # 삼성전자 현재가 시세 조회 result = inquire_price(env_dv="real", fid_cond_mrkt_div_code="J", fid_input_iscd="005930") print(result) ``` -------------------------------- ### Verify uv Installation Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Commands to locate the uv executable on different operating systems. ```bash which uv # macOS/Linux where uv # Windows ``` -------------------------------- ### Manage Kis Trading MCP Container Lifecycle Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Standard Docker commands to start, stop, restart, or remove the kis-trade-mcp container. ```bash # 컨테이너 시작 docker start kis-trade-mcp # 컨테이너 중지 docker stop kis-trade-mcp # 컨테이너 재시작 docker restart kis-trade-mcp # 컨테이너 제거 docker stop kis-trade-mcp docker rm kis-trade-mcp ``` -------------------------------- ### Configure Configuration Directory Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Create the configuration directory and copy the template file. ```bash # 설정 폴더 생성 및 파일 복사 mkdir -p ~/KIS/config cp kis_devlp.yaml ~/KIS/config/ ``` -------------------------------- ### Run Server with Docker Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Commands to build and run the assistant as a Docker container. ```bash # Docker 이미지 빌드 docker build -t kis-code-assistant-mcp . # 서버 실행 docker run -d -p 8081:8081 --name kis-code-assistant-mcp kis-code-assistant-mcp ``` -------------------------------- ### Execute Sample Scripts via CLI Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Commands to run domestic stock sample scripts using uv for both REST and Websocket implementations. ```bash # 국내주식 샘플 코드 실행 (examples_user/domestic_stock/) uv run python domestic_stock_examples.py # REST 방식 uv run python domestic_stock_examples_ws.py # Websocket 방식 ``` ```bash # 국내주식 > 주식현재가 시세 샘플 코드 실행 (examples_llm/domestic_stock/inquire_price/) uv run python chk_inquire_price.py ``` -------------------------------- ### Execute Strategy Builder and Backtester Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Commands to initialize the strategy builder and backtester environments. ```bash # Strategy Builder (전략 설계 + 시그널) cd strategy_builder ./start.sh # Backtester (백테스팅) cd backtester ./start.sh ``` -------------------------------- ### GET /api/strategies/categories Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Retrieves a list of strategy categories. ```APIDOC ## GET /api/strategies/categories ### Description Retrieves a list of available strategy categories. ### Method GET ### Endpoint /api/strategies/categories ``` -------------------------------- ### GET /api/strategies Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Retrieves a list of available strategies. ```APIDOC ## GET /api/strategies ### Description Retrieves a list of available strategies, including optional parameters for filtering. ### Method GET ### Endpoint /api/strategies ``` -------------------------------- ### Claude Desktop Configuration (Source Clone) Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Alternative configuration for Claude Desktop when running from a local source clone using uv. ```json { "mcpServers": { "kis-code-assistant-mcp": { "command": "{uv 실행 경로}", "args": [ "--directory", "{프로젝트 폴더 경로}/MCP/KIS Code Assistant MCP", "run", "server.py", "--stdio" ] } } } ``` -------------------------------- ### GET /api/symbols/search Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Searches for stock symbols by name or code. ```APIDOC ## GET /api/symbols/search ### Description Searches for stock symbols based on the provided name or code. ### Method GET ### Endpoint /api/symbols/search ``` -------------------------------- ### Project File Structure Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Overview of the project directory layout and key configuration files. ```text KIS Code Assistant MCP/ ├── package.json # NPM 패키지 설정 ├── bin/ │ └── cli.js # npx 실행 진입점 ├── server.py # MCP 서버 메인 파일 ├── data.csv # API 정보 데이터 ├── pyproject.toml # 프로젝트 설정 및 의존성 ├── uv.lock # 의존성 잠금 파일 ├── Dockerfile # Docker 이미지 빌드 파일 ├── README.md # 프로젝트 설명서 ├── .gitignore # Git 무시 파일 목록 ├── .dockerignore # Docker 무시 파일 목록 ├── .python-version # Python 버전 지정 ├── images/ # 프로젝트 이미지 파일들 └── src/ ├── prompts/ │ └── prompt.py # 프롬프트 관련 코드 └── utils/ └── api_searcher.py # API 검색 로직 ``` -------------------------------- ### GET /api/files/templates Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Retrieves a list of available YAML templates. ```APIDOC ## GET /api/files/templates ### Description Retrieves a list of available YAML templates for strategy configuration. ### Method GET ### Endpoint /api/files/templates ``` -------------------------------- ### Run Preset Strategy Backtest in Python Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Executes a backtest using a predefined strategy from the registry. Requires Docker to be running for the LeanClient execution. ```python from kis_backtest import LeanClient, STRATEGY_REGISTRY import kis_backtest.strategies.preset # 10종 전략 자동 등록 # 전략 빌드 (파라미터 오버라이드 가능) schema = STRATEGY_REGISTRY.build("sma_crossover", fast_period=20, slow_period=50) # Lean 코드 생성 from kis_backtest import LeanCodeGenerator generator = LeanCodeGenerator(schema) code = generator.generate( symbols=["005930"], start_date="2024-01-01", end_date="2024-12-31", ) # 백테스트 실행 (Docker 필요) client = LeanClient() result = await client.run_backtest(code) ``` -------------------------------- ### GET /api/market/orderbook/:code Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/README.md Retrieves the orderbook for a specific stock code. ```APIDOC ## GET /api/market/orderbook/:code ### Description Retrieves the orderbook for a specific stock code. ### Method GET ### Endpoint /api/market/orderbook/:code ### Parameters #### Path Parameters - **code** (string) - Required - The stock code to retrieve the orderbook for. ``` -------------------------------- ### GET /api/symbols/{code} Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Retrieves detailed information for a specific stock symbol. ```APIDOC ## GET /api/symbols/{code} ### Description Retrieves detailed information for a specific stock symbol identified by its code. ### Method GET ### Endpoint /api/symbols/{code} ### Parameters #### Path Parameters - **code** (string) - Required - The unique stock symbol code. ``` -------------------------------- ### Troubleshoot Container Issues Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Diagnostic commands for common issues like startup failures, missing environment variables, resource constraints, and network connectivity. ```bash # 로그 확인 docker logs kis-trade-mcp # 환경변수 확인 docker exec kis-trade-mcp env | grep KIS ``` ```bash # 컨테이너 재시작 docker restart kis-trade-mcp # 환경변수 다시 설정하여 실행 docker run -d --name kis-trade-mcp -e KIS_APP_KEY="..." ... ``` ```bash # 메모리 사용량 확인 docker stats kis-trade-mcp # 컨테이너 리소스 제한 설정 docker run -d --name kis-trade-mcp --memory="2g" --cpus="2" ... ``` ```bash # 포트 확인 docker port kis-trade-mcp # 네트워크 연결 테스트 (MCP_ACCESS_TOKEN 필요) curl -H "Authorization: Bearer your_strong_random_token" http://localhost:3000/sse ``` -------------------------------- ### GET /api/strategies Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/README.md Retrieves a list of available strategies, including the builder state. ```APIDOC ## GET /api/strategies ### Description Retrieves a list of available strategies, including the builder state. ### Method GET ### Endpoint /api/strategies ``` -------------------------------- ### Build Docker Image Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands to build the Docker image for the KIS Trading MCP. ```bash # Docker 이미지 빌드 docker build -t kis-trade-mcp . # 또는 태그와 함께 빌드 docker build -t kis-trade-mcp:latest . ``` -------------------------------- ### GET /api/auth/status Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/README.md Checks the current authentication status, including the mode and authentication state. ```APIDOC ## GET /api/auth/status ### Description Checks the current authentication status, including the mode and authentication state. ### Method GET ### Endpoint /api/auth/status ``` -------------------------------- ### POST /api/backtest/run Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Executes a backtest using a preset strategy. ```APIDOC ## POST /api/backtest/run ### Description Executes a backtest using a predefined strategy. ### Method POST ### Endpoint /api/backtest/run ``` -------------------------------- ### Clone the Project Repository Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands to clone the repository and navigate to the MCP directory. ```bash # 프로젝트 클론 git clone https://github.com/koreainvestment/open-trading-api.git cd "open-trading-api/MCP/Kis Trading MCP" ``` -------------------------------- ### Debug Docker Container Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Commands to inspect logs and restart the Docker container if it fails to start. ```bash # 로그 확인 docker logs kis-code-assistant-mcp # 컨테이너 재시작 docker restart kis-code-assistant-mcp ``` -------------------------------- ### Run SMA Crossover Backtest Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Executes a basic SMA crossover backtest for Samsung Electronics. ```bash uv run python examples/basic_backtest.py --example basic ``` -------------------------------- ### Reinstall Dependencies Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Run this command to resolve issues related to missing or corrupted project dependencies. ```bash # 의존성 재설치 uv sync --reinstall ``` -------------------------------- ### Run YAML Strategy Parsing Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Parses and converts YAML-based trading strategies. ```bash uv run python examples/yaml_strategy.py --example all ``` -------------------------------- ### Verify Docker Environment Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Use these commands to verify that the Docker daemon is running and that the required Lean images are present. ```bash docker info # Docker Desktop 실행 상태 확인 docker images | grep lean # Lean 이미지 확인 (첫 실행 시 자동 다운로드) ``` -------------------------------- ### Cursor MCP 서버 실행 및 설정 Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/MCP AI 도구 연결 방법.md Docker 또는 로컬 환경에서 서버를 실행하고 Cursor 설정에 추가하는 방법입니다. ```bash # Docker로 실행하는 경우 docker build -t kis-code-assistant-mcp . docker run -d -p 8081:8081 --name kis-code-assistant-mcp kis-code-assistant-mcp # 또는 로컬에서 직접 실행 uv run server.py ``` ```bash curl http://localhost:8081/health # {"status":"healthy","server":"kis-code-assistant-mcp","version":"0.1.0",...} ``` ```json { "mcpServers": { "kis-code-assistant-mcp": { "url": "http://localhost:8081/mcp" } } } ``` ```json { "mcpServers": { "kis-code-assistant-mcp": { "command": "npx", "args": ["-y", "@koreainvestment/kis-code-assistant-mcp"] } } } ``` -------------------------------- ### Run Portfolio Analysis Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Analyzes the diversification effects of a given portfolio. ```bash uv run python examples/portfolio_analysis.py --example basic ``` -------------------------------- ### Manage strategies with Python API Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Demonstrates loading YAML strategies, overriding parameters, generating Lean code, and exporting DSL strategies to YAML. ```python from kis_backtest.file import StrategyFileLoader, StrategyFileSaver # 1. YAML 파일에서 스키마 로드 schema = StrategyFileLoader.load_as_schema("my_strategy.kis.yaml") # 2. 파라미터 오버라이드 schema = StrategyFileLoader.load_schema_with_params( "my_strategy.kis.yaml", param_overrides={"period": 21, "oversold": 25} ) # 3. YAML 문자열에서 로드 schema = StrategyFileLoader.load_schema_from_string(yaml_content) # 4. Lean 코드 생성 from kis_backtest.codegen import LeanCodeGenerator generator = LeanCodeGenerator(schema) code = generator.generate( symbols=["005930"], start_date="2025-01-01", end_date="2025-12-31", ) # 5. Python DSL을 YAML로 내보내기 from kis_backtest.dsl import RuleBuilder, SMA strategy = RuleBuilder("my_strategy").buy_when(SMA(5) > SMA(20)).build() StrategyFileSaver.save_definition(strategy, "my_strategy.kis.yaml") ``` -------------------------------- ### Configure MCP Client with npx Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Add this configuration to your MCP client (e.g., Claude Desktop, Cursor) to run the assistant via npx. ```json { "mcpServers": { "kis-code-assistant-mcp": { "command": "npx", "args": ["-y", "@koreainvestment/kis-code-assistant-mcp"] } } } ``` -------------------------------- ### LeanClient.run_backtest Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Executes a backtest simulation using generated Lean code. ```APIDOC ## LeanClient.run_backtest(code) ### Description Executes a backtest simulation based on the provided Lean code. Requires a Docker environment to run. ### Parameters - **code** (str) - Required - The generated Lean strategy code to execute. ### Example ```python client = LeanClient() result = await client.run_backtest(code) ``` ``` -------------------------------- ### Initialize API Authentication Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Initialize the authentication module within your Python script. ```python import kis_auth as ka # 실전투자 인증 ka.auth(svr="prod", product="01") # 모의투자: svr="vps" ``` -------------------------------- ### POST /api/backtest/run-custom Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Executes a backtest using a custom YAML or strategy configuration. ```APIDOC ## POST /api/backtest/run-custom ### Description Executes a backtest using a custom YAML configuration or strategy definition. ### Method POST ### Endpoint /api/backtest/run-custom ``` -------------------------------- ### Monitor Logs and Performance Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands for retrieving container logs and monitoring system resource usage. ```bash # 전체 로그 docker logs kis-trade-mcp # 최근 100줄 docker logs --tail 100 kis-trade-mcp # 실시간 로그 docker logs -f kis-trade-mcp # 특정 시간대 로그 docker logs --since "2024-01-01T00:00:00" kis-trade-mcp ``` ```bash # 컨테이너 리소스 사용량 docker stats kis-trade-mcp # 컨테이너 상세 정보 docker inspect kis-trade-mcp # 프로세스 확인 docker exec kis-trade-mcp ps aux ``` -------------------------------- ### 환경 설정 및 의존성 설치 Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/examples/README.md 프로젝트 디렉토리로 이동하여 uv를 통해 의존성을 설치합니다. KIS API 인증 정보는 kis_auth.py에 설정해야 합니다. ```bash cd strategy_builder uv sync # KIS API 인증 설정 필요 (kis_auth.py에 설정) ``` -------------------------------- ### Run Live Trading Position Check Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Retrieves and displays current holdings for live trading. ```bash uv run python examples/live_trading.py --example position ``` -------------------------------- ### Verify Server Connectivity Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Commands to check if the local server or Docker container is running correctly. ```bash # 서버가 실행 중인지 확인 curl http://localhost:8081/health # Docker 컨테이너 확인 docker ps --filter "name=kis-code-assistant-mcp" ``` -------------------------------- ### Configure API Credentials Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Configuration structure for the kis_devlp.yaml file to authenticate with real and paper trading environments. ```yaml # 실전투자 my_app: "여기에 실전투자 앱키 입력" my_sec: "여기에 실전투자 앱시크릿 입력" # 모의투자 paper_app: "여기에 모의투자 앱키 입력" paper_sec: "여기에 모의투자 앱시크릿 입력" # HTS ID(KIS Developers 고객 ID) my_htsid: "사용자 HTS ID" # 계좌번호 앞 8자리 my_acct_stock: "증권계좌 8자리" my_acct_future: "선물옵션계좌 8자리" my_paper_stock: "모의투자 증권계좌 8자리" my_paper_future: "모의투자 선물옵션계좌 8자리" # 계좌번호 뒤 2자리 my_prod: "01" ``` -------------------------------- ### POST /api/auth/login Source: https://github.com/koreainvestment/open-trading-api/blob/main/strategy_builder/README.md Performs login to the trading system. Supports 'vps' for mock trading and 'prod' for real trading. ```APIDOC ## POST /api/auth/login ### Description Performs login to the trading system. Supports 'vps' for mock trading and 'prod' for real trading. ### Method POST ### Endpoint /api/auth/login ``` -------------------------------- ### POST /api/strategies/build Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Builds a strategy and returns the corresponding schema. ```APIDOC ## POST /api/strategies/build ### Description Builds a strategy based on provided input and returns the StrategySchema. ### Method POST ### Endpoint /api/strategies/build ``` -------------------------------- ### Run RuleBuilder DSL Backtest Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Executes a backtest using the RuleBuilder domain-specific language. ```bash uv run python examples/rule_builder.py --example basic ``` -------------------------------- ### Check Container Status and Logs Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md Commands to monitor the container status and verify the HTTP server connection. ```bash # 컨테이너 상태 확인 docker ps # 컨테이너 로그 확인 docker logs kis-trade-mcp # 실시간 로그 확인 docker logs -f kis-trade-mcp # HTTP 서버 접근 확인 (MCP_ACCESS_TOKEN 필요) curl -H "Authorization: Bearer your_strong_random_token" http://localhost:3000/sse ``` -------------------------------- ### Configure Claude Desktop Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/Kis Trading MCP/Readme.md JSON configuration for Claude Desktop to connect to the MCP server. The configuration is identical for Linux, Mac, and Windows. ```json { "mcpServers": { "kis-trade-mcp": { "command": "npx", "args": [ "-y", "mcp-remote", "http://localhost:3000/sse", "--header", "Authorization: Bearer your_strong_random_token" ] } } } ``` -------------------------------- ### MCP Tools Reference Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md List of available MCP tools for interacting with the Backtester service. ```APIDOC ## MCP Tools - **list_presets**: Returns a list of 10 preset strategies and their parameter definitions. - **get_preset_yaml**: Returns a preset strategy as a .kis.yaml string. - **validate_yaml**: Validates a YAML strategy file. - **list_indicators**: Returns a list of 80 available technical indicators. - **run_backtest**: Executes a backtest using a YAML strategy (asynchronous, returns a job_id). - **run_preset_backtest**: Executes a backtest using a predefined preset strategy. - **get_backtest_result**: Retrieves backtest results (defaults to waiting for completion; use wait=false for immediate status). - **retry_backtest**: Retries a failed backtest job. - **get_report**: Retrieves a backtest report in JSON or HTML format. ``` -------------------------------- ### kis_devlp.yaml Configuration Template Source: https://github.com/koreainvestment/open-trading-api/blob/main/README.md Template for defining API credentials, HTS ID, and account information. ```yaml # 실전투자 my_app: "여기에 실전투자 앱키 입력" my_sec: "여기에 실전투자 앱시크릿 입력" # 모의투자 paper_app: "여기에 모의투자 앱키 입력" paper_sec: "여기에 모의투자 앱시크릿 입력" # HTS ID(KIS Developers 고객 ID) - 체결통보, 나의 조건 목록 확인 등에 사용됩니다. my_htsid: "사용자 HTS ID" # 계좌번호 앞 8자리 my_acct_stock: "증권계좌 8자리" my_acct_future: "선물옵션계좌 8자리" my_paper_stock: "모의투자 증권계좌 8자리" my_paper_future: "모의투자 선물옵션계좌 8자리" # 계좌번호 뒤 2자리 my_prod: "01" # 종합계좌 # my_prod: "03" # 국내선물옵션 계좌 # my_prod: "08" # 해외선물옵션 계좌 # my_prod: "22" # 개인연금 계좌 # my_prod: "29" # 퇴직연금 계좌 # User-Agent(기본값 사용 권장, 변경 불필요) my_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" ``` -------------------------------- ### Load Strategy from YAML File Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md Loads a strategy schema from a .kis.yaml file, with optional parameter overrides. ```python from kis_backtest import StrategyFileLoader # 파일에서 로드 schema = StrategyFileLoader.load_as_schema("my_strategy.kis.yaml") # 파라미터 오버라이드 schema = StrategyFileLoader.load_schema_with_params( "my_strategy.kis.yaml", param_overrides={"fast_period": 10, "slow_period": 30} ) ``` -------------------------------- ### Claude Desktop 소스 클론 및 설정 Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/MCP AI 도구 연결 방법.md 저장소를 클론하고 uv를 사용하여 로컬에서 MCP 서버를 실행하도록 설정하는 방법입니다. ```bash # 1. 저장소 클론 git clone https://github.com/koreainvestment/open-trading-api.git cd open-trading-api/MCP/KIS\ Code\ Assistant\ MCP # 2. 패키지 설치 uv sync ``` ```json { "mcpServers": { "kis-code-assistant-mcp": { "command": "{uv 실행 경로}", "args": [ "--directory", "{프로젝트 폴더 경로}/MCP/KIS Code Assistant MCP", "run", "server.py", "--stdio" ] } } } ``` -------------------------------- ### kis_devlp.yaml 설정 Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/MCP AI 도구 연결 방법.md 발급받은 API 인증 정보 및 계좌 정보를 입력하는 설정 파일 예시입니다. ```yaml #홈페이지에서 API서비스 신청시 발급 AppKey, AppSecret 값 설정 #실전투자 my_app: "발급받은_실제_APP_KEY" # 한국투자증권에서 발급받은 APP KEY 입력 my_sec: "발급받은_실제_APP_SECRET" # 한국투자증권에서 발급받은 APP SECRET 입력 #모의투자 paper_app: "발급받은_실제_APP_KEY" # 모의투자용 APP KEY (실전과 동일) paper_sec: "발급받은_실제_APP_SECRET" # 모의투자용 APP SECRET (실전과 동일) # HTS ID my_htsid: "실제_HTS_ID" # 한국투자증권 HTS ID 입력 #계좌번호 앞 8자리 my_acct_stock: "실제_계좌번호" # 주식 계좌번호 (예: 50068418) my_acct_future: "실제_계좌번호" # 선물옵션 계좌번호 (주식과 동일 가능) my_paper_stock: "모의투자_계좌번호" # 모의투자 주식 계좌번호 my_paper_future: "모의투자_계좌번호" # 모의투자 선물옵션 계좌번호 (주식과 동일 가능) #계좌번호 뒤 2자리 my_prod: "01" # 01(종합계좌), 03(국내선물옵션), 08(해외선물옵션), 22(개인연금), 29(퇴직연금) ``` -------------------------------- ### Define a strategy using .kis.yaml format Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/README.md This YAML structure defines a SMA crossover strategy with parameters, indicators, and entry/exit conditions. ```yaml version: "1.0" metadata: name: "SMA 골든/데드 크로스" description: "단기 SMA가 장기 SMA 돌파 시 매매" author: "KIS" tags: [trend, sma, crossover] strategy: id: sma_crossover category: trend params: fast_period: default: 20 min: 2 max: 100 type: int slow_period: default: 50 min: 2 max: 200 type: int indicators: - id: sma alias: sma_fast params: period: $fast_period - id: sma alias: sma_slow params: period: $slow_period entry: logic: AND conditions: - indicator: sma_fast operator: cross_above compare_to: sma_slow exit: logic: OR conditions: - indicator: sma_fast operator: cross_below compare_to: sma_slow risk: stop_loss: enabled: true percent: 5.0 take_profit: enabled: true percent: 10.0 ``` -------------------------------- ### Execute MCP via Terminal Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/KIS Code Assistant MCP/README.md Run the assistant directly from the terminal using npx. ```bash npx -y @koreainvestment/kis-code-assistant-mcp ``` -------------------------------- ### Cursor IDE에서 AI를 활용한 API 호출 코드 생성 Source: https://github.com/koreainvestment/open-trading-api/blob/main/MCP/README.MD Cursor IDE 환경에서 MCP를 통해 주가 정보를 가져오는 함수를 AI가 자동으로 생성하도록 유도하는 예시입니다. ```python # AI가 자동으로 API 호출 코드 생성 및 실행 def get_stock_info(code): """삼성전자 주가 정보를 가져오는 함수를 만들어줘""" # MCP를 통해 실제 API 호출 코드가 자동 생성됨 ``` -------------------------------- ### Run Expert Strategies Catalog Source: https://github.com/koreainvestment/open-trading-api/blob/main/backtester/examples/README.md Displays or generates code for 10 expert-level trading strategies. ```bash uv run python examples/expert_strategies.py --story catalog ```