Automatic Trading Development with Python, Kiwoom Securities API, Introduction to PyQt

Recently, automatic trading systems in the stock market have attracted attention among many investors.
In particular, Python has established itself as a suitable language for financial data processing and
automatic trading system development due to its simplicity and powerful libraries. In this article, we will
explore how to develop an automatic trading system using the Kiwoom Securities API and
how to utilize PyQt for building a user interface.

1. Self Diagnosis: Why Use an Automatic Trading System?

An automatic trading system allows trading to be executed automatically based on predefined algorithms,
free from human emotions and momentary judgments. This increases the possibility of maximizing profits
by maintaining consistency in trading and optimizing trading time.

2. Overview of Kiwoom Securities API

The Kiwoom Securities API is a tool provided by Kiwoom Securities that helps to perform trading programmatically.
Through this API, users can access real-time stock data, create orders, and manage trading history.

2.1. Installing Kiwoom API

To use the Kiwoom API, you must first install Kiwoom Securities’ Open API+. After installation, you can set up
the API through the following steps.

1. Download 'Open API+' from the Kiwoom Securities homepage.
2. After installation, run 'OPKorea_1.2.0.exe' in the 'Kiwoom Securities Open API' folder.
3. Enter the API key and password to authenticate.
4. Check if the API is functioning properly.

2.2. Key Features of Kiwoom API

  • Stock Search
  • Real-Time Price Inquiry
  • Order and Trade Execution
  • Transaction History Inquiry
  • Portfolio Management

3. Integrating Python with Kiwoom Securities API

To integrate the Kiwoom Securities API using Python, you can use a GUI framework like PyQt5.
Let’s look at example code using the Kiwoom API and PyQt5.

3.1. Installing PyQt5

pip install PyQt5
pip install PyQt5-tools

3.2. Implementing Login via Kiwoom API

Below is the basic code for logging into the Kiwoom Securities API.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import pyqtSlot
import win32com.client

