Python Automated Trading Development, Kiwoom Securities API, Event Handling

Hello, today I will explain in detail how to develop an automated trading system using Python, particularly utilizing the Kiwoom Securities API. An automated trading system is a program that automatically executes algorithms for stock trading to generate profits. This course will cover in-depth topics ranging from basic installation to event handling and using the API.

1. Preparing the Kiwoom Securities API

To implement automated trading using the Kiwoom Securities API, you first need to obtain an API key. The subsequent steps are as follows:

  • Log in to the Kiwoom Securities homepage and register as an API user.
  • Obtain an API key and install the necessary libraries.

1.1 Library Installation

The Kiwoom Securities API works in a Windows environment, so you must first install Python and PyQt5. These are essential packages for constructing the UI.

pip install PyQt5

Next, download and install the Kiwoom Securities Open API. The API can be found on the Kiwoom Securities homepage.

2. Logging into the Kiwoom Securities API

You first need to log in to Kiwoom Securities through the API. The following code is an example of handling user login.

import win32com.client
import pythoncom
import time

class Kiwoom:
    def __init__(self):
        self.api = win32com.client.Dispatch("KHOPENAPI.KHOpenAPICtrl.1")
        self.login()

    def login(self):
        self.api.CommConnect()
        while self.api.GetConnectState() == 0:
            time.sleep(1)

kiwoom = Kiwoom()

The above code logs into Kiwoom Securities and checks the connection state. After logging in, you can retrieve the desired information.

3. Event Handling

Event handling is the core of the automated trading system. It allows you to perform appropriate actions when specific events occur.

3.1 Order Events

To send orders or check statuses, you need to specify event handlers. Below is the code for handling order events.

class Kiwoom:
    def __init__(self):
        self.api = win32com.client.Dispatch("KHOPENAPI.KHOpenAPICtrl.1")
        self.api.OnEventConnect.connect(self.on_event_connect)

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

    def send_order(self, order_type, code, qty, price, price_type):
        order = self.api.SendOrder("Order Name", "5000", self.api.GetAccList()[0], order_type, code, qty, price, price_type, "")
        return order

The above function is responsible for sending orders, and you can check the success of the order via the return value.

3.2 Real-time Balance Events

If you want to monitor the balance in real-time, you can implement it as follows.

class Kiwoom:
    def __init__(self):
        self.api = win32com.client.Dispatch("KHOPENAPI.KHOpenAPICtrl.1")
        self.api.OnReceiveRealData.connect(self.on_receive_real_data)

    def on_receive_real_data(self, code, data):
        print(f"Balance information received: {code}, {data}")

This code is called every time data comes in real-time.

4. Designing Automated Trading Strategies

Designing a strategy for automated trading is necessary. For example, let’s look at a strategy based on moving averages. Moving averages can help determine the timing for buying or selling stocks.

class MovingAverageStrategy:
    def __init__(self):
        self.short_window = 5
        self.long_window = 20
        self.data = []

    def compute_moving_average(self):
        if len(self.data) < self.long_window:
            return None
        short_ma = sum(self.data[-self.short_window:]) / self.short_window
        long_ma = sum(self.data[-self.long_window:]) / self.long_window
        return short_ma, long_ma

This strategy generates trading signals by comparing the short-term moving average and the long-term moving average.

5. Executing Orders

Now that we have implemented the automated trading system through events, the final step is to write the code that actually executes orders.

def execute_trade(self):
    short_ma, long_ma = self.compute_moving_average()
    if short_ma is not None and short_ma > long_ma:
        print("Buying point")
        self.send_order(1, "005930", 10, 0, 0)  # Example of buying Samsung Electronics
    elif short_ma is not None and short_ma < long_ma:
        print("Selling point")
        self.send_order(2, "005930", 10, 0, 0)  # Example of selling Samsung Electronics

This code executes orders based on a moving average-based trading strategy. Buying and selling points are determined by the crossovers of the moving averages.

6. Complete Automated Trading System

By integrating all the above elements, you can implement the complete automated trading system. The final code combining all classes is as follows.

class AutoTradingSystem:
    def __init__(self):
        self.kiwoom = Kiwoom()
        self.strategy = MovingAverageStrategy()

    def run(self):
        while True:
            self.kiwoom.api.BlockRequest("opw00018", ...) # Request balance information
            self.strategy.data.append(self.get_market_data())  # Collect market data
            self.strategy.execute_trade()  # Execute trading
            time.sleep(60)  # Execute periodically

This is the basic structure of an automated trading system. Properly combine APIs, event handling, and trading strategies to create your own automated trading system.

Conclusion

In this tutorial, we explored how to implement an automated trading system using the Kiwoom Securities API with Python and the importance of event handling. Understand and utilize each component to develop your own automated trading system. Additionally, try out more strategies and consider using backtesting frameworks like Thoth to check the performance of your strategies. Continuous research is necessary to create algorithms that reflect the current market volatility.

References