{"id":37419,"date":"2024-11-01T09:57:25","date_gmt":"2024-11-01T09:57:25","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=37419"},"modified":"2024-11-01T11:50:54","modified_gmt":"2024-11-01T11:50:54","slug":"automated-trading-development-in-python-kiwoom-securities-api-learning-the-basics-of-api","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/37419\/","title":{"rendered":"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API"},"content":{"rendered":"<p><body><\/p>\n<article>\n<p>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.<\/p>\n<h2>1. What is automated trading?<\/h2>\n<p>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.<\/p>\n<h2>2. Introduction to Kiwoom Securities API<\/h2>\n<p>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.<\/p>\n<h3>2.1 Installing and setting up the API<\/h3>\n<p>To use the API, you must first install Kiwoom Securities&#8217; Open API+. Follow the steps below to proceed with the installation.<\/p>\n<ol>\n<li>Visit the Kiwoom Securities website and download the Open API+.<\/li>\n<li>Configure the necessary environment settings during the installation process.<\/li>\n<li>After the installation is complete, you will be ready to use the API by logging into Kiwoom Securities.<\/li>\n<\/ol>\n<h3>2.2 Basic environment setup after installation<\/h3>\n<p>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:<\/p>\n<pre><code>pip install PyQt5 pythoncom<\/code><\/pre>\n<h2>3. Using the Kiwoom Securities API<\/h2>\n<p>Now, let&#8217;s start using the Kiwoom Securities API to fetch data and place orders.<\/p>\n<h3>3.1 Implementing the API class<\/h3>\n<p>Let\u2019s implement a class to utilize the Kiwoom Securities API. It will include the basic functions for logging in and fetching price data.<\/p>\n<pre><code>import sys\nimport time\nimport pythoncom\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QAxContainer import QAxWidget\n\nclass KiwoomAPI:\n    def __init__(self):\n        self.app = QApplication(sys.argv)\n        self.api = QAxWidget(\"KHOPENAPI.KHOpenAPICtrl.1\")\n        self.api.OnEventConnect.connect(self.connected)\n        self.login()\n\n    def connected(self, errCode):\n        if errCode == 0:\n            print(\"Login successful\")\n        else:\n            print(\"Login failed\", errCode)\n\n    def login(self):\n        self.api.dynamicCall(\"CommConnect()\")\n        self.app.exec_()\n\n    def get_price(self, code):\n        self.api.dynamicCall(\"SetInputValue(QString, QString)\", \"Stock Code\", code)\n        self.api.dynamicCall(\"CommRqData(QString, QString, int, QString)\", \"Basic Stock Information\", \"opt10001\", 0, \"0101\")\n        time.sleep(1)  # Wait for data reception\n        return self.api.dynamicCall(\"GetCommData(QString, QString, int, QString)\", \"Basic Stock Information\", \"opt10001\", 0, \"Current Price\")\n\napi = KiwoomAPI()\nprice = api.get_price(\"005930\")  # Samsung Electronics\nprint(\"Samsung Electronics Current Price:\", price)\n<\/code><\/pre>\n<p>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.<\/p>\n<h3>3.2 Placing stock orders<\/h3>\n<p>Next, let&#8217;s learn how to place stock orders. We will add the following code to implement a buy order function.<\/p>\n<pre><code>class KiwoomAPI:\n    # ... Previous code omitted ...\n\n    def buy_stock(self, code, qty):\n        self.api.dynamicCall(\"SetInputValue(QString, QString)\", \"Stock Code\", code)\n        self.api.dynamicCall(\"SetInputValue(QString, QString)\", \"Order Quantity\", qty)\n        self.api.dynamicCall(\"SetInputValue(QString, QString)\", \"Price\", self.get_price(code))\n        self.api.dynamicCall(\"SetInputValue(QString, QString)\", \"Transaction Type\", \"1\") # 1: Buy, 2: Sell\n        self.api.dynamicCall(\"CommRqData(QString, QString, int, QString)\", \"Stock Order\", \"opt10003\", 0, \"0101\")\n        time.sleep(1)\n        print(\"Order completed\")\n\n# Example usage\napi.buy_stock(\"005930\", 1)  # Buy 1 share of Samsung Electronics\n<\/code><\/pre>\n<h2>4. Building an automated trading system<\/h2>\n<p>Now, based on our understanding of the basic API usage, let&#8217;s write a simple automated trading strategy. For example, it can be implemented to automatically buy when certain conditions are met.<\/p>\n<h3>4.1 Simple Moving Average Strategy<\/h3>\n<p>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.<\/p>\n<pre><code>import pandas as pd\n\ndef get_historical_data(code, count):\n    # Request historical data\n    # This part needs to fetch data through another call provided by the Kiwoom API.\n    return pd.DataFrame()  # Return in DataFrame format\n\ndef trading_strategy():\n    historical_data = get_historical_data(\"005930\", 100)\n    historical_data['MA5'] = historical_data['Close'].rolling(window=5).mean()\n    historical_data['MA20'] = historical_data['Close'].rolling(window=20).mean()\n\n    if historical_data['MA5'].iloc[-2] < historical_data['MA20'].iloc[-2] and historical_data['MA5'].iloc[-1] > historical_data['MA20'].iloc[-1]:\n        print(\"Buy signal generated\")\n        api.buy_stock(\"005930\", 1)\n    elif historical_data['MA5'].iloc[-2] > historical_data['MA20'].iloc[-2] and historical_data['MA5'].iloc[-1] < historical_data['MA20'].iloc[-1]:\n        print(\"Sell signal generated\")\n        # api.sell_stock(\"005930\", 1)  # Sell logic can be added later\n\ntrading_strategy()\n<\/code><\/pre>\n<h2>5. Precautions and Conclusion<\/h2>\n<p>There are many things to be cautious about when implementing automated trading. Please keep the following points in mind.<\/p>\n<ul>\n<li>Before investing real money, validate the strategy\u2019s effectiveness with sufficient backtesting.<\/li>\n<li>Be careful not to exceed the API call limits, and implement exception handling if necessary.<\/li>\n<li>Consider market volatility and prepare risk management measures.<\/li>\n<\/ul>\n<p>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.<\/p>\n<\/article>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &hellip; <a href=\"https:\/\/atmokpo.com\/w\/37419\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[147],"tags":[],"class_list":["post-37419","post","type-post","status-publish","format-standard","hentry","category-python-auto-trading"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/37419\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"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 &hellip; \ub354 \ubcf4\uae30 &quot;Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/37419\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:57:25+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:50:54+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/37419\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/37419\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API\",\"datePublished\":\"2024-11-01T09:57:25+00:00\",\"dateModified\":\"2024-11-01T11:50:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/37419\/\"},\"wordCount\":545,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Python Auto Trading\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/37419\/\",\"url\":\"https:\/\/atmokpo.com\/w\/37419\/\",\"name\":\"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:57:25+00:00\",\"dateModified\":\"2024-11-01T11:50:54+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/37419\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/37419\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/37419\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/37419\/","og_locale":"ko_KR","og_type":"article","og_title":"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"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 &hellip; \ub354 \ubcf4\uae30 \"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API\"","og_url":"https:\/\/atmokpo.com\/w\/37419\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:57:25+00:00","article_modified_time":"2024-11-01T11:50:54+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/37419\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/37419\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API","datePublished":"2024-11-01T09:57:25+00:00","dateModified":"2024-11-01T11:50:54+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/37419\/"},"wordCount":545,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Python Auto Trading"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/37419\/","url":"https:\/\/atmokpo.com\/w\/37419\/","name":"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:57:25+00:00","dateModified":"2024-11-01T11:50:54+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/37419\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/37419\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/37419\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Automated Trading Development in Python, Kiwoom Securities API, Learning the Basics of API"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/37419","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=37419"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/37419\/revisions"}],"predecessor-version":[{"id":37420,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/37419\/revisions\/37420"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=37419"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=37419"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=37419"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}