class Kiwoom(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Kiwoom Securities Automatic Trading System")
        self.setGeometry(300, 300, 400, 300)
        self.login_button = QPushButton("Login", self)
        self.login_button.clicked.connect(self.login)
        self.login_button.resize(100, 40)
        self.login_button.move(150, 130)

        self.kiwoom = win32com.client.Dispatch("KHOpenAPI.KHOpenAPICtrl.1")
    
    @pyqtSlot()
    def login(self):
        self.kiwoom.CommConnect()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    kiwoom = Kiwoom()
    kiwoom.show()
    sys.exit(app.exec_())

4. Real-Time Stock Data Inquiry

Now, after adding the login feature, let’s add the real-time data inquiry functionality.
To access real-time prices, we need to write a function for data requests.

class Kiwoom(QMainWindow):
    # ... Previous code omitted ...
    def retrieve_stock_data(self, stock_code):
        self.kiwoom.SetInputValue("종목코드", stock_code)
        self.kiwoom.CommRqData("Basic Stock Information", "opt10001", 0, "0101")

    def OnReceiveTrData(self, scrno, rqname, trcode, recordname, prevnext, 
                       dataLength, errorCode, message, splm):
        print("Data Received")
        self.current_price = self.kiwoom.GetCommData(trcode, rqname, 0, "Current Price")
        print(f"Current Price: {self.current_price.strip()}")

4.1. Adding Real-Time Data Reception Functionality

We added the `OnReceiveTrData` method to the basic code above.
In this method, we will implement the logic for processing the received data.

5. Implementing Order Functionality

Now, let’s add a simple order functionality.
Let’s look at a code example for handling buy and sell orders.

def buy_stock(self, stock_code, quantity):
    self.kiwoom.SetInputValue("Stock Code", stock_code)
    self.kiwoom.SetInputValue("Order Quantity", quantity)
    self.kiwoom.SetInputValue("Price", 0)  # Market Price
    self.kiwoom.SetInputValue("Order Type", 1)  # Buy
    self.kiwoom.CommRqData("Stock Order", "opt00001", 0, "0101")

def sell_stock(self, stock_code, quantity):
    self.kiwoom.SetInputValue("Stock Code", stock_code)
    self.kiwoom.SetInputValue("Order Quantity", quantity)
    self.kiwoom.SetInputValue("Price", 0)  # Market Price
    self.kiwoom.SetInputValue("Order Type", 2)  # Sell
    self.kiwoom.CommRqData("Stock Order", "opt00001", 0, "0101")

6. Optimizing GUI Design

You can design a more intuitive and user-friendly GUI using PyQt5.
By using various widgets, user experience can be enhanced.

self.quantity_input = QLineEdit(self)
self.quantity_input.move(150, 50)
self.quantity_input.resize(100, 30)

self.stock_code_input = QLineEdit(self)
self.stock_code_input.move(150, 90)
self.stock_code_input.resize(100, 30)

self.buy_button = QPushButton("Buy", self)
self.buy_button.move(150, 130)
self.buy_button.clicked.connect(self.on_buy_click)

6.1. Handling Click Events for the Order Button

def on_buy_click(self):
    stock_code = self.stock_code_input.text()
    quantity = int(self.quantity_input.text())
    self.buy_stock(stock_code, quantity)

7. Developing an Automatic Trading Algorithm

Now, let’s implement the core algorithm of automatic trading.
A simple strategy to consider is the moving average crossover strategy.

def moving_average_strategy(self):
    short_window = 5
    long_window = 20
    prices = self.get_past_prices(stock_code)

    short_ma = prices[-short_window:].mean()
    long_ma = prices[-long_window:].mean()

    if short_ma > long_ma:
        self.buy_stock(stock_code, 1)
    elif short_ma < long_ma:
        self.sell_stock(stock_code, 1)

7.1. Getting Historical Price Data

def get_past_prices(self, stock_code):
    # Implement the method to retrieve historical price data
    pass

8. Termination and Continuous Trading

When managing assets, it is very important to monitor trading history after orders are executed and
take necessary actions. After a trade is completed, the process of updating the portfolio is necessary.

def update_portfolio(self):
    # Implement the method to update portfolio status
    pass

Conclusion

In this article, we explored how to implement a simple automatic trading system using the
Kiwoom Securities API with Python. By adding a user interface through PyQt, we were able to
create a more intuitive and user-friendly system. Next, it is recommended to build upon this
foundation by adding more complex and diverse algorithms to create a personalized automatic trading system.

Automated Trading Development, Kiwoom Securities API, PyQt Basics

Stock trading is becoming increasingly automated, with many traders seeking to use algorithms for more efficient trading. This article will cover the basics of developing an automated trading system using the Kiwoom Securities API with Python and introduce how to create a user interface using PyQt.

1. Introduction to Python and the Concept of Automated Trading

Python is a high-level programming language used in various fields. It is particularly useful in data analysis, machine learning, web development, and more. Automated trading refers to a system that automatically executes trades based on a specified algorithm, saving time and effort for many investors.

2. What is the Kiwoom Securities API?

The Kiwoom Securities API defines the interface between the programs provided by Kiwoom Securities and users. This allows developers to programmatically control stock trading, market information retrieval, order placement, and more. To use the Kiwoom Securities API, one must first open an account with Kiwoom Securities and apply for the Open API service.

2.1. How to Apply for Open API

  1. Access the Kiwoom Securities website and open an account.
  2. Find the Open API application menu and apply.
  3. Once API usage approval is complete, you will receive an API authentication key.

3. Basic Structure of an Automated Trading System

An automated trading system generally consists of the following components:

  • Data Collection: Collecting data such as stock prices and trading volumes.
  • Strategy Development: Establishing trading strategies based on the collected data.
  • Order Execution: Automatically placing orders according to the strategy.
  • Monitoring: Monitoring the system’s status and performance in real time.

4. How to Use the Kiwoom Securities API

Below is an example code to retrieve stock information using the Kiwoom Securities API.


import pythoncom
import win32com.client

# Initialize Kiwoom Securities API object
def init_api():
    pythoncom.CoInitialize()
    return win32com.client.Dispatch("KHOPENAPI.KHOpenAPI")

# Retrieve stock information
def get_stock_info(code):
    api = init_api()
    price = api.GetMasterLastPrice(code)
    name = api.GetMasterCodeName(code)
    return name, price

if __name__ == "__main__":
    stock_code = "005930"  # Samsung Electronics code
    stock_name, stock_price = get_stock_info(stock_code)
    print(f"The current price of {stock_name} is: {stock_price} won")

        

5. UI Development Using PyQt

PyQt is a library that helps build GUIs using the Qt framework in Python. This chapter will explain how to create a basic PyQt application.

5.1. Installing PyQt

PyQt can be easily installed using pip. Use the following command to install it:

pip install PyQt5
        

5.2. Basic PyQt Application

Below is the code for a basic PyQt application.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('Automated Trading System')
        
        layout = QVBoxLayout()
        label = QLabel('Hello! This is an automated trading system.')
        layout.addWidget(label)
        
        self.setLayout(layout)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

        

6. Implementing an Automated Trading System

Based on the above content, let’s implement a real automated trading system. The example will use a simple moving average strategy.

6.1. Moving Average Strategy

The moving average strategy calculates the average price over a certain period based on historical price data, and buys when the current price exceeds the average price, and sells when it is below.

6.2. Example Code


import numpy as np
import pandas as pd

# Fetch historical stock price data (temporary data)
def fetch_historical_data(code):
    # Assume the stock price data is in a pandas DataFrame
    dates = pd.date_range('2023-01-01', periods=100)
    prices = np.random.randint(1000, 2000, size=(100,))
    return pd.DataFrame({'Date': dates, 'Close': prices}).set_index('Date')

# Buy/Sell strategy
def trading_strategy(data, short_window=5, long_window=20):
    signals = pd.DataFrame(index=data.index)
    signals['price'] = data['Close']
    signals['short_mavg'] = data['Close'].rolling(window=short_window, min_periods=1).mean()
    signals['long_mavg'] = data['Close'].rolling(window=long_window, min_periods=1).mean()
    
    signals['signal'] = 0
    signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:] > signals['long_mavg'][short_window:], 1, 0)
    signals['positions'] = signals['signal'].diff()
    
    return signals

