python-kis

repository·main·Indexed 43 days ago

https://github.com/soju06/python-kis

A community-driven Python library for the Korea Investment & Securities (KIS) Open Trading API. It provides high-level abstractions for stock quotes, account management, and order execution, featuring full type hinting and WebSocket support for real-time price updates. Designed for Python 3.11+, it includes the PyKis client and KisAuth for secure credential management.

Tokens
1.8K
Snippets
8
Records
9
Agent score
5%

What's inside python-kis

  1. View available tutorials

    main

    The project provides a comprehensive set of tutorials organized by functional area:

    1. Authentication Management: Secret key management and access token management.
    2. Stock Quotes and Charts: Price quotes, charts, order books (quotes), and market operating hours.
    3. Orders and Balance Inquiry: Deposit/balance, realized profit/loss, daily execution history, buy/sell availability, pending orders, and order execution/correction/cancellation.
    4. Real-time Event Reception: Real-time price, order book (quotes), and execution history.
  2. How to manage credentials with KisAuth

    main

    It is recommended to manage your credentials using the KisAuth object and saving them to a file to avoid hardcoding sensitive information.

    1. Create a KisAuth instance with your HTS ID, App Key, App Secret, and Account number.
    2. Use auth.save("filename.json") to store the credentials securely.
    3. Load them later using KisAuth.load("filename.json") or pass the filename directly to PyKis.
    from pykis import KisAuth
    
    auth = KisAuth(
        id="YOUR_HTS_ID",
        appkey="YOUR_APP_KEY",
        secretkey="YOUR_APP_SECRET",
        account="00000000-01",
        virtual=False,
    )
    
    # Save to a file
    auth.save("secret.json")
    
    # Later, load and use
    from pykis import PyKis
    kis = PyKis(KisAuth.load("secret.json"), keep_token=True)
  3. Initialize the PyKis client

    main

    You can initialize the PyKis client in two ways: using a saved credential file (recommended) or by providing credentials directly in the constructor.

    Using a credential file

    from pykis import PyKis, KisAuth
    
    # For real trading
    kis = PyKis("secret.json", keep_token=True)
    
    # For mock/virtual trading (requires two files: real and virtual)
    kis = PyKis("secret.json", "virtual_secret.json", keep_token=True)

    Providing credentials directly

    from pykis import PyKis
    
    # Real trading
    kis = PyKis(
        id="soju06",
        account="00000000-01",
        appkey="PSED321z...",
        secretkey="RR0sFMVB...",
        keep_token=True,
    )
    
    # Mock/Virtual trading
    kis = PyKis(
        id="soju06",
        account="00000000-01",
        appkey="PSED321z...",
        secretkey="RR0sFMVB...",
        virtual_id="soju06",
        virtual_appkey="PSED321z...",
        virtual_secretkey="RR0sFMVB...",
        keep_token=True,
    )
    from pykis import PyKis
    
    kis = PyKis(
        id="soju06",
        account="00000000-01",
        appkey="PSED321z...",
        secretkey="RR0sFMVB...",
        keep_token=True,
    )
  4. Subscribe to real-time stock prices

    main

    To receive real-time price updates for domestic or overseas stocks, use the .on("price", callback) method on a stock object. The callback function receives a KisSubscriptionEventArgs containing a KisRealtimePrice object in its response field.

    To stop receiving updates, call .unsubscribe() on the ticket returned by the .on() method.

    from pykis import KisRealtimePrice, KisSubscriptionEventArgs, KisWebsocketClient, PyKis
    
    def on_price(sender: KisWebsocketClient, e: KisSubscriptionEventArgs[KisRealtimePrice]):
        print(e.response)
    
    # Assuming 'hynix' is a stock object and 'kis' is the PyKis instance
    ticket = hynix.on("price", on_price)
    
    print(kis.websocket.subscriptions) # View currently subscribed events
    
    input("Press Enter to exit...")
    
    ticket.unsubscribe()
  5. Cancel all pending orders

    main

    You can iterate through all pending orders in an account using the pending_orders() method and call .cancel() on each order object to cancel them all.

    # 미체결 주문 전체 취소
    for order in account.pending_orders():
        order.cancel()
  6. Check account balance with account.balance()

    main

    Use account.balance() to retrieve your deposits (KRW, USD, etc.) and your current stock holdings.

    from pykis import KisBalance
    
    # Access the main account
    account = kis.account()
    
    # Retrieve balance and holdings
    balance: KisBalance = account.balance()
    
    print(repr(balance))
  7. Retrieve stock quotes with stock.quote()

    main

    Use the stock.quote() method on a stock object to retrieve real-time market data (price, volume, indicators, etc.).

    • stock.quote(): Standard quote.
    • stock.quote(extended=True): Retrieves extended market/day-trading quotes.
    from pykis import KisQuote
    
    # Get a stock object (e.g., NVIDIA)
    stock = kis.stock("NVDA")
    
    # Get standard quote
    quote: KisQuote = stock.quote()
    
    # Get extended/day-trading quote
    quote: KisQuote = stock.quote(extended=True)
    
    print(quote)
  8. Execute buy and sell orders

    main

    Manage trades using buy(), sell(), modify(), and cancel() methods on a stock object.

    • buy(qty=N, price=P): Buy N shares. If price is omitted, it's a market order.
    • sell(qty=N, price=P): Sell N shares. If qty is omitted, it sells the entire position. If price is omitted, it's a market order.
    • modify(qty=N, price=P): Modify an existing pending order's quantity or price.
    • cancel(): Cancel a pending order.

    Note: order.pending returns a boolean indicating if the order is still unfilled.

    from pykis import KisOrder
    
    # Market buy 1 share
    order: KisOrder = hynix.buy(qty=1)
    
    # Limit buy 1 share at specific price
    order: KisOrder = hynix.buy(price=194700, qty=1)
    
    # Market sell all shares
    order: KisOrder = hynix.sell()
    
    # Limit sell all shares at specific price
    order: KisOrder = hynix.sell(price=194700)
    
    # Check if order is pending
    if order.pending:
        print(f"Unfilled qty: {order.pending_order.pending_qty}")
    
    # Modify order
    order = order.modify(price=195000)
    
    # Cancel order
    order.cancel()