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

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.

Automated Trading Development with Python, Kiwoom Securities API, Sign Up for Paper Trading

This article will detail how to develop an automated trading system using Python and how to use the Kiwoom Securities API. It will also include the process of signing up for simulated trading, providing a way to safely test the developed program before investing real money.

1. What is Automated Trading?

Automated trading (Algorithmic Trading) refers to a system where a program automatically executes trades according to a specific algorithm. This allows for faster and more accurate trading, eliminating emotional judgment.

2. What is the Kiwoom Securities API?

The Kiwoom Securities API is a program interface provided by Kiwoom Securities that allows investors to directly trade stocks through their own programs. The API enables easy access to real-time pricing information, order entry, execution confirmation, and more.

2.1 Advantages of the API

  • Real-time data provision
  • Automation of orders and trades programmatically
  • Implementation of various strategies

2.2 Disadvantages of the API

  • Requires a thorough understanding and practice
  • Need to ensure system stability and reliability

3. How to Sign Up for Simulated Trading

Simulated trading is a system that allows you to experience investing under the same conditions as real trading. Open a simulated trading account provided by Kiwoom Securities and try it for free.

3.1 How to Open a Simulated Trading Account

  1. Visit the Kiwoom Securities website and complete the registration process.
  2. After logging in, select the ‘Simulated Trading’ menu.
  3. Proceed with the application for opening a simulated trading account.
  4. Once the application is completed, you will receive your account number and password.

4. Installing the Kiwoom Securities API

Next, you need to install the necessary software to use the Kiwoom Securities API as follows.

4.1 Prerequisites

  • Install Kiwoom Securities OpenAPI+
  • Install Python (recommended version: 3.8 or higher)
  • Python modules: pywin32, numpy, pandas, etc.

4.2 Installing Kiwoom Securities OpenAPI+

The Kiwoom Securities OpenAPI+ can be downloaded from Kiwoom Securities, and after installation, you need to log in to configure your settings. After installation, you must activate the ‘Switch to Simulated Trading’ checkbox in the ‘API Settings’.

5. Writing an Automated Trading Program in Python

Now, let’s create an automated trading program in Python. Below is an example code for a basic trading system.

5.1 Basic Code Structure

import sys
import time
import win32com.client

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

    def login(self):
        # Login
        self.api.CommConnect()
        print("Login completed")

    def buy(self, code, qty):
        # Buy function
        self.api.SendOrder("buyOrder", "0101", self.api.GetAccountList(0), 1, code, qty, 0, "03", "")

    def sell(self, code, qty):
        # Sell function
        self.api.SendOrder("sellOrder", "0101", self.api.GetAccountList(0), 2, code, qty, 0, "03", "")

    def check_balance(self):
        # Check balance
        balance = self.api.GetAccInfo(1)
        print("Current balance:", balance)

if __name__ == "__main__":
    trader = AutoTrade()
    trader.check_balance()
    trader.buy("005930", 1)  # Buy Samsung Electronics
    time.sleep(1)
    trader.sell("005930", 1)  # Sell Samsung Electronics

5.2 Code Explanation

The above code demonstrates connecting to the Kiwoom Securities API through the AutoTrade class and trading stocks using the buy and sell functions. It also includes a balance-checking feature.

6. Implementing Strategies

The core of an automated trading program is the investment strategy. Let’s implement a simple moving average crossover strategy.

6.1 Implementing the Moving Average Crossover Strategy

import pandas as pd

class MovingAverageStrategy:
    def __init__(self, trader):
        self.trader = trader

    def execute(self, code):
        data = self.get_historical_data(code)
        data['SMA20'] = data['close'].rolling(window=20).mean()
        data['SMA50'] = data['close'].rolling(window=50).mean()

        # Generate trading signals
        if data['SMA20'].iloc[-1] > data['SMA50'].iloc[-1]:
            self.trader.buy(code, 1)
        elif data['SMA20'].iloc[-1] < data['SMA50'].iloc[-1]:
            self.trader.sell(code, 1)

    def get_historical_data(self, code):
        # Collect historical data (example)
        # Implement actual data collection logic
        return pd.DataFrame()  # Placeholder