if __name__ == "__main__":
    stock_code = "005930"  # Samsung Electronics code
    historical_data = fetch_historical_data(stock_code)
    signals = trading_strategy(historical_data)
    
    print(signals.tail())  # Print signals for the last 5 days

        

7. Conclusion

This article covered the basics of developing an automated trading system using Python, how to use the Kiwoom Securities API, and how to build a user interface using PyQt. Based on this information, try creating your own automated trading system!

Automated Trading Development with Python, Kiwoom Securities API, Open API + Log In

Recently, automated trading has gained popularity among traders in the financial markets. In particular, Python has established itself as a suitable language for developing automated trading systems due to its concise syntax and various libraries. This article will cover the initial setup and login method for automated trading using Kiwoom Securities’ Open API.

1. What is Kiwoom Securities Open API?

Kiwoom Securities Open API is an interface that allows users to programmatically execute trades utilizing various trading functions provided by the user. Developers can access a variety of financial products such as stocks, futures, and options through this API, and can receive trade orders and real-time data.

1.1 Advantages of the API

  • Ease of developing automated trading systems
  • Real-time market data collection
  • Developer community support
  • Compatibility with various programming languages

2. Prerequisites

To use Kiwoom Securities Open API, several prerequisites are necessary. You need a Kiwoom Securities account and an API key.

2.1 Creating a Kiwoom Securities Account

Visit the Kiwoom Securities website to create an account. After creating the account, configure the necessary settings through the API-related menu.

2.2 Issuing an API Key

After logging in, fill out the API application form to get your API key. This is essential for using the API.

2.3 Setting Up the Python Environment

Prepare the Python development environment. Anaconda or Visual Studio Code is recommended. The necessary libraries are as follows:

