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.