{"id":1214,"date":"2024-11-08T13:30:00","date_gmt":"2024-11-08T13:30:00","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/masterlink-securities-api\/"},"modified":"2024-11-08T13:30:00","modified_gmt":"2024-11-08T13:30:00","slug":"masterlink-securities-api","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/masterlink-securities-api\/","title":{"rendered":"MasterLink Securities API Beginner&#8217;s Guide\uff1a How to Use TQuant Lab Strategies for Automated Trading"},"content":{"rendered":"<figure class=\"wp-block-image caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"MasterLink Securities API\" class=\"wp-image-30539\" height=\"1066\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/image-48.jpeg\" width=\"1600\"\/><figcaption class=\"wp-element-caption\">Photo by<a href=\"https:\/\/unsplash.com\/@walkator\" rel=\"noopener\" target=\"_blank\"> Walkator<\/a> on<a href=\"https:\/\/unsplash.com\/\" rel=\"noopener\" target=\"_blank\"> Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Preface<\/h2>\n<p class=\"wp-block-paragraph\">In modern financial markets, algorithmic trading is increasingly becoming essential for investors to enhance efficiency and reduce risk. More and more brokerage firms offer API services, enabling investors to automate order placement and quickly respond to market changes. This article will demonstrate using  MasterLink Securities API for automated trading while integrating strategies from TQuant Lab. Through a practical example, we\u2019ll show how a systematic approach can optimize investment decisions, helping investors seize market opportunities and improve performance.<\/p>\n<h2 class=\"wp-block-heading\">Strategy Example<\/h2>\n<p class=\"wp-block-paragraph\">This guide uses Warren Buffett\u2019s corporate investment principles as an example. Refer to <strong>TQuant Lab\u2019s Warren Buffett Corporate Investment Rules<\/strong> for a detailed introduction.<\/p>\n<h3 class=\"wp-block-heading\"><strong>Example Summary<\/strong><\/h3>\n<p class=\"wp-block-paragraph\">The quantitative indicators used in this strategy include:<\/p>\n<ol class=\"wp-block-list\">\n<li>Recent Annual Return on Equity (ROE) &gt; Industry Average<\/li>\n<li>3-Year Average ROE &gt; 15%<\/li>\n<li>Recent Annual Gross Profit Margin &gt; Industry Average<\/li>\n<li>7-Year Market Value Growth \/ 7-Year Retained Earnings Growth &gt; 1<\/li>\n<li>(Recent Annual Free Cash Flow \/ Free Cash Flow from 7 Years Ago) \u2013 1 &gt; 1<\/li>\n<\/ol>\n<p class=\"wp-block-paragraph\">Since ROE can be boosted by increased debt, industries with high leverage, such as the financial sector, are excluded. Additionally, Buffett expects companies to generate more than one unit of market value for every unit of retained earnings. This involves filtering companies listed for over 7 years, as a more extended listing history is necessary for this evaluation.<\/p>\n<h2 class=\"wp-block-heading\">Fetch the required financial data using the TejToolAPI<\/h2>\n<p class=\"wp-block-paragraph\">According to the stock selection criteria in the corporate investment rules, we require the following 7 financial items:<\/p>\n<ul class=\"wp-block-list\">\n<li>Primary Industry (Chinese)<\/li>\n<li>Consistent ROE<\/li>\n<li>Operating Gross Margin<\/li>\n<li>Individual Stock Market Value (in NT$)<\/li>\n<li>Retained Earnings<\/li>\n<li>Cash Flow from Operations<\/li>\n<li>Cash Flow from Investments<\/li>\n<\/ul>\n<p class=\"wp-block-paragraph\">The cash flow from operations and the cash flow from investments can be used to calculate the free cash flow.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Free Cash Flow = Cash Flow from Operations + (-) Cash Flow from Investments<\/strong><\/p>\n<p class=\"wp-block-paragraph\">Note that the cash flow from investments is often a negative number.<\/p>\n<p class=\"wp-block-paragraph\">p.s.<\/p>\n<p class=\"wp-block-paragraph\">Detailed instructions for using the <strong>TejToolAPI<\/strong> can be found on the <strong>TQuant Lab GitHub<\/strong>: <a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Data%20Preprocess%20-%20tejtoolapi.ipynb\" rel=\"noopener\" target=\"_blank\">TejToolAPI Documentation<\/a>.<\/p>\n<p class=\"wp-block-paragraph\">The datasets provided by the <strong>TejToolAPI<\/strong> can be referenced on the <strong>TQuant Lab official website<\/strong>: <a href=\"https:\/\/tquant.tejwin.com\/%e8%b3%87%e6%96%99%e9%9b%86\/\" rel=\"noopener\" target=\"_blank\">TQuant Lab Datasets<\/a>.<\/p>\n<h2 class=\"wp-block-heading\">Extract targets that meet the 5 stock selection criteria.<\/h2>\n<p class=\"wp-block-paragraph\">We select stocks meeting the criteria as of <strong>2015-12-31<\/strong>. For each condition, a separate set is created, and the final step involves taking the intersection of these sets to identify the targets that satisfy all the conditions.<\/p>\n<p class=\"wp-block-paragraph\">By taking the intersection of stocks meeting the 5 stock selection criteria, we can determine our targets. It is evident that the majority of these stocks belong to the <strong>Electronic Components<\/strong> and <strong>Semiconductor<\/strong> industries.<\/p>\n<figure class=\"wp-block-image aligncenter size-full caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"MasterLink Securities API\" class=\"wp-image-29704\" height=\"612\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/image-562.png\" width=\"313\"\/><figcaption class=\"wp-element-caption\">Targets that meet the 5 stock selection criteria.<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\">This gives us the stock pool selected using this strategy. Next, we proceed to the formal order placement stage.<\/p>\n<h2 class=\"wp-block-heading\">Environment Setup and Package Installation<\/h2>\n<p class=\"wp-block-paragraph\">The verification process includes the following steps:<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 1:<\/strong><br \/>Download the API component and use your program to log in to the MasterLink Securities API. Log in to the test environment.<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 2:<\/strong><br \/>Place, modify, and cancel ROD orders (verify the order details on the Digital API website and execute the order through your program).<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 3:<\/strong><br \/>Place IOC orders (verify the order details on the Digital API website and execute the order through your program).<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 4:<\/strong><br \/>Place FOK orders (verify the order details on the Digital API website and execute the order through your program).<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 5:<\/strong><br \/>After placing the order, enter the order number on the Digital API website verification page.<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 6:<\/strong><br \/>For Steps 3, 4, and 5, after entering the order number, click \u201cVerify\u201d on the Digital API website verification page.<\/p>\n<p class=\"wp-block-paragraph\"><strong>STEP 7:<\/strong><br \/>Once the verification is successful, the process is complete. Please wait for the manual review to finalize the approval process before gaining access.<\/p>\n<p class=\"wp-block-paragraph\">First, you must install <strong>MasterTradePy<\/strong>, which can help you implement automated trading strategies.<\/p>\n<p class=\"wp-block-paragraph\">Use the cd command in the terminal to navigate to the <strong>MasterTradePy<\/strong> folder.<\/p>\n<pre class=\"wp-block-code\"><code>cd MasterTradePy\u00a0\npip install MasterTradePy-0.0.15-py3-none-win_amd64.whl<\/code><\/pre>\n<h2 class=\"wp-block-heading\">Importing Packages<\/h2>\n<p class=\"wp-block-paragraph\">Return to your code editor and load the required packages for the API.<\/p>\n<pre class=\"wp-block-code\"><code>import threading\n\nfrom MasterTradePy.api import MasterTradeAPI\n\nfrom MasterTradePy.model import *\n\nfrom MasterTradePy.constant import PriceType, OrderType, TradingSession, Side, TradingUnit, RCode<\/code><\/pre>\n<h2 class=\"wp-block-heading\">Initialization Settings<\/h2>\n<p class=\"wp-block-paragraph\">Set up your account credentials (account and password) and specify the target stock codes.<\/p>\n<p class=\"wp-block-paragraph\">Here, we create a list of stock codes selected based on the <strong>Buffett Strategy<\/strong>, representing the stock pool.<\/p>\n<pre class=\"wp-block-code\"><code>username = 'your_username'\n\npassword = 'your_password'\n\nstock_id_list = [\n\n\u00a0\u00a0\u00a0\u00a01476, 1477, 2467, 3006, 3014, 3034,\u00a0\n\n\u00a0\u00a0\u00a0\u00a03042, 3413, 3533, 3557, 5234, 5269,\u00a0\n\n\u00a0\u00a0\u00a0\u00a06202, 8016, 8046, 8081, 9906\n\n]<\/code><\/pre>\n<p class=\"wp-block-paragraph\"><strong><code>event = threading.Event()<\/code> Explanation<\/strong><\/p>\n<p class=\"wp-block-paragraph\"><code><strong>event = threading.Event()<\/strong><\/code> manages synchronization between multiple threads. This is particularly important when using the API for trading, as it ensures that certain events (e.g., successful connection) occur before other program parts proceed.<\/p>\n<pre class=\"wp-block-code\"><code><strong>event = threading.Event()<\/strong><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Execute Orders<\/h2>\n<p class=\"wp-block-paragraph\">We will place market orders to buy all the stocks in the stock pool.<\/p>\n<pre class=\"wp-block-code\"><code>def execute_order(api, stock_id_list):\n\n    account = 'your_account'\n\n    price = ''  # Leave blank for market order\n\n    qtr = '1000'  # For 1 lot, enter 1000\n\n    orderType = OrderType.ROD\n\n    if not price:\n        priceType = PriceType.MKT\n    else:\n        priceType = PriceType.LMT\n\n    for stock_id in stock_id_list:\n        symbol = stock_id\n\n        order = Order(tradingSession=TradingSession.NORMAL,\n                      side=Side.Buy,\n                      symbol=symbol,\n                      priceType=priceType,\n                      price=price,\n                      tradingUnit=TradingUnit.COMMON, \n                      qty=qty,\n                      orderType=orderType,\n                      tradingAccount=account,\n                      userDef='')\n\n        rcode = api.NewOrder(order)\n\n        if rcode == RCode.OK:\n            print(f'Order sent successfully: {symbol}')\n        else:\n            print(f'Order failed! Stock symbol: {symbol}. Please run the program again and adjust the input based on the returned data.')\n<\/code><\/pre>\n<h2 class=\"wp-block-heading\">Main Program Flow for Automated Order Placement<\/h2>\n<p class=\"wp-block-paragraph\">The primary flow of the automated order placement program is as follows:<\/p>\n<pre class=\"wp-block-code\"><code>def main():\n\n    trader = ConcreteMarketTrader()\n\n    api = MasterTradeAPI(trader)\n\n    api.SetConnectionHost('solace140.masterlink.com.tw:55555')\n\n    # Log in to the trading server\n    rc = api.Login(username, password, True, True, True)\n\n    if rc == RCode.OK:\n\n        print('Successfully connected to the trading server, proceeding with two-factor authentication')\n\n        # Retrieve accounts and perform verification\n        accounts = [x[4:] for x in api.accounts]\n\n        rcc = api.CheckAccs(tradingAccounts=accounts)\n\n        if rcc == RCode.OK:\n\n            print('Verification passed, API trading functions are available')\n\n    execute_order(api, stock_id_list)\n\n    input(\"Press Enter to finish...\\n\")\n\nmain()\n<\/code><\/pre>\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\">This article demonstrates how to use MasterLink Securities\u2019 API for automated order placement, applying Buffett\u2019s value investing strategy in practical scenarios. We covered how to set up the trading environment, execute the strategy, and follow the order placement process. By utilizing programmatic trading, investors can enhance trading efficiency. In the next article, we will introduce the usage and examples of the SinoPac API, guiding readers further into the field of algorithmic trading.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The Buffett stock selection rules and API automation program in this article are for demonstration purposes only and do not guarantee profitability. Investing involves risks, and strategies may result in gains or losses. When referencing this article to develop investment strategies, it is recommended to incorporate both personal and external information, specify the quantity and price for each stock order, and strictly manage risk.<\/p>\n<p class=\"wp-block-paragraph\">In the future, TEJ will continue using its database and TQuant Lab to construct various indicators and backtest their performance. Readers interested in trading backtesting are encouraged to explore <strong><a href=\"https:\/\/tquant.tejwin.com\/\" rel=\"noopener\" target=\"_blank\">TQuant Lab<\/a><\/strong>\u2018s offerings. With a high-quality database, you can build a trading strategy tailored to your needs.<\/p>\n<div class=\"wp-block-button has-custom-width wp-block-button__width-100 has-custom-font-size\" style=\"font-size:20px\"><a class=\"wp-block-button__link has-background wp-element-button\" href=\"\/en\/databank-solution\/market-data\/\" style=\"border-radius:16px;background:linear-gradient(135deg,rgb(255,234,148) 0%,rgb(106,215,179) 50%,rgb(33,139,194) 100%)\"><strong>Access to Comprehensive <strong>Industrial Market <\/strong>Data<\/strong><br \/><strong>Start Building Portfolios That Outperforms the Market Today!<\/strong><\/a><\/div>\n<p class=\"wp-block-paragraph\">\n<h2 class=\"wp-block-heading\">Source Code<\/h2>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Quant\/blob\/main\/%E5%85%83%E5%AF%8C%20API%20%E4%B8%8B%E5%96%AE%E4%BB%8B%E7%B4%B9.ipynb\" rel=\"noopener\" target=\"_blank\">Github<\/a><\/p>\n<h2 class=\"wp-block-heading\">Further Reading<\/h2>\n<ul class=\"wp-block-list\">\n<li><a href=\"\/en\/insight\/counter-indicator\/\">Counter-Indicator Analysis: Using TEJ API to Examine the Relationship Between Stock Prices and Counter-Indicators Issued By Authority\u201d<\/a><\/li>\n<li><a href=\"\/en\/insight\/election-market-trend\/\">Is There an Election Market Trend ? Research on Presidential Elections Using TEJ API <\/a><\/li>\n<\/ul>\n<p class=\"wp-block-paragraph\">\n","protected":false},"excerpt":{"rendered":"<p>In modern financial markets, algorithmic trading is increasingly becoming essential for investors to enhance efficiency and reduce risk. More and more brokerage firms offer API services, enabling investors to automate order placement and quickly respond to market changes. This article will demonstrate using  MasterLink Securities API for automated trading while integrating strategies from TQuant Lab. Through a practical example, we\u2019ll show how a systematic approach can optimize investment decisions, helping investors seize market opportunities and improve performance.<\/p>\n","protected":false},"featured_media":1213,"template":"","tags":[91,104],"insight_category":[16],"class_list":["post-1214","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-beginners-guide","tag-trading","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/1214","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/1213"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=1214"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=1214"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=1214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}