if __name__ == "__main__":
    trader = AutoTrade()
    strategy = MovingAverageStrategy(trader)
    strategy.execute("005930")  # Samsung Electronics

6.2 Strategy Explanation

The moving average strategy above generates trading signals by comparing the 20-day and 50-day simple moving averages (SMA). A buy signal occurs when the 20-day SMA crosses above the 50-day SMA, and a sell signal occurs when it crosses below.

7. Analyzing Automated Trading Performance

Automated trading systems should continuously analyze and improve performance. The following elements should be included in performance analysis:

7.1 Performance Indicators

  • Total return
  • Maximum drawdown
  • Sharpe ratio

7.2 Recording Results

Record trading results for analysis. Trading results can be saved in formats such as CSV files.

8. Conclusion

In this article, we explored automated trading using Python, how to use the Kiwoom Securities API, and how to sign up for simulated trading. This enables beginners to easily develop automated trading systems and test them in an environment similar to real trading. Continue to research and develop various strategies!

Automated Trading Development in Python, Kiwoom Securities API, Handling Login Events

Handling Login Events with Kiwoom Securities API

Automating stock trading is becoming an increasingly important factor in today’s investment environment. In this course, we will explain in detail how to handle login events during the development process of automated trading software using the Kiwoom Securities API with Python. The Kiwoom Securities API is very popular in the Korean stock market, offering powerful features and is particularly favored by many traders.

Introduction to Kiwoom Securities API

The Kiwoom Securities API is a programming interface provided by Kiwoom Securities that allows users to programmatically execute stock trading. By using the API, various tasks such as buying and selling stocks, checking balances, and collecting market data can be performed. The designed client software can primarily perform the following functions:

  • Buying and selling stocks
  • Real-time market data inquiry
  • Transaction history check
  • Profit and loss analysis

Setting Up the Environment

To use the Kiwoom Securities API, the following environment setup is required.

  1. Open a Kiwoom Securities account and register a certified certificate
  2. Install Kiwoom Securities Open API+ on your PC
  3. Install the necessary libraries

When you install Kiwoom Securities Open API+, dedicated DLL files that allow you to use <OpenAPI> are provided. To communicate with Python, you need to install the pywin32 library. To do this, enter the following command:

pip install pywin32

Handling Login Events

The first step of the Kiwoom Securities API is to log in. The basic procedure for handling login events is as follows:

  1. Initialize the API
  2. Send login request
  3. Check login success

Initializing the API

To use the API, you must first initialize the COM object. Below is a basic code example for initialization:

import win32com.client

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

Sending a Login Request

Login is accomplished by calling the <CommConnect> method. This method opens a login window and processes the login. Below is the code for sending a login request:

# Send login request
kiwoom.CommConnect()  # Create login window

Handling Login Events

After sending the login request, you need to handle the information about the login result. You can check the login result using the <OnEventConnect> event handler. This event is called upon successful login and can be handled as follows:

class MyKiwoom:
    def __init__(self):
        self.kiwoom = win32com.client.Dispatch("KHOpenAPI.KHOpenAPICtrl.1")
        self.kiwoom.OnEventConnect.connect(self.on_event_connect)

    def login(self):
        self.kiwoom.CommConnect()  # Send login request

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

# Example usage
my_kiwoom = MyKiwoom()
my_kiwoom.login()

Actions After Successful Login

After a successful login, you can now make various requests through the API. Below is how to retrieve a list of held stocks after logging in:

def get_stock_list(self):
        count = self.kiwoom.GetAccountList()
        stock_list = []
        for i in range(count):
            stock_code = self.kiwoom.GetAccountStock(i)
            if stock_code:
                stock_list.append(stock_code)
        return stock_list

# Example of retrieving held stocks
print(my_kiwoom.get_stock_list())

Conclusion and Further Advice

In this session, we learned how to handle login events using the Kiwoom Securities API. The possibilities for automating stock trading through various API methods are limitless. It is also advisable to explore how to build automated trading algorithms using real-time data.

Finally, remember that stock trading always carries risks, so be sure to conduct sufficient testing before proceeding with automated trading!

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.