Automated Trading Development in Python, Kiwoom Securities API, Basic Information Request

Hello! In this post, we will explore how to request basic information using the Kiwoom Securities API, which is one of the methods for developing an automated trading system using Python. I believe many of you who are interested in stock trading have chosen this topic to automate your trading.

1. What is Kiwoom Securities API?

The Kiwoom Securities API is an interface that allows stock trading and information retrieval through a program provided by Kiwoom Securities. By using this API, you can access your Kiwoom Securities account to automatically perform stock trading and retrieve information. In particular, using Python allows for easy requests and responses handling, making it popular among many developers.

2. Setting Up the Development Environment

To use the Kiwoom Securities API, the following preparations are necessary:

  • Open a Kiwoom Securities account
  • Sign up for Kiwoom Securities OpenAPI+
  • Install and set up Kiwoom Securities API
  • Install Python and required libraries

2.1 Installing Kiwoom Securities OpenAPI+

Download and install the OpenAPI+ program provided by Kiwoom Securities. After installation, you need to log in to use the API.

2.2 Installing Python

If Python is not installed, please download and install it from the official website.

2.3 Installing Required Libraries

pip install pyqt5

The Kiwoom Securities API uses the Qt library, so you need to install PyQt5.

3. Accessing Kiwoom Securities API

To access the Kiwoom Securities API, you need to initialize the Kiwoom API first. You can write the following code for this.

import sys
from PyQt5.QtWidgets import QApplication
from kiwoom import Kiwoom

app = QApplication(sys.argv)
kiwoom = Kiwoom()
kiwoom.CommConnect()  # Display the login window

This code creates a popup window for logging in using PyQt5. Once the user logs in with their account, they can access the API.

4. Requesting Basic Information

After logging in, you can request basic stock information by using the GetMasterCodeName method. This method allows you to retrieve the name corresponding to the stock code.

code = "005930"  # Samsung Electronics
name = kiwoom.GetMasterCodeName(code)
print(name)  # Samsung Electronics

4.1 Example of Stock Information Retrieval

The following code is an example that takes several stock codes as input and outputs their corresponding names.

codes = ["005930", "000660", "035420", "051910"]  # Samsung Electronics, SK Hynix, NAVER, LG Household & Health Care
for code in codes:
    name = kiwoom.GetMasterCodeName(code)
    print(f"{code}: {name}")

5. Requesting Additional Information

In addition to retrieving basic stock information, you can request other information as well. For example, you can inquire about current price, opening price, high price, and low price. To do this, you can use the GetMasterLastPrice, GetMasterOpen, GetMasterHigh, and GetMasterLow methods.

current_price = kiwoom.GetMasterLastPrice(code)
open_price = kiwoom.GetMasterOpen(code)
high_price = kiwoom.GetMasterHigh(code)
low_price = kiwoom.GetMasterLow(code)

print(f"{code} Current Price: {current_price}, Opening Price: {open_price}, High Price: {high_price}, Low Price: {low_price}")

6. Conclusion

In this post, we looked at how to request basic information using the Kiwoom Securities API. Through the API, various information can be easily retrieved and utilized in automated trading logic. In the next post, we will explain how to fetch real-time stock information and the basic structure of an automated trading system using it. We appreciate your interest!

7. References

Python Automated Trading Development, Kiwoom Securities API, Fetching Account Information

Developing an automated trading system has become a very popular topic among stock investors these days. Such systems refer to mechanisms that use computer programs to buy and sell stocks automatically. In this course, we will learn about the first step in automated trading development using Python, focusing on how to retrieve account information using the Kiwoom Securities API.

1. What is the Kiwoom Securities API?

The Kiwoom Securities API is a service provided through Kiwoom Securities’ Open API, which enables users to view and trade stocks, futures, and options, as well as access account information and market data through programs. This API allows investors to automatically execute various strategies.

2. Preparing to Use the Kiwoom Securities API

To use the Kiwoom Securities API, the following preparations are necessary.

  1. Open a Kiwoom Securities account: You need to open an account with Kiwoom Securities.
  2. Apply for Open API: You need to apply for permission to use the Open API at Kiwoom Securities.
  3. Set up API environment: You need to configure the environment on the computer where the API will be used.

2.1 How to Apply for Open API

After logging into the Kiwoom Securities website, you can request permission to use the API through the Open API service application. Once your request is approved, you will receive an API key, allowing you to access the API.

2.2 API Environment Setup

To use the API, you need a package that can send and receive HTTP requests in Python. We will mainly use the pywin32 library to interact with Windows COM objects. This library can be installed using the following method.

pip install pywin32

3. Retrieving Account Information