pip install pyqt5
pip install pandas
pip install numpy

3. Logging into Kiwoom Securities Open API+

Before using the API, you must first log in. The code below demonstrates the process of logging into the API.

3.1 Importing Kiwoom API Module

import win32com.client
import pythoncom

3.2 Defining Login-related Functions

Define a callback function for logging in. This is necessary for event handling with the API.


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

    def login_event_slot(self):
        self.tr.OnEventConnect.connect(self.login_event)

    def login_event(self, err_code):
        if err_code == 0:
            print("Login Successful")
        else:
            print("Login Failed")

3.3 Executing Login

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    kiwoom = Kiwoom()
    kiwoom.tr.CommConnect()
    app.exec_()

Running the above code will display the Kiwoom Securities login window. After logging in, if the connection is successful, the message “Login Successful” will be printed.

4. Obtaining Stock Codes

After logging in, add the following code to obtain the code for the desired stock.


def get_code_list(self):
    code_list = self.tr.GetCodeListByMarket(0)  # 0: KOSPI
    return code_list.split(';')

This function retrieves the codes of stocks listed on the KOSPI.

4.1 Printing Stock Codes

if __name__ == "__main__":
    # Existing code ...
    code_list = kiwoom.get_code_list()
    print("KOSPI Stock Code List:", code_list)

5. Placing Stock Orders

Next, we will write code to allow placing orders. Below is an example of placing a buy order.


def buy_stock(self, code, quantity):
    self.tr.SendOrder("Order Name", "130", "Stock Code", quantity, 0, "00", "0", "0", "")

The above function shows an example of buying stocks at market price.

5.1 Executing Buy Orders

if __name__ == "__main__":
    # Existing code ...
    kiwoom.buy_stock("005930", 1)  # Buy 1 share of Samsung Electronics

6. Placing Sell Orders

Sell orders are processed similarly.


def sell_stock(self, code, quantity):
    self.tr.SendOrder("Sell Order", "130", "Stock Code", -quantity, 0, "00", "0", "0", "")

When placing an order, the quantity value is entered as a negative number to execute a sell.

6.1 Executing Sell Orders

if __name__ == "__main__":
    # Existing code ...
    kiwoom.sell_stock("005930", 1)  # Sell 1 share of Samsung Electronics

7. Receiving Real-time Data

One of the important aspects of trading is receiving real-time data. Below explains how to receive real-time data.


def setup_signal(self):
    self.tr.OnReceiveRealData.connect(self.receive_real_data)

def receive_real_data(self, code, real_type, real_data):
    print(f"Stock: {code}, Real-time Data: {real_type}, Data: {real_data}")

This function allows you to process real-time data.

7.1 Executing Real-time Data Reception

if __name__ == "__main__":
    # Existing code ...
    kiwoom.setup_signal()
    kiwoom.tr.SetRealReg("0001", "005930", "20", "0")  # Register real-time data for Samsung Electronics

8. Conclusion

In this article, we explored the initial setup and login method for automated trading using Kiwoom Securities Open API with Python. There are many more functionalities, so I encourage you to add the features you need and build your own automated trading system. Through continuous learning and experimentation, you can develop your own trading strategies.

Helpful Resources

Developing Python Automated Trading, Using Kiwoom Securities API, KOA Studio

Auto trading is a system that automatically executes trades in the financial market using algorithms. Python is preferred by many traders and developers because it is easy to process data and implement algorithms. This article will explain in detail how to develop an auto trading system using Kiwoom Securities’ API and KOA Studio with Python.

1. Introduction to Kiwoom Securities API

The Kiwoom Securities API is provided by Kiwoom Securities, allowing traders to implement their algorithms and collect market data in real-time. The Kiwoom Securities API offers the following features:

  • Real-time price inquiry
  • Order transmission and management
  • Account information inquiry
  • Transaction history inquiry

2. Introduction to KOA Studio

