### Install Visualization Libraries Source: https://github.com/soju06/python-kis/wiki/Tutorial Install the necessary libraries, pandas and lightweight-charts, for visualizing stock chart data. ```sh pip install pandas lightweight-charts ``` -------------------------------- ### Install python-kis Library Source: https://github.com/soju06/python-kis/wiki/Home Install the library using pip. The library is written for Python 3.11. ```zsh pip install python-kis ``` -------------------------------- ### Pending Orders Object Representation Source: https://github.com/soju06/python-kis/wiki/Tutorial This example shows the structure of `KisSimplePendingOrders` and `KisDomesticPendingOrder` objects, detailing information about pending orders. ```python KisSimplePendingOrders( account_number=KisAccountNumber('00000000-01'), orders=[ KisDomesticPendingOrder( order_number=KisOrderBase( kis=kis, account_number=KisAccountNumber('00000000-01'), code='039200', market='KRX', branch='91253', number='0000157444' ), type='buy', price=41300, qty=2, executed_qty=0, condition=None, execution=None ) ] ) ``` -------------------------------- ### Orderable Amount Object Representations Source: https://github.com/soju06/python-kis/wiki/Tutorial These are examples of `KisForeignOrderableAmount` and `KisDomesticOrderableAmount` objects, showing the structure and data contained within them. ```python KisForeignOrderableAmount( account_number=KisAccountNumber('50113500-01'), symbol='NVDA', market='NASDAQ', unit_price=109.18, qty=906, amount=100000, condition='extended', execution=None ) KisDomesticOrderableAmount( account_number=KisAccountNumber('50113500-01'), symbol='039200', market='KRX', unit_price=40950, qty=59, amount=2435453, condition=None, execution=None ) ``` -------------------------------- ### Get Trading Hours for Markets Source: https://context7.com/soju06/python-kis/llms.txt Fetches the opening and closing times for domestic (KR) and international (US) markets in KST. The output includes market, open/close times, and KST equivalents. ```python from pykis import KisTradingHours us_hours: KisTradingHours = kis.trading_hours("US") kr_hours: KisTradingHours = kis.trading_hours("KR") print(repr(us_hours)) ``` -------------------------------- ### Daily Chart Data Structure Source: https://github.com/soju06/python-kis/wiki/Tutorial Example of the data structure returned for daily stock charts, including market, symbol, and a list of bars with open, close, high, low, volume, amount, and change. ```python KisDomesticDailyChart( market='KRX', symbol='000660', bars=[ KisDomesticDailyChartBar(time='2024-07-19T00:00:00+09:00', open=208500, close=209500, high=214000, low=207000, volume=4519170, amount=949039126250, change=-3000), KisDomesticDailyChartBar(time='2024-07-22T00:00:00+09:00', open=209000, close=205000, high=209500, low=200500, volume=6662441, amount=1363039398518, change=-4500), KisDomesticDailyChartBar(time='2024-07-23T00:00:00+09:00', open=208500, close=205000, high=209500, low=200500, volume=5976519, amount=1224619868908, change=0), KisDomesticDailyChartBar(time='2024-07-24T00:00:00+09:00', open=202000, close=208500, high=212500, low=200000, volume=4838734, amount=1003813878000, change=3500), KisDomesticDailyChartBar(time='2024-07-25T00:00:00+09:00', open=196200, close=190000, high=198800, low=189000, volume=12503762, amount=2411730871900, change=-18500), KisDomesticDailyChartBar(time='2024-07-26T00:00:00+09:00', open=190800, close=191800, high=194500, low=186100, volume=8769107, amount=1670363205934, change=1800) ] ) ``` -------------------------------- ### Check Sellable Quantity using Stock Shortcut Source: https://github.com/soju06/python-kis/wiki/Tutorial Access the sellable quantity of a stock directly through its shortcut property after obtaining the `KisStock` object. This is a more concise way to get the sellable amount. ```python oscotec = kis.stock("039200") # 오스코텍 매도 가능 수량 조회 print(oscotec.orderable) # 매도 가능 수량 ``` -------------------------------- ### Fetch Stock Chart Data Source: https://github.com/soju06/python-kis/wiki/Tutorial Retrieve daily, weekly, monthly, or yearly chart data for stocks using the `chart` function with various time period and date range parameters. The `period` argument can specify intervals like 'month' or 'year', and `start`/`end` dates can be provided. ```python from datetime import date, time from pykis import KisChart chart: KisChart = coupang.chart() # 기본값은 상장 이래의 일봉입니다. # 최근 기간 조회는 아래와 같이 시간 표현식을 사용할 수 있습니다. # 1m: 1분 # 1h: 1시간 # 1d: 1일 # 1w: 1주 # 1M: 1개월 (개월 단위는 대문자 M) # 1y: 1년 # 1y6M: 1년 6개월 chart: KisChart = coupang.chart("3d") # 최근 3일 일봉입니다. chart: KisChart = coupang.chart("1y", period="month") # 최근 1년간의 월봉입니다. chart: KisChart = coupang.chart(period="year") # 상장 이래의 연간 일봉입니다. chart: KisChart = coupang.chart(start=date(2023, 1, 1)) # 2023년 1월 1일부터 현재까지의 일봉입니다. chart: KisChart = coupang.chart( start=date(2023, 1, 1), end=date(2024, 1, 1), ) # 2023년 1월 1일부터 2023년 12월 31일까지의 일봉입니다. chart: KisChart = coupang.chart("1h", period=1) # 최근 1시간의 1분봉입니다. chart: KisChart = coupang.chart(period=5) # 당일 5분봉입니다. chart: KisChart = coupang.chart(period=1, end=time(12, 30)) # 당일 12시 30분까지의 1분봉입니다. ``` -------------------------------- ### Place Buy/Sell Orders Source: https://github.com/soju06/python-kis/wiki/Tutorial Use `stock.buy()` and `stock.sell()` to place buy or sell orders. You can specify quantity and price for limit orders, or omit price for market orders. ```python from pykis import KisOrder # SK하이닉스 1주 시장가 매수 주문 order: KisOrder = hynix.buy(qty=1) # SK하이닉스 1주 지정가 매수 주문 order: KisOrder = hynix.buy(price=194700, qty=1) # SK하이닉스 전량 시장가 매도 주문 order: KisOrder = hynix.sell() ``` -------------------------------- ### PyKis 객체 생성 (파일 저장) Source: https://github.com/soju06/python-kis/wiki/Home Demonstrates how to create a PyKis object by saving and loading secret keys from a file, which is the recommended approach for security. ```APIDOC ## PyKis 객체 생성 (파일 저장) ### Description This method shows how to initialize the PyKis client by saving your API credentials to a JSON file and then loading them. ### Code ```python from pykis import KisAuth # Save credentials to a file auth = KisAuth( id="YOUR_HTS_ID", appkey="YOUR_APP_KEY", secretkey="YOUR_APP_SECRET", account="00000000-01", virtual=False, ) auth.save("secret.json") # Load credentials from the file to create PyKis object from pykis import PyKis # For real trading kis = PyKis("secret.json", keep_token=True) kis = PyKis(KisAuth.load("secret.json"), keep_token=True) # For virtual trading kis = PyKis("secret.json", "virtual_secret.json", keep_token=True) kis = PyKis(KisAuth.load("secret.json"), KisAuth.load("virtual_secret.json"), keep_token=True) ``` ``` -------------------------------- ### PyKis 객체 생성 (직접 입력) Source: https://github.com/soju06/python-kis/wiki/Home Demonstrates how to create a PyKis object by directly providing API credentials as arguments. ```APIDOC ## PyKis 객체 생성 (직접 입력) ### Description This method shows how to initialize the PyKis client by directly passing your API credentials as arguments. ### Code ```python from pykis import PyKis # For real trading kis = PyKis( id="soju06", account="00000000-01", appkey="PSED321z...", secretkey="RR0sFMVB...", keep_token=True, ) # For 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, ) ``` ``` -------------------------------- ### Get Account Object Source: https://github.com/soju06/python-kis/wiki/Tutorial Retrieve an account scope object using the `kis.account()` function to access account-specific information like balances and holdings. ```python from pykis import KisAccount account: KisAccount = kis.account() ``` -------------------------------- ### Print Chart Object Representation Source: https://github.com/soju06/python-kis/wiki/Tutorial Use the `repr()` function to get a string representation of a chart object, which can be useful for debugging or quick inspection of chart data. ```python print(repr(hynix.chart("7d"))) # SK하이닉스의 최근 7일 일봉 차트 ``` -------------------------------- ### Create PyKis Object with Direct Credentials Source: https://github.com/soju06/python-kis/wiki/Home Instantiate the PyKis client by directly providing your API credentials. Supports both real trading and virtual trading accounts. ```python from pykis import PyKis # 실전투자용 한국투자증권 API를 생성합니다. is = PyKis( id="soju06", # HTS 로그인 ID account="00000000-01", # 계좌번호 appkey="PSED321z...", # AppKey 36자리 secretkey="RR0sFMVB...", # SecretKey 180자리 keep_token=True, # API 접속 토큰 자동 저장 ) # 모의투자용 한국투자증권 API를 생성합니다. is = PyKis( id="soju06", # HTS 로그인 ID account="00000000-01", # 모의투자 계좌번호 appkey="PSED321z...", # 실전투자 AppKey 36자리 secretkey="RR0sFMVB...", # 실전투자 SecretKey 180자리 virtual_id="soju06", # 모의투자 HTS 로그인 ID virtual_appkey="PSED321z...", # 모의투자 AppKey 36자리 virtual_secretkey="RR0sFMVB...", # 모의투자 SecretKey 180자리 keep_token=True, # API 접속 토큰 자동 저장 ) ``` -------------------------------- ### Create PyKis Object from Secret File Source: https://github.com/soju06/python-kis/wiki/Home Instantiate the PyKis client using a saved secret key file. Supports both real trading and virtual trading accounts. ```python from pykis import PyKis, KisAuth # 실전투자용 PyKis 객체를 생성합니다. is = PyKis("secret.json", keep_token=True) is = PyKis(KisAuth.load("secret.json"), keep_token=True) # 모의투자용 PyKis 객체를 생성합니다. is = PyKis("secret.json", "virtual_secret.json", keep_token=True) is = PyKis(KisAuth.load("secret.json"), KisAuth.load("virtual_secret.json"), keep_token=True) ``` -------------------------------- ### Get Account Scope Source: https://context7.com/soju06/python-kis/llms.txt Returns a KisAccount scope object for accessing account-related functions like balance, orders, and trades. Allows specifying a particular account number. ```python from pykis import KisAccount account: KisAccount = kis.account() # 특정 계좌번호 지정 account: KisAccount = kis.account("12345678-01") ``` -------------------------------- ### Place Buy Orders with Various Conditions Source: https://github.com/soju06/python-kis/wiki/Tutorial Demonstrates different types of buy orders including limit, market, conditional limit, best limit, priority limit, and after-hours orders. Note that some conditions are not supported in simulation trading. ```python stock.buy(price=100, condition=None, execution=None) # 전체 지정가 매수 ``` ```python stock.buy(price=None, condition=None, execution=None) # 전체 시장가 매수 ``` ```python stock.buy(price=100, condition=None, execution=None) # 지정가 매수 ``` ```python stock.buy(price=None, condition=None, execution=None) # 시장가 매수 ``` ```python stock.buy(price=100, condition='condition', execution=None) # 조건부지정가 매수 ``` ```python stock.buy(price=100, condition='best', execution=None) # 최유리지정가 매수 ``` ```python stock.buy(price=100, condition='priority', execution=None) # 최우선지정가 매수 ``` ```python stock.buy(price=100, condition='extended', execution=None) # 시간외단일가 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition='before', execution=None) # 장전시간외 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition='after', execution=None) # 장후시간외 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition=None, execution='IOC') # IOC지정가 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition=None, execution='FOK') # FOK지정가 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition=None, execution='IOC') # IOC시장가 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition=None, execution='FOK') # FOK시장가 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition='best', execution='IOC') # IOC최유리 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition='best', execution='FOK') # FOK최유리 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition='LOO', execution=None) # 나스닥, 뉴욕, 아멕스 장개시지정가 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition='LOC', execution=None) # 나스닥, 뉴욕, 아멕스 장마감지정가 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition='MOO', execution=None) # 나스닥, 뉴욕, 아멕스 장개시시장가 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition='MOC', execution=None) # 나스닥, 뉴욕, 아멕스 장마감시장가 매수 (모의투자 미지원) ``` ```python stock.buy(price=None, condition='extended', execution=None) # 나스닥, 뉴욕, 아멕스 주간거래 시장가 매수 (모의투자 미지원) ``` ```python stock.buy(price=100, condition='extended', execution=None) # 나스닥, 뉴욕, 아멕스 주간거래 지정가 매수 (모의투자 미지원) ``` -------------------------------- ### Create PyKis API Client Source: https://context7.com/soju06/python-kis/llms.txt Instantiate the main PyKis client for API communication. Can be initialized using saved authentication files, multiple files for real/virtual trading, or directly with API keys. `keep_token=True` enables automatic token saving and reuse. ```python from pykis import PyKis, KisAuth # 방법 1: 저장된 인증 파일로 실전투자 클라이언트 생성 kis = PyKis("secret.json", keep_token=True) # 방법 2: 실전+모의 동시 사용 kis = PyKis("secret.json", "virtual_secret.json", keep_token=True) # 방법 3: 키를 직접 입력 kis = PyKis( id="soju06", account="00000000-01", appkey="PSED321z...", secretkey="RR0sFMVB...", keep_token=True, ) # 방법 4: 모의투자 포함 직접 입력 kis = PyKis( id="soju06", account="00000000-01", appkey="PSED321z...", secretkey="RR0sFMVB...", virtual_id="soju06", virtual_appkey="PSED321z...", virtual_secretkey="RR0sFMVB...", keep_token=True, ) print(kis.virtual) # False (실전투자 여부) print(kis.primary_account) # KisAccountNumber('00000000-01') ``` -------------------------------- ### Get Stock Object for Domestic and International Stocks Source: https://github.com/soju06/python-kis/wiki/Tutorial Retrieve a `KisStock` object for a given stock symbol. You can specify the market for faster lookups, otherwise, it defaults to a predefined market search order. ```python from pykis import KisStock # 국내 주식 hynix: KisStock = kis.stock("000660") # SK하이닉스 (코스피) ecopro: KisStock = kis.stock("247540") # 에코프로비엠 (코스닥) # 해외 주식 (미국) nvida: KisStock = kis.stock("NVDA") # 엔비디아 (나스닥) coupang: KisStock = kis.stock("CPNG") # 쿠팡 (뉴욕) ``` ```python tokyo_electric: KisStock = kis.stock("9501", market="TYO") # 도쿄 전력 (도쿄) # 또는 국가코드를 사용할 수 있습니다. toky_electric: KisStock = kis.stock("9501", market="JP") # 도쿄 전력 (도쿄) ``` -------------------------------- ### Place Sell Orders with Various Conditions Source: https://github.com/soju06/python-kis/wiki/Tutorial Demonstrates different types of sell orders including limit, market, conditional limit, best limit, priority limit, and after-hours orders. Note that some conditions are not supported in simulation trading. ```python stock.sell(price=100, condition=None, execution=None) # 전체 지정가 매도 ``` ```python stock.sell(price=None, condition=None, execution=None) # 전체 시장가 매도 ``` ```python stock.sell(price=100, condition=None, execution=None) # 지정가 매도 ``` ```python stock.sell(price=None, condition=None, execution=None) # 시장가 매도 ``` ```python stock.sell(price=100, condition='condition', execution=None) # 조건부지정가 매도 ``` ```python stock.sell(price=100, condition='best', execution=None) # 최유리지정가 매도 ``` ```python stock.sell(price=100, condition='priority', execution=None) # 최우선지정가 매도 ``` ```python stock.sell(price=100, condition='extended', execution=None) # 시간외단일가 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition='before', execution=None) # 장전시간외 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition='after', execution=None) # 장후시간외 매도 ``` ```python stock.sell(price=100, condition=None, execution='IOC') # IOC지정가 매도 (모의투자 미지원) ``` ```python stock.sell(price=100, condition=None, execution='FOK') # FOK지정가 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition=None, execution='IOC') # IOC시장가 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition=None, execution='FOK') # FOK시장가 매도 (모의투자 미지원) ``` ```python stock.sell(price=100, condition='best', execution='IOC') # IOC최유리 매도 (모의투자 미지원) ``` ```python stock.sell(price=100, condition='best', execution='FOK') # FOK최유리 매도 (모의투자 미지원) ``` ```python stock.sell(price=100, condition='LOO', execution=None) # 나스닥, 뉴욕, 아멕스 장개시지정가 매도 (모의투자 미지원) ``` ```python stock.sell(price=100, condition='LOC', execution=None) # 나스닥, 뉴욕, 아멕스 장마감지정가 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition='MOO', execution=None) # 나스닥, 뉴욕, 아멕스 장개시시장가 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition='MOC', execution=None) # 나스닥, 뉴욕, 아멕스 장마감시장가 매도 (모의투자 미지원) ``` ```python stock.sell(price=None, condition='extended', execution=None) # 나스닥, 뉴욕, 아멕스 주간거래 시장가 매도 (모의투자 미지원) ``` ```python stock.sell(price=100, condition='extended', execution=None) # 나스닥, 뉴욕, 아멕스 주간거래 지정가 매도 (모의투자 미지원) ``` -------------------------------- ### Get Orderable Amount for Stocks Source: https://context7.com/soju06/python-kis/llms.txt Queries the orderable quantity and amount for stock purchases based on market, symbol, and condition. Supports both account-level and stock-level queries, including extended hours and limit orders. ```python from pykis import KisOrderableAmount account = kis.account() nvda = kis.stock("NVDA") oscotec = kis.stock("039200") # 주간거래 시장가 매수 가능 수량 amount: KisOrderableAmount = account.orderable_amount( market="NASDAQ", symbol="NVDA", condition="extended" ) print(f"NVDA 주간거래 매수가능: {amount.qty}주 (단가:{amount.unit_price})") # 지정가 매수 가능 수량 (종목 스코프 사용) amount2: KisOrderableAmount = oscotec.orderable_amount(price=40950) print(f"오스코텍 지정가 매수가능: {amount2.qty}주 / 금액:{amount2.amount}원") ``` -------------------------------- ### 시세 조회 Source: https://github.com/soju06/python-kis/wiki/Home Shows how to fetch real-time stock quotes for both domestic and international stocks using the `stock.quote()` method. ```APIDOC ## 시세 조회 ### Description Use the `stock.quote()` function to retrieve real-time stock quotes for domestic and international stocks. ### Method ```python stock.quote() stock.quote(extended=True) ``` ### Parameters #### Query Parameters - **extended** (bool) - Optional - Set to `True` to fetch extended trading hours quotes. ### Request Example ```python from pykis import KisQuote # Get the product object for NVIDIA stock = kis.stock("NVDA") # Fetch standard quote quote: KisQuote = stock.quote() # Fetch extended trading hours quote quote: KisQuote = stock.quote(extended=True) # PyKis objects can be inspected using repr for key details. print(repr(quote)) ``` ### Response #### Success Response (200) - **quote** (KisQuote) - An object containing the stock quote information. ``` -------------------------------- ### Get Stock Scope Object Source: https://context7.com/soju06/python-kis/llms.txt Obtain a `KisStock` object using a stock code (ticker) for accessing stock-specific functionalities like price quotes, orders, and real-time subscriptions. Market codes can speed up lookups. ```python from pykis import KisStock # 국내 주식 hynix: KisStock = kis.stock("000660") # SK하이닉스 (KRX) samsung: KisStock = kis.stock("005930") # 삼성전자 (KRX) # 해외 주식 nvda: KisStock = kis.stock("NVDA") # 엔비디아 (NASDAQ) coupang: KisStock = kis.stock("CPNG") # 쿠팡 (NYSE) # 시장 코드 또는 국가 코드로 빠르게 조회 tokyo_elec: KisStock = kis.stock("9501", market="TYO") # 도쿄 전력 (도쿄) tokyo_elec: KisStock = kis.stock("9501", market="JP") # 국가코드도 가능 # 종목 기본 정보 출력 print(f"종목코드: {hynix.symbol}") # 000660 print(f"종목시장: {hynix.market}") # KRX # 상세 정보 (KisStockInfo) info = hynix.info print(f"표준코드: {info.std_code}") print(f"영문명: {info.name_eng}") print(f"시장명: {info.market_name}") ``` -------------------------------- ### Create PyKis Object with Direct Secret Key Input Source: https://github.com/soju06/python-kis/wiki/Tutorial Initialize PyKis objects by directly providing your HTS ID, account number, app key, and secret key. Supports both real and virtual trading configurations. ```python from pykis import PyKis # 실전투자용 한국투자증권 API를 생성합니다. kis = PyKis( id="soju06", # HTS 로그인 ID account="00000000-01", # 계좌번호 appkey="PSED321z...", # AppKey 36자리 secretkey="RR0sFMVB...", # SecretKey 180자리 keep_token=True, # API 접속 토큰 자동 저장 ) # 모의투자용 한국투자증권 API를 생성합니다. kis = PyKis( id="soju06", # HTS 로그인 ID account="00000000-01", # 모의투자 계좌번호 appkey="PSED321z...", # 실전투자 AppKey 36자리 secretkey="RR0sFMVB...", # 실전투자 SecretKey 180자리 virtual_id="soju06", # 모의투자 HTS 로그인 ID virtual_appkey="PSED321z...", # 모의투자 AppKey 36자리 virtual_secretkey="RR0sFMVB...", # 모의투자 SecretKey 180자리 keep_token=True, # API 접속 토큰 자동 저장 ) ``` -------------------------------- ### Manually Manage Access Tokens with PyKis Source: https://github.com/soju06/python-kis/wiki/Tutorial Manually manage access tokens by loading them from a file or setting them directly on the PyKis object. This allows for token persistence across sessions. ```python from pykis.kis import PyKis, KisAccessToken # 저장된 토큰을 사용하려면 아래와 같이 PyKis 객체를 생성합니다. kis = PyKis("secret.json", token="token.json") kis = PyKis("secret.json", token=KisAccessToken.load("token.json")) # 또는 아래와 같이 PyKis 객체를 생성한 후 토큰을 설정합니다. kis = PyKis("secret.json") kis.token = KisAccessToken.load("token.json") # 아래 프로퍼티를 호출하면 만료기간이 보장된 토큰을 발급받을 수 있습니다. token = kis.token # 토큰의 정보를 확인합니다. print(repr(token), str(token)) # 안전한 경로에 해당 토큰을 파일로 저장합니다. token.save("token.json") # 파일로 저장된 토큰이 만료되더라도 PyKis 객체에서 자동으로 갱신합니다. print(f"남은 유효기간: {kis.token.remaining}") ``` -------------------------------- ### Query Orderable Amount Source: https://github.com/soju06/python-kis/wiki/Tutorial Use `account.orderable_amount()` or `stock.orderable_amount()` to check the orderable amount for buying stocks. You can specify the market, symbol, and condition for NASDAQ, or provide a price for domestic stocks. ```APIDOC ## Query Orderable Amount ### Description Use `account.orderable_amount()` or `stock.orderable_amount()` to check the orderable amount for buying stocks. You can specify the market, symbol, and condition for NASDAQ, or provide a price for domestic stocks. ### Method `account.orderable_amount(market: str, symbol: str, condition: str = None)` `account.orderable_amount(price: int)` `stock.orderable_amount(market: str, symbol: str, condition: str = None)` `stock.orderable_amount(price: int)` ### Parameters #### Path Parameters None #### Query Parameters - **market** (str) - Required - The stock market (e.g., "NASDAQ", "KRX"). - **symbol** (str) - Required - The stock symbol (e.g., "NVDA", "039200"). - **condition** (str) - Optional - The trading condition (e.g., "extended"). - **price** (int) - Required - The price for domestic stock orderable amount calculation. ### Request Example ```python # Example for NASDAQ orderable_amount = account.orderable_amount(market="NASDAQ", symbol="NVDA", condition="extended") # Example for domestic stock orderable_amount = oscotec.orderable_amount(price=40950) ``` ### Response #### Success Response (200) Returns a `KisOrderableAmount` object containing details like `account_number`, `symbol`, `market`, `unit_price`, `qty`, `amount`, and `condition`. #### Response Example ```json KisForeignOrderableAmount( account_number=KisAccountNumber('50113500-01'), symbol='NVDA', market='NASDAQ', unit_price=109.18, qty=906, amount=100000, condition='extended', execution=None ) KisDomesticOrderableAmount( account_number=KisAccountNumber('50113500-01'), symbol='039200', market='KRX', unit_price=40950, qty=59, amount=2435453, condition=None, execution=None ) ``` ``` -------------------------------- ### Execute Buy/Sell Orders, Modifications, and Cancellations Source: https://github.com/soju06/python-kis/wiki/Tutorial Manage stock orders using `stock.order()`, `stock.buy()`, `stock.sell()`, `stock.modify()`, and `stock.cancel()` functions. This includes placing new buy/sell orders, and modifying or canceling existing ones. ```APIDOC ## Execute Buy/Sell Orders, Modifications, and Cancellations ### Description Manage stock orders using `stock.order()`, `stock.buy()`, `stock.sell()`, `stock.modify()`, and `stock.cancel()` functions. This includes placing new buy/sell orders, and modifying or canceling existing ones. ### Method `stock.buy(price: int = None, qty: int = None)` `stock.sell(price: int = None, qty: int = None)` `stock.modify(order_number: str, price: int = None, qty: int = None)` `stock.cancel(order_number: str)` ### Parameters #### Path Parameters None #### Query Parameters - **price** (int) - Optional - The price for the order. If not specified, a market order is placed. - **qty** (int) - Optional - The quantity for the order. If not specified for a sell order, it defaults to selling all available quantity. - **order_number** (str) - Required - The unique identifier for the order to be modified or canceled. ### Request Example ```python # Place a market buy order for 1 share of SK Hynix hynix.buy(qty=1) # Place a limit buy order for 1 share of SK Hynix at 194700 hynix.buy(price=194700, qty=1) # Place a market sell order for all available shares of SK Hynix hynix.sell() # Modify an existing order hynix.modify(order_number="12345", price=195000, qty=2) # Cancel an existing order hynix.cancel(order_number="12345") ``` ### Response #### Success Response (200) Returns a `KisOrder` object containing details of the placed, modified, or canceled order. #### Response Example ```json KisOrder( account_number=KisAccountNumber('50113500-01'), order_number='00000000-00000000-00000000-00000000', symbol='000660', market='KRX', type='buy', price=194700, qty=1, condition='normal', execution=None ) ``` ``` -------------------------------- ### Subscribe to Real-time Execution Details Source: https://context7.com/soju06/python-kis/llms.txt Subscribe to real-time execution events for orders in your account. Supports both domestic and international stock executions. ```python from pykis import KisRealtimeExecution, KisSubscriptionEventArgs, KisWebsocketClient account = kis.account() def on_execution(sender: KisWebsocketClient, e: KisSubscriptionEventArgs[KisRealtimeExecution]): ex = e.response print(f"[{ex.type}] {ex.symbol} | 체결가:{ex.price} | 체결수량:{ex.executed_qty}") ticket = account.on("execution", on_execution) print(kis.websocket.subscriptions) # {KisWebsocketTR(id='H0GSCNI9', key='soju06'), KisWebsocketTR(id='H0STCNI9', key='soju06')} input("Press Enter to exit...") ticket.unsubscribe() # 출력 예시 # [buy] 000660 | 체결가:173600 | 체결수량:10 ``` -------------------------------- ### PyKis — API Client Creation Source: https://context7.com/soju06/python-kis/llms.txt The main client class responsible for all communication with the Korean Investment & Securities API. It can be initialized using a file path, a KisAuth object, or direct key strings. `keep_token=True` enables automatic token saving and reuse. ```APIDOC ## PyKis — API 클라이언트 생성 한국투자증권 API와의 모든 통신을 담당하는 메인 클라이언트 클래스입니다. 파일 경로, `KisAuth` 객체, 또는 직접 키 문자열로 생성할 수 있으며, `keep_token=True`로 토큰 자동 저장·재사용이 가능합니다. ```python from pykis import PyKis, KisAuth # 방법 1: 저장된 인증 파일로 실전투자 클라이언트 생성 kis = PyKis("secret.json", keep_token=True) # 방법 2: 실전+모의 동시 사용 kis = PyKis("secret.json", "virtual_secret.json", keep_token=True) # 방법 3: 키를 직접 입력 kis = PyKis( id="soju06", account="00000000-01", appkey="PSED321z...", secretkey="RR0sFMVB...", keep_token=True, ) # 방법 4: 모의투자 포함 직접 입력 kis = PyKis( id="soju06", account="00000000-01", appkey="PSED321z...", secretkey="RR0sFMVB...", virtual_id="soju06", virtual_appkey="PSED321z...", virtual_secretkey="RR0sFMVB...", keep_token=True, ) print(kis.virtual) # False (실전투자 여부) print(kis.primary_account) # KisAccountNumber('00000000-01') ``` ``` -------------------------------- ### Order Management (Buy/Sell) Source: https://github.com/soju06/python-kis/blob/main/README.md Place buy, sell, modify, and cancel orders using `stock.buy()`, `stock.sell()`, `stock.modify()`, and `stock.cancel()` functions. ```APIDOC ## Order Management (Buy/Sell) ### Description Place buy, sell, modify, and cancel orders using `stock.buy()`, `stock.sell()`, `stock.modify()`, and `stock.cancel()` functions. ### Methods #### Buy Order - `stock.buy(qty: int)`: Place a market price buy order. - `stock.buy(price: int, qty: int)`: Place a limit price buy order. #### Sell Order - `stock.sell()`: Place a market price sell order for all available quantity. - `stock.sell(price: int)`: Place a limit price sell order for all available quantity. - `stock.sell(price: int, qty: int)`: Place a limit price sell order for a specified quantity. #### Modify Order - `order.modify(price: int)`: Modify the price of an existing order. - `order.modify(qty: int)`: Modify the quantity of an existing order. #### Cancel Order - `order.cancel()`: Cancel a specific order. - `account.pending_orders()`: Retrieve a list of pending orders, which can then be cancelled individually. ### Parameters - `qty` (int): The quantity of stocks to trade. - `price` (int): The limit price for the order. ### Response Returns an `KisOrder` object for placed or modified orders. ### Request Example ```python # Market price buy order for 1 share of SK Hynix order = hynix.buy(qty=1) # Limit price buy order for 1 share of SK Hynix at 194700 order = hynix.buy(price=194700, qty=1) # Market price sell order for all shares of SK Hynix order = hynix.sell() # Limit price sell order for all shares of SK Hynix at 194700 order = hynix.sell(price=194700) # Modify order price order = order.modify(price=195000) # Modify order quantity order = order.modify(qty=10) # Cancel order order.cancel() # Cancel all pending orders for order in account.pending_orders(): order.cancel() ``` ### Response Example (Order Status) ```python print(order.pending) # Check if the order is pending print(order.pending_order.pending_qty) # Get the pending quantity ``` ``` -------------------------------- ### Query Sellable Quantity Source: https://github.com/soju06/python-kis/wiki/Tutorial Check the sellable quantity of stocks using either the `KisBalanceStock` object from `account.balance()` or the shortcut property of a `KisStock` object. ```APIDOC ## Query Sellable Quantity ### Description Check the sellable quantity of stocks using either the `KisBalanceStock` object from `account.balance()` or the shortcut property of a `KisStock` object. ### Method `account.balance().stocks[index].orderable` `account.balance().stock(symbol).orderable` `kis.stock(symbol).orderable` ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (str) - Required - The stock symbol (e.g., "039200"). ### Request Example ```python # Using KisBalanceStock object balance_stock = account.balance().stock("039200") sellable_quantity = balance_stock.orderable # Using KisStock shortcut property oscotec = kis.stock("039200") sellable_quantity = oscotec.orderable ``` ### Response #### Success Response (200) Returns the sellable quantity as a `Decimal` object. #### Response Example ``` Decimal('118') ``` ``` -------------------------------- ### Create PyKis Object from Saved Secret Keys Source: https://github.com/soju06/python-kis/wiki/Tutorial Instantiate PyKis objects using previously saved secret key files. Supports both real trading and virtual trading environments. ```python from pykis import PyKis, KisAuth # 실전투자용 PyKis 객체를 생성합니다. kis = PyKis("secret.json", keep_token=True) kis = PyKis(KisAuth.load("secret.json"), keep_token=True) # 모의투자용 PyKis 객체를 생성합니다. kis = PyKis("secret.json", "virtual_secret.json", keep_token=True) kis = PyKis(KisAuth.load("secret.json"), KisAuth.load("virtual_secret.json"), keep_token=True) ``` -------------------------------- ### Save Secret Keys to File Source: https://github.com/soju06/python-kis/wiki/Home Save your API credentials (ID, App Key, Secret Key, Account) to a JSON file for secure management. This is the recommended method. ```python from pykis import KisAuth auth = KisAuth( # HTS 로그인 ID 예) soju06 id="YOUR_HTS_ID", # 앱 키 예) Pa0knAM6JLAjIa93Miajz7ykJIXXXXXXXXXX appkey="YOUR_APP_KEY", # 앱 시크릿 키 예) V9J3YGPE5q2ZRG5EgqnLHn7XqbJjzwXcNpvY . . . secretkey="YOUR_APP_SECRET", # 앱 키와 연결된 계좌번호 예) 00000000-01 account="00000000-01", # 모의투자 여부 virtual=False, ) # 안전한 경로에 시크릿 키를 파일로 저장합니다. auth.save("secret.json") ```