Now, let’s learn how to retrieve account information through the Kiwoom Securities API with actual code.

3.1 Logging into the Kiwoom Securities API

To use the API, you must first log in. The following code shows how to create a login window using PyQt5 and check the login status.

import os
import sys
import pythoncom
import win32com.client

from PyQt5 import QtWidgets

class Kiwoom:
    def __init__(self):
        self.app = QtWidgets.QApplication(sys.argv)
        self.khw = win32com.client.Dispatch("KH OPENAPI")  # Create Kiwoom API object
        self.khw.OnEventConnect.connect(self._on_event_connect)

    def login(self):
        self.khw.CommConnect()  # Request login

    def _on_event_connect(self, err_code):
        if err_code == 0:
            print("Login successful")
        else:
            print("Login failed")

if __name__ == "__main__":
    kiwoom = Kiwoom()
    kiwoom.login()
    pythoncom.PumpThreads()  # Maintain event loop

3.2 Retrieving Account Information

If you have successfully logged in, you can now retrieve account information. Here is how to query account information through the Kiwoom Securities API.

class Kiwoom:
    # Following the previous code
    def get_account_info(self):
        account_list = self.khw.GetLoginInfo("ACCNO")  # Query account numbers
        print("Account list:", account_list)

        # Request information for all accounts
        for account in account_list.split(';'):
            if account:
                print("Account number:", account)

if __name__ == "__main__":
    kiwoom = Kiwoom()
    kiwoom.login()
    pythoncom.PumpThreads()
    kiwoom.get_account_info()  # Retrieve account information

The code above retrieves the user’s account list and prints each account number. You can retrieve account information using the GetLoginInfo method. Based on this information, you can retrieve other necessary information or proceed with trading.

4. Querying Asset Information by Account

Let’s learn how to query asset information for each account. You can check the quantity of stocks held and the assessed value, among other details.

class Kiwoom:
    # Following the previous code
    def get_account_assets(self):
        # Request asset information (AT: assessed value/current price)
        self.khw.SetInputValue("Account Number", "Enter account number")
        self.khw.SetInputValue("Password", "")  # Password
        self.khw.SetInputValue("Consultation Type", "0")  # 0: General, 1: Spot, 2: Futures, 3: Options
        self.khw.CommRcvData("010101", 0)  # Request

if __name__ == "__main__":
    kiwoom = Kiwoom()
    kiwoom.login()
    pythoncom.PumpThreads()
    kiwoom.get_account_assets()  # Retrieve asset information

5. Conclusion

In this course, we explained how to retrieve account information using the Kiwoom Securities API. In the future, you will learn how to implement trading functionalities and market information retrieval to develop your own automated trading system. In the next course, we will implement additional features for actual trading.

6. Reference Materials

Python Automated Trading Development, Kiwoom Securities API, Account Opening and Module Installation

The automated trading system is one of the rapidly growing fields in financial technology. Many traders are developing algorithm-based automated trading systems to enhance trading efficiency. This article will explain in detail how to use the Kiwoom Securities API required for automated trading development using Python, from opening an account to module installation.

1. Opening a Kiwoom Securities Account

To develop an automated trading system, you first need to open a securities account. Here is how to open an account with Kiwoom Securities.

1.1. Visit the Kiwoom Securities Website