KOA Studio is an integrated development environment that allows the development of auto trading systems using Kiwoom Securities’ API. It provides a variety of features to help developers develop easily. The main features of KOA Studio are:

  • Visual user interface
  • Data visualization features
  • Contextual help provided
  • Code templates provided

3. Environment Setup

To develop an auto trading system, the environment must be set up in the following order:

3.1. Open a Kiwoom Securities Account

First, you need to open an account with Kiwoom Securities. Without a brokerage account, you cannot use the API, so please open an account on the official website.

3.2. Apply for API Access Approval

To use the API, you need to apply for API access approval from Kiwoom Securities. Once approved, you will receive an API key, which is required for authentication in the code.

3.3. Install KOA Studio

Download and install KOA Studio. Once the installation is complete, run the program to perform the initial setup.

4. Basic Code Structure

The basic code structure for an auto trading system is as follows:

import win32com.client
import time

class AutoTrader:
    def __init__(self):
        self.app = win32com.client.Dispatch('KHOPENAPI.KHOpenAPICtrl.1')
        self.app.CommConnect()
        time.sleep(1)

    def get_stock_price(self, code):
        price = self.app.CommGetData("OPTKWM", "조회", 0, 0, code)
        return price

    def buy_stock(self, code, quantity):
        order_result = self.app.SendOrder("Order01", "123456", code, quantity, 0, 0, 0, "")
        return order_result

    def sell_stock(self, code, quantity):
        order_result = self.app.SendOrder("Order01", "123456", code, -quantity, 0, 0, 0, "")
        return order_result

The above code provides basic functionality to retrieve the current price of stocks and to buy and sell stocks using the Kiwoom Securities API.

5. Data Collection and Analysis

To devise an auto trading strategy, it is necessary to collect and analyze market data. You can solidify your strategy by utilizing prices, trading volumes, and technical indicators.

5.1. Requesting Real-time Prices

The method for requesting real-time prices to utilize in trading strategies is as follows:

def request_realtime_quotes(self, code):
    self.app.SetInputValue("StockCode", code)
    self.app.CommRQData("RealTimeInquiry", "OPTKWM", 0, "0101")

The method above is necessary for querying real-time prices of a specific stock.

5.2. Calculating Technical Indicators

You can calculate technical indicators based on the collected data. For example, here is how to calculate the moving average (MA):

def calculate_moving_average(prices, period):
    return sum(prices[-period:]) / period

6. Implementing Auto Trading Strategy

Now let’s implement an auto trading strategy based on the collected data and analysis results. One example would be a simple moving average crossover strategy.

def trading_strategy(self):
    short_ma = calculate_moving_average(self.prices, short_period)
    long_ma = calculate_moving_average(self.prices, long_period)

    if short_ma > long_ma:
        self.buy_stock(self.current_stock_code, 1)
    elif short_ma < long_ma:
        self.sell_stock(self.current_stock_code, 1)

7. Backtesting

To validate the effectiveness of the strategy, backtesting based on historical data should be conducted. The pandas library is useful for data analysis. Here’s an example of backtesting:

import pandas as pd

def backtest_strategy(data, strategy):
    results = []
    for index, row in data.iterrows():
        result = strategy(row)
        results.append(result)
    return results

8. Conclusion

In this article, we explored the development of an auto trading system using Python. By utilizing the Kiwoom Securities API and KOA Studio, try to implement your own auto trading strategy. Through Python's powerful data processing capabilities and the Kiwoom Securities API, we hope you discover more opportunities and achieve successful trading.

9. Additional Resources

Additional materials and links for auto trading are as follows:

If you found this article helpful, please share it!

Automated Trading Development, Kiwoom Securities API, Hello PyQt

Hello, blog readers! Today, we will take a closer look at how to develop an automated trading system using the Kiwoom Securities API with Python, as well as Hello PyQt for GUI development. Stock automated trading is an appealing topic for many investors, and it can help us make better investment decisions.

Table of Contents

1. Overview of the Automated Trading System

An automated trading system is a system that automatically performs trades based on specific conditions. This allows traders to eliminate emotions and consistently execute predetermined strategies.

