Table of Contents
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’ll show how a systematic approach can optimize investment decisions, helping investors seize market opportunities and improve performance.
This guide uses Warren Buffett’s corporate investment principles as an example. Refer to TQuant Lab’s Warren Buffett Corporate Investment Rules for a detailed introduction.
The quantitative indicators used in this strategy include:
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.
According to the stock selection criteria in the corporate investment rules, we require the following 7 financial items:
The cash flow from operations and the cash flow from investments can be used to calculate the free cash flow.
Free Cash Flow = Cash Flow from Operations + (-) Cash Flow from Investments
Note that the cash flow from investments is often a negative number.
p.s.
Detailed instructions for using the TejToolAPI can be found on the TQuant Lab GitHub: TejToolAPI Documentation.
The datasets provided by the TejToolAPI can be referenced on the TQuant Lab official website: TQuant Lab Datasets.
We select stocks meeting the criteria as of 2015-12-31. 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.
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 Electronic Components and Semiconductor industries.
This gives us the stock pool selected using this strategy. Next, we proceed to the formal order placement stage.
The verification process includes the following steps:
STEP 1:
Download the API component and use your program to log in to the MasterLink Securities API. Log in to the test environment.
STEP 2:
Place, modify, and cancel ROD orders (verify the order details on the Digital API website and execute the order through your program).
STEP 3:
Place IOC orders (verify the order details on the Digital API website and execute the order through your program).
STEP 4:
Place FOK orders (verify the order details on the Digital API website and execute the order through your program).
STEP 5:
After placing the order, enter the order number on the Digital API website verification page.
STEP 6:
For Steps 3, 4, and 5, after entering the order number, click “Verify” on the Digital API website verification page.
STEP 7:
Once the verification is successful, the process is complete. Please wait for the manual review to finalize the approval process before gaining access.
First, you must install MasterTradePy, which can help you implement automated trading strategies.
Use the cd command in the terminal to navigate to the MasterTradePy folder.
cd MasterTradePy
pip install MasterTradePy-0.0.15-py3-none-win_amd64.whl
Return to your code editor and load the required packages for the API.
import threading
from MasterTradePy.api import MasterTradeAPI
from MasterTradePy.model import *
from MasterTradePy.constant import PriceType, OrderType, TradingSession, Side, TradingUnit, RCode
Set up your account credentials (account and password) and specify the target stock codes.
Here, we create a list of stock codes selected based on the Buffett Strategy, representing the stock pool.
username = 'your_username'
password = 'your_password'
stock_id_list = [
1476, 1477, 2467, 3006, 3014, 3034,
3042, 3413, 3533, 3557, 5234, 5269,
6202, 8016, 8046, 8081, 9906
]
event = threading.Event()
Explanation
event = threading.Event()
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.
event = threading.Event()
We will place market orders to buy all the stocks in the stock pool.
def execute_order(api, stock_id_list):
account = 'your_account'
price = '' # Leave blank for market order
qtr = '1000' # For 1 lot, enter 1000
orderType = OrderType.ROD
if not price:
priceType = PriceType.MKT
else:
priceType = PriceType.LMT
for stock_id in stock_id_list:
symbol = stock_id
order = Order(tradingSession=TradingSession.NORMAL,
side=Side.Buy,
symbol=symbol,
priceType=priceType,
price=price,
tradingUnit=TradingUnit.COMMON,
qty=qty,
orderType=orderType,
tradingAccount=account,
userDef='')
rcode = api.NewOrder(order)
if rcode == RCode.OK:
print(f'Order sent successfully: {symbol}')
else:
print(f'Order failed! Stock symbol: {symbol}. Please run the program again and adjust the input based on the returned data.')
The primary flow of the automated order placement program is as follows:
def main():
trader = ConcreteMarketTrader()
api = MasterTradeAPI(trader)
api.SetConnectionHost('solace140.masterlink.com.tw:55555')
# Log in to the trading server
rc = api.Login(username, password, True, True, True)
if rc == RCode.OK:
print('Successfully connected to the trading server, proceeding with two-factor authentication')
# Retrieve accounts and perform verification
accounts = [x[4:] for x in api.accounts]
rcc = api.CheckAccs(tradingAccounts=accounts)
if rcc == RCode.OK:
print('Verification passed, API trading functions are available')
execute_order(api, stock_id_list)
input("Press Enter to finish...\n")
main()
This article demonstrates how to use MasterLink Securities’ API for automated order placement, applying Buffett’s 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.
Note: 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.
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 TQuant Lab‘s offerings. With a high-quality database, you can build a trading strategy tailored to your needs.
Subscribe to newsletter