Python Automated Trading Development, Kiwoom Securities API, Widgets and Windows

In recent years, the changes in financial markets have been progressing very rapidly. In particular, automated trading systems are providing more opportunities for individual investors. This article will start from the basics of automated trading development using Python, explain how to use the Kiwoom Securities API, and detail the use of GUI widgets and windows.

1. Understanding Automated Trading Systems

An automated trading system is software that automatically executes trades when certain conditions are met. These systems can be applied to various assets such as stocks, foreign exchange, and cryptocurrencies. Many approaches can be used in this system, including algorithmic trading, high-frequency trading, and event-driven trading.

2. Python and Automated Trading

Python is a very popular language for developing stock trading algorithms, along with powerful data processing libraries. Data analysis libraries such as Pandas, Numpy, and Matplotlib make data collection and processing easier.

3. Overview of Kiwoom Securities API

Kiwoom Securities is one of the most popular securities firms in Korea, offering an API for stock trading. This allows users to conduct stock trades directly through a program.

The Kiwoom Securities API is called Kiwoom Open API, providing functionalities such as real-time data collection, order execution, and account information verification. To use this API, you need to install the HTS (Home Trading System) provided by Kiwoom Securities and configure settings for API usage.

3.1. Installing and Configuring the Kiwoom Securities API

  1. Download and install the HTS from the Kiwoom Securities website.
  2. After installation, configure the settings for API usage in the program.
  3. Apply for API usage through the Kiwoom Securities customer center.
  4. Obtain the API key and prepare it for use in the code.

4. Using the Kiwoom Securities API in Python

The Kiwoom Securities API is a COM (Component Object Model)-based API; to use this API in Python, you need a library called pywin32. Below is how to install this library.

pip install pywin32

4.1. Example Code for Kiwoom Securities API

Below is a basic example code to connect to the Kiwoom Securities API and retrieve account information using Python.

import win32com.client
import pythoncom
import time

# Initialize Kiwoom API
kiwoom = win32com.client.Dispatch("KHOPENAPI.KHOpenAPICtrl.1")

# Initialize COM
def run_loop():
    pythoncom.PumpWaitingMessages()

# Login
kiwoom.CommConnect()

# Wait after login
run_loop()
    
# Retrieve account number
account_num = kiwoom.GetLoginInfo("ACCNO")
print(f"Account Number: {account_num}")

# Retrieve account balance
def get_account_balance(account_num):
    kiwoom.SetInputValue("Account Number", account_num)
    kiwoom.CommRqData("Balance Inquiry", "opw00001", 0, "4100")

get_account_balance(account_num)

5. Implementing Automated Trading Logic

The core of an automated trading system is the trading logic. It is necessary to generate buy and sell signals based on specific trading strategies and execute them through the API.

5.1. Example of a Basic Trading Strategy

Below is an example implementing a simple moving average crossover strategy. This strategy generates a buy signal when the short-term moving average crosses above the long-term moving average and generates a sell signal in the opposite case.


import pandas as pd

# Stock data collection function
def get_stock_data(stock_code, start_date, end_date):
    # Fetch stock data (can use yfinance or another data source)
    return pd.DataFrame()  # Return the actual stock data frame

# Trading strategy function
def trading_strategy(stock_code):
    data = get_stock_data(stock_code, '2022-01-01', '2023-01-01')
    
    # Calculate moving averages
    data['short_ma'] = data['close'].rolling(window=5).mean()
    data['long_ma'] = data['close'].rolling(window=20).mean()
    
    # Generate buy and sell signals
    data['signal'] = 0
    data['signal'][data['short_ma'] > data['long_ma']] = 1  # Buy signal
    data['signal'][data['short_ma'] < data['long_ma']] = -1  # Sell signal
    
    return data.final_signals

# Test
stock_code = 'A005930'  # Samsung Electronics
signals = trading_strategy(stock_code)
print(signals)

6. GUI Widgets and Windows

When developing an automated trading system, the user interface should also be considered. Libraries such as PyQt or Tkinter can be used to create a user-friendly GUI.

6.1. Simple GUI Example Using Tkinter

Below is a simple example of a GUI for an automated trading system implemented using Tkinter.


import tkinter as tk
from tkinter import messagebox

def start_trading():
    # Implement the trading start feature
    messagebox.showinfo("Notification", "Automated trading started")

# GUI setup
root = tk.Tk()
root.title("Automated Trading System")

start_button = tk.Button(root, text="Start Automated Trading", command=start_trading)
start_button.pack()

root.mainloop()

7. Conclusion

This article introduced basic knowledge and example codes necessary for developing an automated trading system using Python. By using the Kiwoom Securities API, you can collect real-time data and implement a system that interacts with users through a GUI. Automated trading systems provide many benefits to individual investors; however, incorrect strategies or excessive risk settings can lead to significant losses, so a cautious approach is necessary.

In the future, I hope to contribute to successful investments while studying the advancement of automated trading systems and various strategies.