1.1 Advantages of Automated Trading

  • Emotion Elimination: Trading decisions are not influenced by emotions
  • Rapid Transactions: Ability to respond immediately to market changes
  • Continuous Monitoring: Ability to monitor the market 24/7
  • Investment Strategy Consistency: Trades are executed consistently based on set strategies

1.2 Components of an Automated Trading System

  • Data Collection Module: Collects data such as prices and trading volumes
  • Signal Generation Module: Algorithm that generates trading signals
  • Execution Module: Executes actual trades based on the signals
  • Monitoring and Reporting: Monitors trading results and provides reporting functions

2. Introduction to the Kiwoom Securities API

The Kiwoom Securities API is a program interface provided by Kiwoom Securities that supports users in automating online stock trading. Through this API, users can programmatically perform real-time queries of stock data and execute trading orders.

2.1 Features of the Kiwoom Securities API

  • Real-time Data: Ability to check real-time stock prices and orders
  • Order and Execution: Ability to verify trading orders and execution history
  • Error Handling: Provides various error handling features related to trading

2.2 Procedure for Using the Kiwoom Securities API

  1. Open a Kiwoom Securities account and apply for the API
  2. Set up the API integration environment
  3. Install and integrate Python libraries

3. Setting Up the Python Environment

To develop an automated trading program, you first need to set up the Python environment. Below are the required packages and installation methods.

3.1 Install Required Packages

pip install pyqt5
pip install kiwoom

3.2 Write API Integration Code

Now, let’s write the code to integrate the Kiwoom Securities API with Python.

from PyQt5.QtWidgets import QApplication
from Kiwoom import Kiwoom

app = QApplication([])
kiwoom = Kiwoom()
kiwoom.CommConnect()  # Login connection

4. Implementing Basic Automated Trading Logic

Now, let’s implement basic automated trading logic. This example will be based on a simple moving average crossover strategy.

4.1 Explanation of Moving Average Crossover Strategy

The moving average crossover strategy involves buying when the short-term moving average crosses above the long-term moving average and selling when it crosses below.

4.2 Implementation Example

import pandas as pd

def moving_average(data, window):
    return data.rolling(window=window).mean()

def trade_logic(df):
    df['SMA10'] = moving_average(df['Close'], 10)
    df['SMA50'] = moving_average(df['Close'], 50)

    if df['SMA10'].iloc[-1] > df['SMA50'].iloc[-1]:
        print("Buy signal generated")
        # Write order code here
    else:
        print("Sell signal generated")
        # Write order code here

# Example of data collection
# df = kiwoom.GetStockData("005930")  # Samsung Electronics
# trade_logic(df)

5. GUI Development Using PyQt

Now, let’s develop a GUI to add a user interface. PyQt is a library that makes it easy to develop GUIs in Python.

5.1 Basic Example of PyQt

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Automated Trading System")
        self.setGeometry(100, 100, 300, 200)

        layout = QVBoxLayout()
        self.start_button = QPushButton("Start Automated Trading")
        self.start_button.clicked.connect(self.start_trading)
        
        layout.addWidget(self.start_button)
        self.setLayout(layout)

    def start_trading(self):
        print("Starting automated trading...")

app = QApplication([])
window = MyWindow()
window.show()
app.exec_()

5.2 Integrating GUI and Automated Trading Logic

We will write integration code to ensure the automated trading system operates when the button is clicked in the GUI.

def start_trading(self):
    df = kiwoom.GetStockData("005930")  # Samsung Electronics
    trade_logic(df)

6. Real-World Applications and Conclusion

Now let’s look at a real-world application of the automated trading system. You can select the most suitable strategy among various strategies and proceed with actual investments. It is important to always adapt your strategy flexibly to market changes.

6.1 Conclusion

In this tutorial, we learned about developing an automated trading system using Python, the Kiwoom Securities API, and GUI development using PyQt. Based on this knowledge, we hope you can build a more sophisticated automated trading system. Wishing you successful investment outcomes!