### Install Mojito Python Module Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This command installs the Mojito Python module using pip. Ensure you have pip installed and a stable internet connection. ```sh pip install mojito2 ``` -------------------------------- ### Cancel Stock Order (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python example illustrates how to cancel an existing stock order using the Mojito library. It requires specific order identifiers and parameters to successfully cancel the trade. ```python resp = broker.cancel_order("91252", "0000117057", "00", 60000, 5, "Y") # KRX_FWDG_ORD_ORGNO, ODNO, 지정가 주문, 가격, 수량, 모두 print(resp) ``` -------------------------------- ### Real-time Data Reception Loop (Python) Source: https://context7.com/sharebook-kr/mojito/llms.txt This Python code snippet demonstrates a loop for continuously receiving market data (trades, quotes, etc.) from a WebSocket broker. It processes different data types based on the first element of the received data and includes examples of the expected data structures. The loop terminates upon calling broker_ws.terminate(). ```python while True: data = broker_ws.get() # Queue에서 데이터 가져오기 if data[0] == '체결': print(f"[체결] {data[1]}") # 출력 예시: # {'유가증권단축종목코드': '005930', '주식체결시간': '100530', # '주식현재가': '72000', '전일대비': '-500', ...} elif data[0] == '호가': print(f"[호가] {data[1]}") # 출력 예시: # {'유가증권 단축 종목코드': '005930', '매도호가01': '72100', # '매수호가01': '72000', '매도호가잔량01': '1500', ...} elif data[0] == '체잔': print(f"[체결통보] {data[1]}") # 출력 예시: # {'계좌번호': '12345678', '주문번호': '0000117057', # '체결수량': '10', '체결단가': '72000', ...} # 종료 시 broker_ws.terminate() ``` -------------------------------- ### Create Market Buy Order (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python code demonstrates placing a market buy order for a specified stock and quantity using the Mojito library. The response, including order details, is pretty-printed. ```python resp = broker.create_market_buy_order("005930", 10) # 삼성전자, 10주, 시장가 pprint.pprint(resp) ``` -------------------------------- ### Fetch Account Balance (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python snippet shows how to query your current stock balance using the Mojito library. It utilizes the authenticated broker object to retrieve balance information, which is then pretty-printed. ```python resp = broker.fetch_balance() pprint.pprint(resp) ``` -------------------------------- ### Create Sell Order (Limit/Market) Source: https://context7.com/sharebook-kr/mojito/llms.txt Executes sell orders for stocks, either at a limit price or at the market price. Requires stock symbol and quantity. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) resp = broker.create_market_sell_order( symbol="005930", quantity=5 ) pprint.pprint(resp) resp = broker.create_limit_sell_order( symbol="005930", price=75000, quantity=3 ) pprint.pprint(resp) ``` -------------------------------- ### Create Limit Buy Order for US Stocks (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python snippet shows how to place a limit buy order for a US stock using the Mojito library by specifying the exchange as 'NASD'. It requires the stock symbol, price, and quantity. ```python broker = KoreaInvestment(key, secret, acc_no=acc_no, exchange="NASD") resp = broker.create_limit_buy_order("TQQQ", 35, 1) print(resp) ``` -------------------------------- ### Fetch Current Stock Price (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python snippet demonstrates how to fetch the current price of a stock using the Mojito library's KoreaInvestment class. It requires API credentials and an account number. The output is pretty-printed. ```python import mojito import pprint key = "발급받은 API KEY" secret = "발급받은 API SECRET" acc_no = "12345678-01" broker = mojito.KoreaInvestment(api_key=key, api_secret=secret, acc_no=acc_no) resp = broker.fetch_price("005930") pprint.pprint(resp) ``` -------------------------------- ### Fetch OHLCV Data (Daily/Weekly/Monthly/Yearly) Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves OHLCV (Open, High, Low, Close, Volume) data for a stock. Supports daily, weekly, monthly, and yearly intervals, with an option to include adjusted prices. ```python import mojito import pandas as pd import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Fetch daily OHLCV data for Samsung Electronics resp = broker.fetch_ohlcv( symbol="005930", timeframe='D', # 'D': Daily, 'W': Weekly, 'M': Monthly, 'Y': Yearly adj_price=True # Reflect adjusted prices ) pprint.pprint(resp['output1']) # Stock basic information print(f"Number of data points retrieved: {len(resp['output2'])}") # Convert to Pandas DataFrame df = pd.DataFrame(resp['output2']) dt = pd.to_datetime(df['stck_bsop_date'], format="%Y%m%d") df.set_index(dt, inplace=True) df = df[['stck_oprc', 'stck_hgpr', 'stck_lwpr', 'stck_clpr']] df.columns = ['open', 'high', 'low', 'close'] df.index.name = "date" print(df.head()) # open high low close # date # 2024-01-02 72000 72500 71500 72000 # 2024-01-03 72100 73000 72000 72800 # ... ``` -------------------------------- ### Initialize KoreaInvestment Class for Trading Source: https://context7.com/sharebook-kr/mojito/llms.txt Initializes the main interface for Korea Investment & Securities REST API. It requires API keys, a secret, and an account number. Supports specifying domestic or international exchanges and enables a mock trading mode for testing. ```python import mojito # Domestic stock trading (default Seoul exchange) broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" # Account number (first 8 digits-last 2 digits) ) # Mock trading mode enabled broker_mock = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", mock=True # Mock trading mode ) # International stock trading (NASDAQ) broker_nasdaq = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", exchange="나스닥" # Supported: NASDAQ, NYSE, AMEX, HK, SH, SZ, TYO, HAN, HCM ) ``` -------------------------------- ### Create Market Buy Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Places a market buy order for stocks. ```APIDOC ## Create Market Buy Order - 시장가 매수 주문 ### Description Places a market buy order for stocks. Supports both domestic and international stocks. ### Method `create_market_buy_order(symbol: str, quantity: int)` ### Endpoint Not applicable (direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (str) - Required - The stock symbol to buy. - **quantity** (int) - Required - The number of shares to buy. ### Request Example ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Market buy order for 10 shares of Samsung Electronics resp = broker.create_market_buy_order( symbol="005930", quantity=10 ) pprint.pprint(resp) ``` ### Response #### Success Response (200) - **resp** (dict) - Response from the order placement, including status and order details. #### Response Example ```json { "rt_cd": "0", "msg_cd": "APBK0013", "msg1": "주문 전송 완료 되었습니다.", "output": { "KRX_FWDG_ORD_ORGNO": "91252", "ODNO": "0000117057", "ORD_TMD": "121052" } } ``` ``` -------------------------------- ### Create Limit Buy Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Places a limit buy order for stocks at a specified price. It can fetch the current price to set a desired buy price. Supports both domestic and international stocks. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) resp = broker.fetch_price("005930") current_price = int(resp['output']['stck_prpr']) print(f"현재가: {current_price:,}원") buy_price = current_price - 5000 resp = broker.create_limit_buy_order( symbol="005930", price=buy_price, quantity=4 ) pprint.pprint(resp) broker_nasdaq = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", exchange="나스닥" ) resp = broker_nasdaq.create_limit_buy_order( symbol="TQQQ", price=35, quantity=1 ) print(resp) ``` -------------------------------- ### Create Limit Buy Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Places a limit buy order for stocks at a specified price. ```APIDOC ## Create Limit Buy Order - 지정가 매수 주문 ### Description Places a limit buy order for stocks at a specified price. You can fetch the current price to set your desired buy price. ### Method `create_limit_buy_order(symbol: str, price: int, quantity: int)` ### Endpoint Not applicable (direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (str) - Required - The stock symbol to buy. - **price** (int) - Required - The price at which to buy. - **quantity** (int) - Required - The number of shares to buy. ### Request Example ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Fetch current price resp = broker.fetch_price("005930") current_price = int(resp['output']['stck_prpr']) print(f"현재가: {current_price:,}원") # Limit buy order for 4 shares of Samsung Electronics at 5000 KRW below current price buy_price = current_price - 5000 resp = broker.create_limit_buy_order( symbol="005930", price=buy_price, quantity=4 ) pprint.pprint(resp) # Limit buy order for international stock (Nasdaq - TQQQ) broker_nasdaq = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", exchange="나스닥" ) resp = broker_nasdaq.create_limit_buy_order( symbol="TQQQ", price=35, quantity=1 ) print(resp) ``` ### Response #### Success Response (200) - **resp** (dict) - Response from the order placement, including status and order details. #### Response Example ```json { "example": "order_response" } ``` ``` -------------------------------- ### Create Market Buy Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Executes a market buy order for stocks. Supports both domestic and international stocks. Requires stock symbol and quantity. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) resp = broker.create_market_buy_order( symbol="005930", quantity=10 ) pprint.pprint(resp) ``` -------------------------------- ### Create Sell Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Places a sell order for stocks, either at market price or a specified limit price. ```APIDOC ## Create Limit Sell Order / Create Market Sell Order - 매도 주문 ### Description Places a sell order for stocks, either at market price or a specified limit price. ### Method `create_market_sell_order(symbol: str, quantity: int)` `create_limit_sell_order(symbol: str, price: int, quantity: int)` ### Endpoint Not applicable (direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (str) - Required - The stock symbol to sell. - **quantity** (int) - Required - The number of shares to sell. - **price** (int) - Required for `create_limit_sell_order` - The price at which to sell. ### Request Example ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Market sell order for 5 shares of Samsung Electronics resp = broker.create_market_sell_order( symbol="005930", quantity=5 ) pprint.pprint(resp) # Limit sell order for 3 shares of Samsung Electronics at 75,000 KRW resp = broker.create_limit_sell_order( symbol="005930", price=75000, quantity=3 ) pprint.pprint(resp) ``` ### Response #### Success Response (200) - **resp** (dict) - Response from the order placement, including status and order details. #### Response Example ```json { "example": "order_response" } ``` ``` -------------------------------- ### Supported Exchanges List (Python) Source: https://context7.com/sharebook-kr/mojito/llms.txt This Python code defines a list of supported exchange identifiers that can be used with the 'exchange' parameter when initializing a broker instance in the Mojito project. It includes exchanges for Korea, NASDAQ, NYSE, and various Asian markets. ```python # exchange 파라미터로 사용 가능한 거래소 SUPPORTED_EXCHANGES = [ "서울", # 국내 (코스피, 코스닥) - 기본값 "나스닥", # NASDAQ "뉴욕", # NYSE "아멕스", # AMEX "홍콩", # SEHK "상해", # Shanghai "심천", # Shenzhen "도쿄", # TSE "하노이", # HNX "호치민" # HSX ] ``` -------------------------------- ### Fetch Daily Stock Price Data (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python code retrieves daily historical price data for a given stock symbol using the Mojito library. It requires authentication details and an account number. The results are displayed in a readable format. ```python import mojito import pprint key = "발급받은 API KEY" secret = "발급받은 API SECRET" acc_no = "12345678-01" broker = mojito.KoreaInvestment(api_key=key, api_secret=secret, acc_no=acc_no) resp = broker.fetch_daily_price("005930") pprint.pprint(resp) ``` -------------------------------- ### Real-time Stock Data via WebSocket (Python) Source: https://github.com/sharebook-kr/mojito/blob/main/README.md This Python code establishes a WebSocket connection using Mojito's KoreaInvestmentWS class to receive real-time stock data, including trades, quotes, and balance updates. It requires API keys, user ID, and subscribed stock codes/symbols. ```python import pprint import mojito with open("../../koreainvestment.key", encoding="utf-8") as f: lines = f.readlines() key = lines[0].strip() secret = lines[1].strip() if __name__ == "__main__": broker_ws = mojito.KoreaInvestmentWS(key, secret, ["H0STCNT0", "H0STASP0"], ["005930", "000660"], user_id="idjhh82") broker_ws.start() while True: data_ = broker_ws.get() if data_[0] == '체결': print(data_[1]) elif data_[0] == '호가': print(data_[1]) elif data_[0] == '체잔': print(data_[1]) ``` -------------------------------- ### Fetch Symbols Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves a list of stock symbols for KOSPI and KOSDAQ. ```APIDOC ## Fetch Symbols - 종목 코드 조회 ### Description Retrieves the entire list of stock codes for KOSPI and KOSDAQ. Returns a Pandas DataFrame with information such as stock code, name, and market classification. ### Method `fetch_symbols()` ### Endpoint Not applicable (direct method call) ### Parameters None ### Request Example ```python import mojito broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Fetch all symbols (KOSPI + KOSDAQ) symbols = broker.fetch_symbols() print(symbols.head()) # Filter for common stocks (group code 'ST') cond = symbols['그룹코드'] == 'ST' print(symbols[cond]) # Save to Excel file symbols.to_excel("korea_code.xlsx", index=False) ``` ### Response #### Success Response (200) - **symbols** (Pandas DataFrame) - DataFrame containing stock codes, names, group codes, and market information. #### Response Example ``` 단축코드 한글명 그룹코드 시장 0 005930 삼성전자 ST 코스피 1 000660 SK하이닉스 ST 코스피 2 035420 NAVER ST 코스피 ... ``` ``` -------------------------------- ### Check Buy Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Checks the purchasable quantity for a given stock and price. ```APIDOC ## Check Buy Order - 매수 가능 조회 ### Description Checks how many shares can be purchased for a specific stock at a given price. ### Method `check_buy_order(symbol: str, price: int, order_type: str)` ### Endpoint Not applicable (direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (str) - Required - The stock symbol. - **price** (int) - Required - The price for the potential buy order. - **order_type** (str) - Required - The type of order, e.g., "00" for limit order, "01" for market order. ### Request Example ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Check purchasable quantity for Samsung Electronics at 72,000 KRW (limit order) resp = broker.check_buy_order( symbol="005930", price=72000, order_type="00" ) pprint.pprint(resp) ``` ### Response #### Success Response (200) - **resp** (dict) - Response containing information about purchasable quantity and cash. #### Response Example ```json { "output": { "ord_psbl_qty": "138", "ord_psbl_cash": "10000000", ... } } ``` ``` -------------------------------- ### Fetch Balance Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves the stock balance for a specified exchange. ```APIDOC ## Fetch Balance ### Description Retrieves the stock balance for a specified exchange (e.g., Nasdaq). ### Method `fetch_balance()` ### Endpoint Not applicable (direct method call) ### Parameters None ### Request Example ```python import mojito import pprint broker_nasdaq = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", exchange="나스닥" ) balance = broker_nasdaq.fetch_balance() pprint.pprint(balance) ``` ### Response #### Success Response (200) - **balance** (dict) - A dictionary containing the stock balance information. #### Response Example ```json { "example": "balance_data" } ``` ``` -------------------------------- ### Fetch Stock Balance (NASDAQ) Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves the stock balance for a specified exchange, in this case, NASDAQ. It requires API credentials and an account number. ```python broker_nasdaq = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", exchange="나스닥" ) balance = broker_nasdaq.fetch_balance() pprint.pprint(balance) ``` -------------------------------- ### Check Buy Order Availability Source: https://context7.com/sharebook-kr/mojito/llms.txt Checks the number of shares that can be bought at a specified price for a given stock symbol. Returns the orderable quantity and available cash. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) resp = broker.check_buy_order( symbol="005930", price=72000, order_type="00" ) pprint.pprint(resp) ``` -------------------------------- ### Fetch Account Balance Information Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves stock holdings and cash balance information for an account. Supports both domestic and international accounts, automatically selecting the correct API based on the exchange configuration. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Fetch domestic stock balance resp = broker.fetch_balance() # List of held stocks (output1) for stock in resp['output1']: print(f"Stock: {stock['prdt_name']}, Quantity: {stock['hldg_qty']}, Valuation Amount: {stock['evlu_amt']}") # Account summary information (output2) pprint.pprint(resp['output2']) # Example Output: # [{'dnca_tot_amt': '10000000', # Total Deposit Amount # 'tot_evlu_amt': '15000000', # Total Valuation Amount # 'nass_amt': '5000000', ...}] # Net Asset Amount ``` -------------------------------- ### KoreaInvestmentWS - Real-time WebSocket Data Source: https://context7.com/sharebook-kr/mojito/llms.txt Establishes a WebSocket connection to receive real-time stock data such as trade prices, quotes, and trade notifications. Data is delivered via a queue. ```python import mojito api_key = "발급받은 API KEY" api_secret = "발급받은 API SECRET" broker_ws = mojito.KoreaInvestmentWS( api_key=api_key, api_secret=api_secret, tr_id_list=["H0STCNT0", "H0STASP0"], tr_key_list=["005930", "000660"], user_id="your_user_id" ) broker_ws.start() ``` -------------------------------- ### Fetch Today's 1-Minute OHLCV Data Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves 1-minute OHLCV data for the current trading day. The function automatically fetches data continuously from the market open (09:01) up to the specified time. ```python import mojito import pandas as pd broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Fetch today's 1-minute OHLCV data for Samsung Electronics result = broker.fetch_today_1m_ohlcv("005930") # Convert to Pandas DataFrame df = pd.DataFrame(result['output2']) dt = pd.to_datetime(df['stck_bsop_date'] + ' ' + df['stck_cntg_hour'], format="%Y%m%d %H%M%S") df.set_index(dt, inplace=True) df = df[['stck_oprc', 'stck_hgpr', 'stck_lwpr', 'stck_prpr', 'cntg_vol', 'acml_tr_pbmn']] df.columns = ['Open', 'High', 'Low', 'Close', 'Volume', 'Accumulated Trading Value'] df.index.name = "datetime" df = df[::-1] # Sort by time print(df) # Open High Low Close Volume Accumulated Trading Value # datetime # 2024-01-02 09:01:00 72000 72100 71950 72050 15000 1080000000 # 2024-01-02 09:02:00 72050 72100 72000 72080 12000 1944000000 # ... ``` -------------------------------- ### KoreaInvestmentWS - Real-time WebSocket Data Source: https://context7.com/sharebook-kr/mojito/llms.txt Receives real-time stock data via WebSocket. ```APIDOC ## KoreaInvestmentWS - 실시간 WebSocket 데이터 수신 ### Description Receives real-time trade prices, quotes, and trade notifications via WebSocket. This runs as a separate process and delivers data through a Queue. ### Method `KoreaInvestmentWS(api_key: str, api_secret: str, tr_id_list: list, tr_key_list: list, user_id: str = None)` `start()` ### Endpoint Not applicable (WebSocket connection) ### Parameters #### WebSocket Initialization Parameters - **api_key** (str) - Required - Your API key. - **api_secret** (str) - Required - Your API secret. - **tr_id_list** (list) - Required - List of TR IDs to subscribe to (e.g., `"H0STCNT0"` for trade price, `"H0STASP0"` for quote). - **tr_key_list** (list) - Required - List of keys (stock codes) to subscribe to. - **user_id** (str) - Optional - User ID for receiving trade notifications. ### Request Example ```python import mojito api_key = "발급받은 API KEY" api_secret = "발급받은 API SECRET" # Initialize WebSocket object broker_ws = mojito.KoreaInvestmentWS( api_key=api_key, api_secret=api_secret, tr_id_list=["H0STCNT0", "H0STASP0"], # Trade price, Quote tr_key_list=["005930", "000660"], # Samsung Electronics, SK Hynix user_id="your_user_id" # Optional: for trade notifications ) # Start the WebSocket connection broker_ws.start() ``` ### Response #### Success Response Data is received asynchronously via the configured Queue. #### Response Example Data will be pushed to the queue based on the subscribed TR IDs and keys. ``` -------------------------------- ### Fetch Symbols - Korean Stock Codes Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves a list of all stock codes for KOSPI and KOSDAQ. Returns a Pandas DataFrame containing stock code, name, group code, and market type. Allows filtering for common stocks and exporting to Excel. ```python import mojito broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) symbols = broker.fetch_symbols() print(symbols.head()) cond = symbols['그룹코드'] == 'ST' print(symbols[cond]) symbols.to_excel("korea_code.xlsx", index=False) ``` -------------------------------- ### Fetch Stock Current Price (Domestic/International) Source: https://context7.com/sharebook-kr/mojito/llms.txt Retrieves the current price of a stock using its symbol (domestic) or ticker (international). The function automatically calls the appropriate API based on the exchange configuration. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Fetch current price for domestic stock (Samsung Electronics: 005930) resp = broker.fetch_price("005930") pprint.pprint(resp) # Example Output: # {'output': {'stck_prpr': '72000', # Current Price # 'prdy_vrss': '-500', # Change from previous day # 'prdy_ctrt': '-0.69', # Percentage change # 'stck_hgpr': '72500', # High Price # 'stck_lwpr': '71500', ...}, # Low Price # 'rt_cd': '0', 'msg_cd': 'MCA00000', 'msg1': 'Successfully processed.'} # Extract current price current_price = int(resp['output']['stck_prpr']) print(f"Samsung Electronics current price: {current_price:,} KRW") # Fetch current price for international stock (NASDAQ - Tesla) broker_nasdaq = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01", exchange="나스닥" ) resp = broker_nasdaq.fetch_price("TSLA") pprint.pprint(resp) ``` -------------------------------- ### Modify Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Modifies an existing order's price or quantity. Requires order details like org_no, order_no, and new price/quantity. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) resp = broker.modify_order( org_no="91252", order_no="0000138450", order_type="00", price=60000, quantity=4, total=True ) pprint.pprint(resp) ``` -------------------------------- ### Modify Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Modifies an existing order's price or quantity. ```APIDOC ## Modify Order - 주문 정정 ### Description Modifies the price or quantity of an existing order. ### Method `modify_order(org_no: str, order_no: str, order_type: str, price: int, quantity: int, total: bool)` ### Endpoint Not applicable (direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **org_no** (str) - Required - The order organization number. - **order_no** (str) - Required - The order number. - **order_type** (str) - Required - The type of order (e.g., "00" for limit order). - **price** (int) - Required - The new price for the order. - **quantity** (int) - Required - The new quantity for the order. - **total** (bool) - Required - `True` if modifying the entire remaining quantity, `False` otherwise. ### Request Example ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Modify an order to change the price resp = broker.modify_order( org_no="91252", order_no="0000138450", order_type="00", price=60000, quantity=4, total=True ) pprint.pprint(resp) ``` ### Response #### Success Response (200) - **resp** (dict) - Response from the order modification request. #### Response Example ```json { "example": "modification_response" } ``` ``` -------------------------------- ### Cancel Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Cancels an existing order. ```APIDOC ## Cancel Order - 주문 취소 ### Description Cancels an existing order. Requires the order organization number (`org_no`) and order number (`order_no`). ### Method `cancel_order(org_no: str, order_no: str, quantity: int, total: bool)` ### Endpoint Not applicable (direct method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **org_no** (str) - Required - The order organization number (e.g., `KRX_FWDG_ORD_ORGNO`). - **order_no** (str) - Required - The order number. - **quantity** (int) - Required - The quantity to cancel. - **total** (bool) - Required - `True` to cancel the remaining quantity, `False` to cancel a partial quantity. ### Request Example ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) # Cancel the entire remaining quantity of an order resp = broker.cancel_order( org_no="91252", order_no="0000119206", quantity=4, total=True ) pprint.pprint(resp) ``` ### Response #### Success Response (200) - **resp** (dict) - Response from the order cancellation request. #### Response Example ```json { "example": "cancellation_response" } ``` ``` -------------------------------- ### Cancel Order Source: https://context7.com/sharebook-kr/mojito/llms.txt Cancels an existing stock order. Requires the order organization number (org_no) and order number (order_no). Can cancel the remaining quantity or a partial amount. ```python import mojito import pprint broker = mojito.KoreaInvestment( api_key="발급받은 API KEY", api_secret="발급받은 API SECRET", acc_no="12345678-01" ) resp = broker.cancel_order( org_no="91252", order_no="0000119206", quantity=4, total=True ) pprint.pprint(resp) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.