{"id":37427,"date":"2024-11-01T09:57:30","date_gmt":"2024-11-01T09:57:30","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=37427"},"modified":"2024-11-01T11:50:52","modified_gmt":"2024-11-01T11:50:52","slug":"python-automated-trading-development-kiwoom-securities-api-event-handling","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/37427\/","title":{"rendered":"Python Automated Trading Development, Kiwoom Securities API, Event Handling"},"content":{"rendered":"<p>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.<\/p>\n<h2>1. Preparing the Kiwoom Securities API<\/h2>\n<p>To implement automated trading using the Kiwoom Securities API, you first need to obtain an API key. The subsequent steps are as follows:<\/p>\n<ul>\n<li>Log in to the Kiwoom Securities homepage and register as an API user.<\/li>\n<li>Obtain an API key and install the necessary libraries.<\/li>\n<\/ul>\n<h3>1.1 Library Installation<\/h3>\n<p>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.<\/p>\n<pre><code>pip install PyQt5<\/code><\/pre>\n<p>Next, download and install the Kiwoom Securities Open API. The API can be found on the Kiwoom Securities homepage.<\/p>\n<h2>2. Logging into the Kiwoom Securities API<\/h2>\n<p>You first need to log in to Kiwoom Securities through the API. The following code is an example of handling user login.<\/p>\n<pre><code>import win32com.client\nimport pythoncom\nimport time\n\nclass Kiwoom:\n    def __init__(self):\n        self.api = win32com.client.Dispatch(\"KHOPENAPI.KHOpenAPICtrl.1\")\n        self.login()\n\n    def login(self):\n        self.api.CommConnect()\n        while self.api.GetConnectState() == 0:\n            time.sleep(1)\n\nkiwoom = Kiwoom()<\/code><\/pre>\n<p>The above code logs into Kiwoom Securities and checks the connection state. After logging in, you can retrieve the desired information.<\/p>\n<h2>3. Event Handling<\/h2>\n<p>Event handling is the core of the automated trading system. It allows you to perform appropriate actions when specific events occur.<\/p>\n<h3>3.1 Order Events<\/h3>\n<p>To send orders or check statuses, you need to specify event handlers. Below is the code for handling order events.<\/p>\n<pre><code>class Kiwoom:\n    def __init__(self):\n        self.api = win32com.client.Dispatch(\"KHOPENAPI.KHOpenAPICtrl.1\")\n        self.api.OnEventConnect.connect(self.on_event_connect)\n\n    def on_event_connect(self, err_code):\n        if err_code == 0:\n            print(\"Login successful\")\n        else:\n            print(\"Login failed\")\n\n    def send_order(self, order_type, code, qty, price, price_type):\n        order = self.api.SendOrder(\"Order Name\", \"5000\", self.api.GetAccList()[0], order_type, code, qty, price, price_type, \"\")\n        return order<\/code><\/pre>\n<p>The above function is responsible for sending orders, and you can check the success of the order via the return value.<\/p>\n<h3>3.2 Real-time Balance Events<\/h3>\n<p>If you want to monitor the balance in real-time, you can implement it as follows.<\/p>\n<pre><code>class Kiwoom:\n    def __init__(self):\n        self.api = win32com.client.Dispatch(\"KHOPENAPI.KHOpenAPICtrl.1\")\n        self.api.OnReceiveRealData.connect(self.on_receive_real_data)\n\n    def on_receive_real_data(self, code, data):\n        print(f\"Balance information received: {code}, {data}\")<\/code><\/pre>\n<p>This code is called every time data comes in real-time.<\/p>\n<h2>4. Designing Automated Trading Strategies<\/h2>\n<p>Designing a strategy for automated trading is necessary. For example, let&#8217;s look at a strategy based on moving averages. Moving averages can help determine the timing for buying or selling stocks.<\/p>\n<pre><code>class MovingAverageStrategy:\n    def __init__(self):\n        self.short_window = 5\n        self.long_window = 20\n        self.data = []\n\n    def compute_moving_average(self):\n        if len(self.data) &lt; self.long_window:\n            return None\n        short_ma = sum(self.data[-self.short_window:]) \/ self.short_window\n        long_ma = sum(self.data[-self.long_window:]) \/ self.long_window\n        return short_ma, long_ma<\/code><\/pre>\n<p>This strategy generates trading signals by comparing the short-term moving average and the long-term moving average.<\/p>\n<h2>5. Executing Orders<\/h2>\n<p>Now that we have implemented the automated trading system through events, the final step is to write the code that actually executes orders.<\/p>\n<pre><code>def execute_trade(self):\n    short_ma, long_ma = self.compute_moving_average()\n    if short_ma is not None and short_ma &gt; long_ma:\n        print(\"Buying point\")\n        self.send_order(1, \"005930\", 10, 0, 0)  # Example of buying Samsung Electronics\n    elif short_ma is not None and short_ma &lt; long_ma:\n        print(\"Selling point\")\n        self.send_order(2, \"005930\", 10, 0, 0)  # Example of selling Samsung Electronics<\/code><\/pre>\n<p>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.<\/p>\n<h2>6. Complete Automated Trading System<\/h2>\n<p>By integrating all the above elements, you can implement the complete automated trading system. The final code combining all classes is as follows.<\/p>\n<pre><code>class AutoTradingSystem:\n    def __init__(self):\n        self.kiwoom = Kiwoom()\n        self.strategy = MovingAverageStrategy()\n\n    def run(self):\n        while True:\n            self.kiwoom.api.BlockRequest(\"opw00018\", ...) # Request balance information\n            self.strategy.data.append(self.get_market_data())  # Collect market data\n            self.strategy.execute_trade()  # Execute trading\n            time.sleep(60)  # Execute periodically<\/code><\/pre>\n<p>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.<\/p>\n<h2>Conclusion<\/h2>\n<p>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.<\/p>\n<h2>References<\/h2>\n<ul>\n<li><a href=\"https:\/\/www.kiwoom.com\">Kiwoom Securities Official Homepage<\/a><\/li>\n<li><a href=\"https:\/\/python.org\">Official Python Homepage<\/a><\/li>\n<li><a href=\"https:\/\/github.com\">Github<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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 &hellip; <a href=\"https:\/\/atmokpo.com\/w\/37427\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Python Automated Trading Development, Kiwoom Securities API, Event Handling&#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-37427","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>Python Automated Trading Development, Kiwoom Securities API, Event Handling - \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\/37427\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Automated Trading Development, Kiwoom Securities API, Event Handling - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"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 &hellip; \ub354 \ubcf4\uae30 &quot;Python Automated Trading Development, Kiwoom Securities API, Event Handling&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/37427\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:57:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:50:52+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\/37427\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/37427\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Python Automated Trading Development, Kiwoom Securities API, Event Handling\",\"datePublished\":\"2024-11-01T09:57:30+00:00\",\"dateModified\":\"2024-11-01T11:50:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/37427\/\"},\"wordCount\":536,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Python Auto Trading\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/37427\/\",\"url\":\"https:\/\/atmokpo.com\/w\/37427\/\",\"name\":\"Python Automated Trading Development, Kiwoom Securities API, Event Handling - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:57:30+00:00\",\"dateModified\":\"2024-11-01T11:50:52+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/37427\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/37427\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/37427\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Automated Trading Development, Kiwoom Securities API, Event Handling\"}]},{\"@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":"Python Automated Trading Development, Kiwoom Securities API, Event Handling - \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\/37427\/","og_locale":"ko_KR","og_type":"article","og_title":"Python Automated Trading Development, Kiwoom Securities API, Event Handling - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"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 &hellip; \ub354 \ubcf4\uae30 \"Python Automated Trading Development, Kiwoom Securities API, Event Handling\"","og_url":"https:\/\/atmokpo.com\/w\/37427\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:57:30+00:00","article_modified_time":"2024-11-01T11:50:52+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\/37427\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/37427\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Python Automated Trading Development, Kiwoom Securities API, Event Handling","datePublished":"2024-11-01T09:57:30+00:00","dateModified":"2024-11-01T11:50:52+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/37427\/"},"wordCount":536,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Python Auto Trading"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/37427\/","url":"https:\/\/atmokpo.com\/w\/37427\/","name":"Python Automated Trading Development, Kiwoom Securities API, Event Handling - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:57:30+00:00","dateModified":"2024-11-01T11:50:52+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/37427\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/37427\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/37427\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Python Automated Trading Development, Kiwoom Securities API, Event Handling"}]},{"@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\/37427","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=37427"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/37427\/revisions"}],"predecessor-version":[{"id":37428,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/37427\/revisions\/37428"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=37427"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=37427"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=37427"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}