Access the official Kiwoom Securities website (https://www.kiwoom.com) and click on the ‘Open Account’ menu.

1.2. Open Account Online

To open an account online, you need to complete identity verification. Prepare your digital certificate and identification (resident registration card, driver’s license).

1.3. Input Information and Submit Documents

Enter the required personal information and select the type of securities account. Then, verify your identification and submit the required documents.

1.4. Account Opening Completed

Once all procedures are completed, the account will be opened within about 1 to 2 days. After the account is opened, you will be eligible to use the API for automated trading programs.

2. Installing Kiwoom Securities OPEN API

To use Kiwoom Securities’ API, specific software is required. This software can be downloaded from Kiwoom’s website.

2.1. Download OPEN API

Kiwoom Securities OPEN API can be found in the ‘Download’ menu. Download several files related to the SDK.

2.2. Check User Manual

Kiwoom Securities provides a user manual for using the OPEN API. You can learn about the functionalities and usage of the API through the manual.

2.3. Environment Setup

After unzipping the downloaded files in an appropriate location, you need to set the environment variables. If you are a Windows user, add the following to the system variables in ‘My Computer’ > ‘Properties’ > ‘Advanced System Settings’ > ‘Environment Variables’:

PATH : C:\Kiwoom\OpenAPI\

2.4. API Authentication Key Issuance

To use Kiwoom Securities’ API, an authentication key is required. This key can be obtained by contacting Kiwoom Securities’ customer service.

3. Installing Python and Required Libraries

In this section, we will learn how to install Python and related libraries.

3.1. Install Python

Python can be installed from the official website (https://www.python.org/downloads/). Make sure to check the ‘Add Python to PATH’ option during the installation process.

3.2. Install PyQt5 and numpy Libraries

PyQt5 is needed to build the UI of the automated trading program. Additionally, Numpy will be used for data processing. Use the following command in CMD to install:

pip install PyQt5 numpy

4. Integrating Kiwoom Securities API with Python

Now, let’s develop a real trading program using the Kiwoom Securities API.

4.1. Define API Class

First, we define a class to call Kiwoom Securities’ OpenAPI.

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QAxContainer import QAxWidget

class Kiwoom:
    def __init__(self):
        self.app = QApplication(sys.argv)
        self.kw_app = QAxWidget('KWOpenAPI.KWOpenAPICtrl.1')
        self.kw_app.OnEventConnect.connect(self.event_connect)

    def event_connect(self, err_code):
        if err_code == 0:
            print("Connection successful")
        else:
            print(f"Connection failed: {err_code}")

    def login(self):
        self.kw_app.dynamicCall("CommConnect()")

if __name__ == "__main__":
    kiwoom = Kiwoom()
    kiwoom.login()
    sys.exit(kiwoom.app.exec_())

4.2. Add Trading Request Function

Add a function for trading requests.

def buy(self, code, qty):
    self.kw_app.dynamicCall("SendOrder(QString, QString, QString, int, QString, int, double, QString)", "buy", "YOUR_ACCOUNT", code, qty, "", "0", "0", "0")

4.3. Run and Test the Program

Run the entire code to check if the trading connection is functioning properly. The environment setup must be correct, and Kiwoom Securities’ API should work appropriately.

if __name__ == "__main__":
    kiwoom = Kiwoom()
    kiwoom.login()
    # Trading Test
    kiwoom.buy("005930", 1)  # Buy one share of Samsung Electronics
    sys.exit(kiwoom.app.exec_())

5. Conclusion

This article explained the basics of opening a Kiwoom Securities account, module installation, and API integration for automated trading development using Python. More testing and stability assurance are needed to execute actual trades. Additionally, risk management and various trading strategies are necessary for actual trading.

In the next article, we will explore the implementation of more advanced automated trading systems, data analysis, and algorithm improvement.

We hope that all readers can build a successful automated trading system!

Automated Trading Development in Python, Kiwoom Securities API, Development Environment Setup

As interest in stock investment has recently increased, many investors are looking to build automated trading systems. In particular, Python is favored by many developers due to its powerful libraries and ease of use. This article will provide a detailed explanation of the development process for automated trading using Python, as well as how to set up a development environment using the Kiwoom Securities API. After reading this article, you will gain a foundational understanding to create your own automated trading program, along with practical development examples.

1. What is an Automated Trading System?

An automated trading system is designed for a computer program to analyze market data and execute trades automatically without user instructions. This helps traders make consistent investment decisions without being swayed by emotions in the market. The automated trading system generates trading signals based on specific algorithms and uses these signals to make buy or sell decisions. This system requires a combination of programming knowledge and trading strategies to operate successfully.

2. What is the Kiwoom Securities API?

The Kiwoom Securities API is a tool that enables trading various financial products such as stocks, futures, and options through a program provided by Kiwoom Securities. This API offers users a range of functions, including real-time data, trade execution, balance checking, and yield analysis. Using the Kiwoom Securities API, you can easily develop and operate your own trading system.

3. Setting Up the Development Environment

3.1. Preparation Steps

To develop an automated trading system, the following preparations are necessary.

  • Install Python: Download and install Python version 3.6 or higher.
  • Open a Kiwoom Securities Account: Open an account with Kiwoom Securities and apply for API usage.
  • Install Python Libraries: The following libraries will be used for development.
    • pykiwoom: A library that helps use the Kiwoom Securities API in Python.
    • pandas: A library for data analysis and manipulation.
    • numpy: A library for numerical calculations.
    • matplotlib: A library for data visualization.

3.2. Installing Python

To install Python, download the installation file suitable for your operating system from [python.org](https://www.python.org/downloads/) and install it. After installation, open the command prompt or terminal and enter the command `python –version` to verify if it was installed correctly.

3.3. Installing Libraries

Use pip to install the previously mentioned libraries. Enter the following commands in the command prompt one by one.

        pip install pykiwoom
        pip install pandas
        pip install numpy
        pip install matplotlib
    

3.4. Configuring the Kiwoom Securities API

To use the Kiwoom Securities API, you need to install and log in to the Kiwoom Securities HTS ‘Hero Moon’. After logging in, you can apply for API usage through the ‘Option’ – ‘API Settings’ menu. Once the application is completed, you can receive an API key.

4. Creating a Basic Trading System

Now that the development environment is ready, let’s implement a basic trading system. The basic structure of an automated trading system is as follows.

  1. Collect market data
  2. Generate trading signals according to the algorithm
  3. Execute trades
  4. Record and analyze results

4.1. Data Collection

First, let’s collect stock data using the Kiwoom Securities API. Below is an example of requesting data for a specific stock using pykiwoom.

        
        from pykiwoom.kiwoom import Kiwoom
        import pandas as pd

        kiwoom = Kiwoom()
        kiwoom.CommConnect()

        # Set stock code
        code = "005930"  # Samsung Electronics

        # Request data
        df = kiwoom.get_master_last_price(code)  # Request current price
        print(df)
        
    

4.2. Generating Trading Signals

Now let’s set a basic trading algorithm. For example, we can generate trading signals based on the Simple Moving Average (SMA).

        
        def generate_signal(data):
            data['SMA_5'] = data['close'].rolling(window=5).mean()
            data['SMA_20'] = data['close'].rolling(window=20).mean()
            data['signal'] = 0
            data['signal'][5:] = np.where(data['SMA_5'][5:] > data['SMA_20'][5:], 1, 0)  # Buy signal
            return data
        
    

4.3. Executing Trades

You can write code to execute trades based on signals as follows.

        
        def execute_trade(signal):
            if signal == 1:
                # Execute buy
                kiwoom.SendOrder("buysignal", "0101", code, 1, 0, 0, "03", "")
            elif signal == 0:
                # Execute sell
                kiwoom.SendOrder("sellsignal", "0101", code, 1, 0, 0, "03", "")
        
    

5. Integrating the Entire System

Finally, let’s integrate all the above elements into a single program. We will periodically collect market data, generate signals, and execute trades.

        
        import time

        while True:
            # Collect data
            data = kiwoom.get_market_data(code)
            
            # Generate trading signal
            signal_data = generate_signal(data)
            latest_signal = signal_data['signal'].iloc[-1]
            
            # Execute trade
            execute_trade(latest_signal)
            
            # Wait for 30 seconds
            time.sleep(30)
        
    

6. Conclusion

In this article, we explored how to build a basic automated trading system using Python and the Kiwoom Securities API. We examined the flow from data collection to generating trading signals and executing trades. I hope this script helps you in developing your own more complex and sophisticated trading systems. Based on a deep understanding of programming and investing, I encourage you to try various strategies.

In the future, I also plan to prepare articles on how to enhance automated trading systems using machine learning and data analysis techniques. Thank you for your interest!

Automatic Trading Development with Python, Kiwoom Securities API, Introduction to PyQt

Recently, automatic trading systems in the stock market have attracted attention among many investors.
In particular, Python has established itself as a suitable language for financial data processing and
automatic trading system development due to its simplicity and powerful libraries. In this article, we will
explore how to develop an automatic trading system using the Kiwoom Securities API and
how to utilize PyQt for building a user interface.

1. Self Diagnosis: Why Use an Automatic Trading System?

An automatic trading system allows trading to be executed automatically based on predefined algorithms,
free from human emotions and momentary judgments. This increases the possibility of maximizing profits
by maintaining consistency in trading and optimizing trading time.

2. Overview of Kiwoom Securities API

The Kiwoom Securities API is a tool provided by Kiwoom Securities that helps to perform trading programmatically.
Through this API, users can access real-time stock data, create orders, and manage trading history.

2.1. Installing Kiwoom API

To use the Kiwoom API, you must first install Kiwoom Securities’ Open API+. After installation, you can set up
the API through the following steps.

1. Download 'Open API+' from the Kiwoom Securities homepage.
2. After installation, run 'OPKorea_1.2.0.exe' in the 'Kiwoom Securities Open API' folder.
3. Enter the API key and password to authenticate.
4. Check if the API is functioning properly.

2.2. Key Features of Kiwoom API

  • Stock Search
  • Real-Time Price Inquiry
  • Order and Trade Execution
  • Transaction History Inquiry
  • Portfolio Management

3. Integrating Python with Kiwoom Securities API

To integrate the Kiwoom Securities API using Python, you can use a GUI framework like PyQt5.
Let’s look at example code using the Kiwoom API and PyQt5.

3.1. Installing PyQt5

pip install PyQt5
pip install PyQt5-tools

3.2. Implementing Login via Kiwoom API

Below is the basic code for logging into the Kiwoom Securities API.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import pyqtSlot
import win32com.client

class Kiwoom(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Kiwoom Securities Automatic Trading System")
        self.setGeometry(300, 300, 400, 300)
        self.login_button = QPushButton("Login", self)
        self.login_button.clicked.connect(self.login)
        self.login_button.resize(100, 40)
        self.login_button.move(150, 130)

        self.kiwoom = win32com.client.Dispatch("KHOpenAPI.KHOpenAPICtrl.1")
    
    @pyqtSlot()
    def login(self):
        self.kiwoom.CommConnect()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    kiwoom = Kiwoom()
    kiwoom.show()
    sys.exit(app.exec_())

4. Real-Time Stock Data Inquiry

Now, after adding the login feature, let’s add the real-time data inquiry functionality.
To access real-time prices, we need to write a function for data requests.

class Kiwoom(QMainWindow):
    # ... Previous code omitted ...
    def retrieve_stock_data(self, stock_code):
        self.kiwoom.SetInputValue("종목코드", stock_code)
        self.kiwoom.CommRqData("Basic Stock Information", "opt10001", 0, "0101")

    def OnReceiveTrData(self, scrno, rqname, trcode, recordname, prevnext, 
                       dataLength, errorCode, message, splm):
        print("Data Received")
        self.current_price = self.kiwoom.GetCommData(trcode, rqname, 0, "Current Price")
        print(f"Current Price: {self.current_price.strip()}")

4.1. Adding Real-Time Data Reception Functionality

We added the `OnReceiveTrData` method to the basic code above.
In this method, we will implement the logic for processing the received data.

5. Implementing Order Functionality

Now, let’s add a simple order functionality.
Let’s look at a code example for handling buy and sell orders.

def buy_stock(self, stock_code, quantity):
    self.kiwoom.SetInputValue("Stock Code", stock_code)
    self.kiwoom.SetInputValue("Order Quantity", quantity)
    self.kiwoom.SetInputValue("Price", 0)  # Market Price
    self.kiwoom.SetInputValue("Order Type", 1)  # Buy
    self.kiwoom.CommRqData("Stock Order", "opt00001", 0, "0101")

def sell_stock(self, stock_code, quantity):
    self.kiwoom.SetInputValue("Stock Code", stock_code)
    self.kiwoom.SetInputValue("Order Quantity", quantity)
    self.kiwoom.SetInputValue("Price", 0)  # Market Price
    self.kiwoom.SetInputValue("Order Type", 2)  # Sell
    self.kiwoom.CommRqData("Stock Order", "opt00001", 0, "0101")

6. Optimizing GUI Design

You can design a more intuitive and user-friendly GUI using PyQt5.
By using various widgets, user experience can be enhanced.

self.quantity_input = QLineEdit(self)
self.quantity_input.move(150, 50)
self.quantity_input.resize(100, 30)

self.stock_code_input = QLineEdit(self)
self.stock_code_input.move(150, 90)
self.stock_code_input.resize(100, 30)

self.buy_button = QPushButton("Buy", self)
self.buy_button.move(150, 130)
self.buy_button.clicked.connect(self.on_buy_click)

6.1. Handling Click Events for the Order Button

def on_buy_click(self):
    stock_code = self.stock_code_input.text()
    quantity = int(self.quantity_input.text())
    self.buy_stock(stock_code, quantity)

7. Developing an Automatic Trading Algorithm

Now, let’s implement the core algorithm of automatic trading.
A simple strategy to consider is the moving average crossover strategy.

def moving_average_strategy(self):
    short_window = 5
    long_window = 20
    prices = self.get_past_prices(stock_code)

    short_ma = prices[-short_window:].mean()
    long_ma = prices[-long_window:].mean()

    if short_ma > long_ma:
        self.buy_stock(stock_code, 1)
    elif short_ma < long_ma:
        self.sell_stock(stock_code, 1)

7.1. Getting Historical Price Data

def get_past_prices(self, stock_code):
    # Implement the method to retrieve historical price data
    pass

8. Termination and Continuous Trading

When managing assets, it is very important to monitor trading history after orders are executed and
take necessary actions. After a trade is completed, the process of updating the portfolio is necessary.

def update_portfolio(self):
    # Implement the method to update portfolio status
    pass

Conclusion

In this article, we explored how to implement a simple automatic trading system using the
Kiwoom Securities API with Python. By adding a user interface through PyQt, we were able to
create a more intuitive and user-friendly system. Next, it is recommended to build upon this
foundation by adding more complex and diverse algorithms to create a personalized automatic trading system.