Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API

Hello, investors! Today, we will explore how to develop automated trading using Python. In particular, we will focus on building an automated trading system using the Kiwoom Securities API, which is widely used in South Korea.

1. What is automated trading?

Automated trading refers to performing trades automatically according to a pre-set investment strategy using a computer program. This allows the exclusion of human emotions and enables quick responses to market volatility. By utilizing an automated trading system, repetitive trading tasks can be automated, saving time and effort.

2. Introduction to Kiwoom Securities API

The Kiwoom Securities API is an interface that allows you to use various functions provided by Kiwoom Securities for stock trading. Through this API, you can programmatically manage stock price information, orders, and execution details, allowing for the design of various automated trading algorithms from basic trading functions to advanced strategies.

2.1 Installing and setting up the API

To use the API, you must first install Kiwoom Securities’ Open API+. Follow the steps below to proceed with the installation.

  1. Visit the Kiwoom Securities website and download the Open API+.
  2. Configure the necessary environment settings during the installation process.
  3. After the installation is complete, you will be ready to use the API by logging into Kiwoom Securities.

2.2 Basic environment setup after installation

Install the required packages to use the Kiwoom Securities API in the Python environment. The primarily used packages are PyQt5 and pythoncom. You can install them with the following command:

pip install PyQt5 pythoncom

3. Using the Kiwoom Securities API

Now, let’s start using the Kiwoom Securities API to fetch data and place orders.

3.1 Implementing the API class

Let’s implement a class to utilize the Kiwoom Securities API. It will include the basic functions for logging in and fetching price data.

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

class KiwoomAPI:
    def __init__(self):
        self.app = QApplication(sys.argv)
        self.api = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.api.OnEventConnect.connect(self.connected)
        self.login()

    def connected(self, errCode):
        if errCode == 0:
            print("Login successful")
        else:
            print("Login failed", errCode)

    def login(self):
        self.api.dynamicCall("CommConnect()")
        self.app.exec_()

    def get_price(self, code):
        self.api.dynamicCall("SetInputValue(QString, QString)", "Stock Code", code)
        self.api.dynamicCall("CommRqData(QString, QString, int, QString)", "Basic Stock Information", "opt10001", 0, "0101")
        time.sleep(1)  # Wait for data reception
        return self.api.dynamicCall("GetCommData(QString, QString, int, QString)", "Basic Stock Information", "opt10001", 0, "Current Price")

api = KiwoomAPI()
price = api.get_price("005930")  # Samsung Electronics
print("Samsung Electronics Current Price:", price)

The code above logs into the Kiwoom Securities API and implements the basic functionality to fetch the current price of a specific stock (Samsung Electronics). It is important to ensure a waiting time after data requests at the detail level.

3.2 Placing stock orders

Next, let’s learn how to place stock orders. We will add the following code to implement a buy order function.

class KiwoomAPI:
    # ... Previous code omitted ...

    def buy_stock(self, code, qty):
        self.api.dynamicCall("SetInputValue(QString, QString)", "Stock Code", code)
        self.api.dynamicCall("SetInputValue(QString, QString)", "Order Quantity", qty)
        self.api.dynamicCall("SetInputValue(QString, QString)", "Price", self.get_price(code))
        self.api.dynamicCall("SetInputValue(QString, QString)", "Transaction Type", "1") # 1: Buy, 2: Sell
        self.api.dynamicCall("CommRqData(QString, QString, int, QString)", "Stock Order", "opt10003", 0, "0101")
        time.sleep(1)
        print("Order completed")

# Example usage
api.buy_stock("005930", 1)  # Buy 1 share of Samsung Electronics

4. Building an automated trading system

Now, based on our understanding of the basic API usage, let’s write a simple automated trading strategy. For example, it can be implemented to automatically buy when certain conditions are met.

4.1 Simple Moving Average Strategy

One of the simplest automated trading strategies is to use moving averages. Buy when the short-term moving average crosses above the long-term moving average and sell when it crosses below.

import pandas as pd

def get_historical_data(code, count):
    # Request historical data
    # This part needs to fetch data through another call provided by the Kiwoom API.
    return pd.DataFrame()  # Return in DataFrame format

def trading_strategy():
    historical_data = get_historical_data("005930", 100)
    historical_data['MA5'] = historical_data['Close'].rolling(window=5).mean()
    historical_data['MA20'] = historical_data['Close'].rolling(window=20).mean()

    if historical_data['MA5'].iloc[-2] < historical_data['MA20'].iloc[-2] and historical_data['MA5'].iloc[-1] > historical_data['MA20'].iloc[-1]:
        print("Buy signal generated")
        api.buy_stock("005930", 1)
    elif historical_data['MA5'].iloc[-2] > historical_data['MA20'].iloc[-2] and historical_data['MA5'].iloc[-1] < historical_data['MA20'].iloc[-1]:
        print("Sell signal generated")
        # api.sell_stock("005930", 1)  # Sell logic can be added later

trading_strategy()

5. Precautions and Conclusion

There are many things to be cautious about when implementing automated trading. Please keep the following points in mind.

  • Before investing real money, validate the strategy’s effectiveness with sufficient backtesting.
  • Be careful not to exceed the API call limits, and implement exception handling if necessary.
  • Consider market volatility and prepare risk management measures.

In this course, we covered the basics of building an automated trading system using Python. I hope you were able to understand the basic flow through examples of API usage and simple strategy implementations. I wish this course helps you in developing more complex systems and strategies in the future.

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

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!

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!