Korea Investment & Securities (KIS) Open API Sample Codes

repository·main·Indexed 23 days ago

https://github.com/koreainvestment/open-trading-api

A sample code repository and quantitative backtesting system for the KIS Open API. It features the kis_backtest Python library for strategy building via RuleBuilder DSL or YAML schemas, a QuantConnect Lean engine integration via Docker, and an MCP server for AI agent interaction. Includes tools for strategy generation, portfolio analysis, and automated trading.

Tokens
33.9K
Snippets
61
Records
166
Agent score
81%

What's inside koreainvestment-open-trading-api

  1. Overview of KIS Backtest Examples

    main

    The backtester/examples directory contains various scripts demonstrating the capabilities of the kis_backtest library.

    FileDescriptionCommandAPI Required
    yaml_strategy.pyYAML strategy parsing/conversion--example allNo
    strategy_generation.pyPreset strategy code generation(no args)No
    expert_strategies.py10 Expert strategies--story catalogNo
    basic_backtest.pyBasic backtesting--example basicYes (Docker)
    rule_builder.pyRuleBuilder DSL backtesting--example basicYes (Docker)
    portfolio_analysis.pyPortfolio diversification analysis--example basicYes
    optimization.pyParameter optimization--example basicYes (Recommended for live accounts)
    live_trading.pyReal-time position lookup--example positionYes
  2. Overview of Korea Investment & Securities (KIS) Open API MCP Server

    main

    The KIS Open API MCP Server allows AI tools like Claude Desktop and Cursor to interact with various financial APIs from Korea Investment & Securities. It provides access to 166 APIs across multiple categories including domestic/overseas stocks, futures/options, bonds, and ETFs/ETNs.

    Supported API Categories:

    • Domestic Stocks (74 APIs): Current price, quotes, charts, balance, orders, rankings, etc.
    • Overseas Stocks (34 APIs): US/Asia stock prices, balance, orders, execution history, etc.
    • Domestic Futures/Options (20 APIs): Quotes, charts, balance, orders, night trading, etc.
    • Overseas Futures/Options (19 APIs): Quotes, orders, margin, execution trends, etc.
    • Domestic Bonds (14 APIs): Quotes, issuance info, balance, order history, etc.
    • ETF/ETN (2 APIs): NAV comparison trends, current price, etc.
    • ELW (1 API): Trading volume rankings.
  3. Overview of Korea Investment & Securities MCP tools

    main

    Korea Investment & Securities (KIS) provides two Model Context Protocol (MCP) tools designed to bridge the gap between AI models and trading data/functionality. These tools allow AI agents (like Claude or Cursor) to interact directly with the KIS OpenAPI.

    1. KIS Code Assistant MCP: A knowledge-retrieval tool. It allows AI to search for KIS OpenAPI documentation and retrieve actual implementation sample code from GitHub based on natural language queries.
    2. KIS Trading MCP: An execution and data tool. It allows AI to directly call KIS OpenAPI endpoints to fetch market data or manage trading accounts.
  4. Understand the Strategy Builder directory structure

    main

    The strategy_builder project is organized into several key modules that separate the user interface, the API server, and the core strategy engine:

    • backend/: A FastAPI server running on port 8000. It provides API endpoints for authentication, accounts, strategy management, orders, market data, and file handling.
    • strategy_core/: The Single Source of Truth (SSoT) for the strategy engine. It includes the StrategyRegistry (using the @register decorator), the executor, and a DSL (Domain Specific Language) layer that converts builder states into Python code via a parser and codegen.
    • core/: Low-level modules for signal/action definitions, technical indicators (80+ types), KIS API data fetching, order execution, position management, and WebSocket handling.
    • strategy/: Contains the BaseStrategy class and specific strategy implementations (strategy_01 to strategy_10.py).
    • frontend/: A Next.js application running on port 3000. It includes the visual Strategy Builder UI, the execution UI, and hooks for interacting with the backend.
    • kis_auth.py: The module used for Korea Investment & Securities (KIS) API authentication.
  5. Understand the KIS Open API Sample Code Repository Structure

    main

    This repository provides sample code for the Korea Investment & Securities (KIS) Open API, designed for both Python developers and LLM-based AI agents. It is organized into two main types of examples:

    1. examples_llm/: Optimized for LLMs. It contains granular, single-functionality samples. Each API feature has its own folder containing a minimal execution file ([function_name].py) and a verification/test file (chk_[function_name].py).
    2. examples_user/: Optimized for human developers. It provides integrated, category-based samples. Each category (e.g., domestic_stock) contains integrated function files ([category]_functions.py) and execution example files ([category]_examples.py). It also includes WebSocket versions (_ws.py).

    Core Components:

    • kis_auth.py: Handles authentication (access tokens, WebSocket keys), common API call functions, and switching between real and mock investment environments.
    • strategy_builder/: A visual UI engine for designing trading strategies and generating BUY/SELL/HOLD signals.
    • backtester/: A QuantConnect Lean-based engine for validating strategies against historical data.
    • kis_devlp.yaml: Configuration file for API settings (requires personal credentials).
    .
    ├── strategy_builder/            # 전략 설계 + 시그널 생성 엔진
    ├── backtester/                  # 백테스팅 엔진 (QuantConnect Lean)
    ├── docs/
    │   └── convention.md            # 코딩 컨벤션 가이드
    ├── examples_llm/                  # LLM용 샘플 코드
    │   ├── kis_auth.py              # 인증 공통 함수
    │   └── ...
    ├── examples_user/                 # user용 실제 사용 예제
    │   ├── kis_auth.py              # 인증 공통 함수
    │   └── ...
    ├── kis_devlp.yaml               # API 설정 파일 (개인정보 입력 필요)
    └── pyproject.toml               # (uv)프로젝트 의존성 관리
  6. Understand Kis Trading MCP limitations and performance

    main

    Be aware of the following constraints when using the Kis Trading MCP server:

    API Limits

    • You must comply with the Korea Investment & Securities (KIS) API rate limits. There are per-minute call limits that may apply.

    Performance

    • Overhead: Running via Docker introduces slight performance overhead.
    • Memory: Tools like SQLAlchemy and pandas used within the server can consume significant memory.
    • Network: Downloading files from GitHub may introduce latency.

    Timeouts

    • File Downloads: 30 seconds (waiting for GitHub response).
    • Code Execution: 15 seconds (API calls and result processing).
    • Container Startup: 60 seconds (dependency installation and initialization).
  7. Use the AI Trading Pipeline (Strategy → Backtest → Execute)

    main

    The repository provides a complete pipeline for automated trading:

    1. Design: Use strategy_builder/ to design a strategy and generate signals (BUY/SELL/HOLD).
    2. Export: Export the designed strategy as a .kis.yaml file.
    3. Validate: Import the .kis.yaml file into the backtester/ to perform historical validation and parameter optimization.
    4. Execute: Once validated, use the signals to execute trades via the KIS Open API.

    Key Tools:

    • strategy_builder/: Includes 80 technical indicators and 10 preset strategies.
    • backtester/: Docker-based QuantConnect Lean engine that produces HTML reports.
    • MCP/: Provides KIS Code Assistant and Trading MCP for AI tool connectivity.
  8. Integrate Strategy Builder with Backtester using .kis.yaml

    main

    The Strategy Builder and Backtester are designed to work together through a unified .kis.yaml file format, enabling a complete quantitative workflow: Design → Validation → Execution.

    Workflow Steps:

    1. Strategy Design: Use the Strategy Builder visual UI to configure indicators, conditions, and risk parameters.
    2. Export: Export the designed strategy as a .kis.yaml file.
    3. Backtest: Import the .kis.yaml file into the Backtester to validate strategy performance using historical data (Lean).
    4. Analysis: Analyze results (returns, Sharpe ratio, Max Drawdown) within the Backtester.
    5. Optimization: Use Grid or Random Search in the Backtester to find optimal parameters.
    6. Live Application: Once validated, bring the strategy back to the Strategy Builder for real-time signal generation and paper/live trading.

    Comparison of Capabilities:

    FeatureStrategy BuilderBacktester
    Strategy DesignVisual Builder-
    Signal GenerationReal-time-
    Order ExecutionPaper/Live Trading-
    Backtesting-Lean (Docker)
    Portfolio Analysis-Analysis/Visualization
    Parameter Optimization-Grid/Random
    Shared Format.kis.yaml Export.kis.yaml Import
  9. How Strategy Builder works with Backtester

    main

    Strategy Builder is a visual tool for designing trading strategies using technical indicators and risk management rules. The workflow is designed to bridge visual design with rigorous testing:

    1. Design: Use the Visual Builder (/builder) to drag and drop indicators (80+ available) and define entry/exit logic.
    2. Export: Export your design as a .kis.yaml file.
    3. Validate: Import the .kis.yaml file into the Backtester to verify the strategy against historical data.
    4. Execute: Once validated, import the same .kis.yaml back into Strategy Builder to generate real-time signals and execute orders (Paper or Live) via the KIS Open API.
  10. Define Strategies using YAML

    main

    You can define trading strategies without writing code by using the .kis.yaml format. This allows for dynamic parameter binding using the $param_name syntax.

    YAML Schema Structure

    • metadata: Name, description, author, and tags.
    • strategy: ID, category, and params (defining default, min, max, type, and description).
    • indicators: List of indicators with id, alias, and params (which can reference strategy parameters).
    • entry/exit: Logic (e.g., AND, OR) and conditions (indicator, operator, and value).
    • risk: Risk management settings like stop_loss.

    Example YAML Strategy

    version: "1.0"
    
    metadata:
      name: "RSI 과매도 반전"
      description: "RSI가 과매도 영역 진입 후 반등 시 매수"
      author: "user"
      tags: [oscillator, rsi, mean_reversion]
    
    strategy:
      id: rsi_oversold
      category: oscillator
    
      params:
        period:
          default: 14
          min: 2
          max: 100
          type: int
          description: "RSI 기간"
        oversold:
          default: 30
          min: 0
          max: 50
          type: float
          description: "과매도 기준"
    
      indicators:
        - id: rsi
          alias: rsi
          params:
            period: $period
    
      entry:
        logic: AND
        conditions:
          - indicator: rsi
            operator: cross_above
            value: $oversold
    
      exit:
        logic: OR
        conditions:
          - indicator: rsi
            operator: cross_below
            value: 70
    
    risk:
      stop_loss:
        enabled: true
        percent: 5.0
  11. Define strategies using the .kis.yaml format

    main

    The .kis.yaml format is the shared Single Source of Truth (SSoT) used by both Strategy Builder and Backtester. It defines the strategy ID, parameters, indicators, entry/exit logic, and risk management.

    Supported Operators

    OperatorMeaning
    cross_aboveCrosses above
    cross_belowCrosses below
    greater_thanGreater than
    less_thanLess than
    greater_equalGreater than or equal
    less_equalLess than or equal
    equalsEquals

    Example .kis.yaml Strategy

    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
  12. Security considerations for Kis Trading MCP

    main

    When deploying the Kis Trading MCP server, follow these security best practices:

    • Local Binding: By default, MCP_HOST is 127.0.0.1. When using Docker, restrict access to the host only by using -p 127.0.0.1:3000:3000.
    • Access Tokens: In SSE/HTTP mode, the MCP_ACCESS_TOKEN environment variable is mandatory. Clients must provide this token via the Authorization: Bearer <token> or X-Api-Key header.
    • Environment Variables: Pass sensitive information (like API keys) via environment variables; never hardcode them in your scripts.
    • Network Isolation: If external access is not required, consider using stdio mode. However, for stability and cross-platform compatibility, Docker + SSE is recommended.
    • Input Validation: The MCP tools validate parameters to ensure user input is not directly executed as code.