[Barley and Xiaomi Learning Quantification] Use Tianqin TqSdk to realize futures quantitative trading (getting started)

The story of soy sauce latte

One day, Xiaomi asked Damai: "I heard that futures are very scary. Many people lose money and lose their pants."
Damai: "That's because they don't set stop losses for heavy positions. Futures can easily set stop profits and stop losses. Will it?" Only those who are able to stop losses will not be kicked off the gambling table."
"Futures are gambling? Then I won't play!" Xiaomi waved his hands and shook his head, as if he was afraid of being evil.
"Gambling and investing are just a matter of thought. The key depends on your grasp of the current situation!" Damai muttered to himself thoughtfully.
Then Damai added: "Investing in futures means trading risks! Leverage magnifies the risks, so you should keep your money in the bank!" Xiaomi
immediately retorted: "You are looking down on people, I can use quantification to avoid risks!"
"Oh, so you know Tianqin Quantification?"
"Where is it? I want to learn it. Can you teach me?"
"It's not difficult. Just give me a cup of soy sauce latte every day!"


Closer to home, quantitative trading actually started in gold and foreign exchange (MT4/MT5). Later, there were various quantitative trading software for futures, including Wenhua Finance, Pyramid, MC Quantitative, etc. in China. Today we will discuss how to use python to call Tianqin TqSdk to implement futures quantitative trading.

提示:以下是本篇文章正文内容,下面案例仅供参考

1. What is TqSdk?

TqSdk is an open source python library initiated by Xinyi Technology and contributed the main code. Relying on Kuaiqi's mature trading and market server system accumulated over many years, TqSdk supports users to build various types of quantitative trading strategy programs with a small amount of code, and Provide a complete solution including historical data - real-time data - development and debugging - strategy backtesting - simulated trading - real trading - operation monitoring - risk management.

Tianqin's python library is the author's simplest and easiest to understand quantitative library, and is suitable for beginners to get started.

2. Preparation work

1. Install the tqsdk library (the Python environment is prepared in advance)

The core of Tianqin Quantification is the TqSdk development kit. Before installing Tianqin Quantification (TqSdk), you need to prepare the appropriate environment and Python package management tools, including: Python >=3.6.4, 3.7, 3.8, 3.9
versions, I There is no problem installing in version 3.10.

There will be no problem installing Windows 7 or above, Mac Os, or Linux, Win10, or Win11.

It is recommended to use the pip command to install/upgrade TqSdk. The command line is as follows (provided that you have already installed the python environment. It is recommended to install Anaconda, which comes with a python operating environment and various supporting libraries, saving a lot of trouble):

pip install tqsdk -U -i https://pypi.tuna.tsinghua.edu.cn/simple

2. Register for an express account

Tianqin’s futures software is called Kuaiqi, and it also has an APP. We need to use Tianqin to quantify, and we must first register for a quick deposit account. Enter the Tianqin Quantification homepage and use your mobile phone number to register directly, which is very convenient.
https://www.shinnytech.com/tianqin/

3. Supported futures companies (updates are subject to official announcement)

https://www.shinnytech.com/blog/tq-support-broker/Can
be used directly after application. Supported ETF options
A Anliang Futures F Founder Mid-Term W Minmetals Economics_ETF
B Beite Futures H Hongye Futures N Nanhua Futures_ETF
B Baocheng Futures Y Galaxy Futures G Guotai Junan_ETF
B Bohai Futures G Guolian Futures G Everbright Futures_ETF
C Chuangyuan Futures D Orient Securities Futures G Guoyuan Futures_ETF
C Great Wall Futures G Everbright Futures H Hongyuan Futures_ETF
C Yangtze River Futures S Shenwan Futures
D Donghua Futures H Huatai Futures
D Orient Huijin D China Eastern Futures D
Donghai Futures C Changan Futures
D Dadi Futures Z Zhongjin Lingnan Futures
D Dayou Futures G Guotai Junan
D Dayue Futures X Cinda Futures
D Mainland Futures Z Zijin Tianfeng
F Funeng Futures D Dongwu Futures D Dongwu Futures_Suzhou
D First Venture Z CICC Fortune
G Guantong Futures Y Yongan Futures
G Guosen Futures
G Guoyuan Futures
G Guofu Futures
G Guangzhou Futures
G SDIC AnxinG
Guoxin Guozheng FuturesG
Guohai LiangshiG Guosheng
FuturesG Guomao FuturesG Guojin FuturesG International FuturesG Guangfa Futures




G Guangjin Futures
G Green Dahua
G Hong Kong Xin Futures H Huachuang Futures H Hua'an
Futures H Huajin Futures H Huaxin Futures H Huawen Futures H Hualong Futures H Hehe Futures H Herong Futures H Hongyuan Futures H Huishang Futures H Hengli Futures H Hengtai Futures H Haihang Futures H Haizheng Futures H Haitong Futures H Chaos Tiancheng H Hongta Futures J Jianxin Futures J Jianghai Huixin J Jinxin Futures J Jinyuan Futures J Jinrui Futures J Jinshi Futures J Jintai Futures L Luzheng Futures (Zhongtai Futures) M Minsheng Futures M Melya Futures Note: Melya is the second seat of CTP, you need to switch to the corresponding seat to use M Maike Futures N Nanhua Futures P Ping An Futures Q Qianhai Futures Q Qisheng Futures R Rich Futures R Ruida Futures S Shanghai East Asia S Shanghai Oriental S Shanghai Mid-Term S Shanxi Sanli





































S Shanjin Futures
S Shengda Futures S
Shenhua Futures T Tong Hui
Futures T Tongguan Jinyuan
W
Minmetals Futures X New Era Futures _ _ _ _ _ _ _ _ _ _ Zhongrong Huixin Z Zhongyan Futures Z Zhongcai Futures Z Zhonghui Futures Z China Steel Futures Z China Merchants Futures Z Zheshang Futures



























3. Try your hand at the knife for the first time

The following code can obtain the 10-second line of the DCE.jm2401 contract and update the data.

1. Sample code:

# 引入TqSdk模块
from tqsdk import TqApi, TqAuth
# 创建api实例,设置web_gui=True生成图形化界面
api = TqApi(web_gui=True, auth=TqAuth("快期账户", "账户密码")) # 使用手机号码即可注册,注册过程也很简单。
# 订阅 DCE.jm2401 合约的10秒线
klines = api.get_kline_serial("DCE.jm2401", 10)
while True:
    # 通过wait_update刷新数据
    api.wait_update()

The operation logic of Tianqin SDK is very simple, as shown below. Isn't it very simple? It's not like those event-driven ones that have a bunch of on functions and a few callback functions, which can make beginners confused.
Insert image description here

2. The prompt after running is as follows:

在使用天勤量化之前,默认您已经知晓并同意以下免责条款,如果不同意请立即停止使用:https://www.shinnytech.com/blog/disclaimer/
2023-09-06 23:43:31 -     INFO - 您可以访问 http://127.0.0.1:51960 查看策略绘制出的 K 线图形。
2023-09-06 23:43:37 -     INFO - 通知 : 与 wss://free-api.shinnytech.com/t/nfmd/front/mobile 的网络连接已建立

3. Use browser to access

Use a browser to access http://127.0.0.1:51960 to view the K-line graphics drawn by the strategy, as follows:
Insert image description here
It is very simple to implement a graphical interface in TqSdk. Just pass in the parameter web_gui = True in TqApi. A set of solutions to meet the real offer/backtest needs.
The port here is random. If you require a fixed web_gui URL, you can pass in the local IP + port, such as web_gui = "http://192.168.1.5:5888" (the local IP + port needs to be filled in) to access the fixed URL.

4. Simulated trading and real trading

After struggling for so long, what everyone is most concerned about is how to trade. Tianqin is very generous, even free users can associate a real futures account. This is so convenient! Just find a futures company supported by Tianqin and open an account.

1. Use a fast account to simulate trading

The [Mobile Phone Number]/[Email Address]/[User Name] and [Password] of the registered Quick Issue account can be used as the Quick Issue simulation account, and the auth incoming parameters are logged in through TqKq. This Quick Issue simulation account is in the Quick Issue APP, QQ Professional Edition and Tianqin Quantitative are interoperable:

from tqsdk import TqApi, TqAuth, TqKq
api = TqApi(TqKq(), auth=TqAuth("快期账户", "账户密码"))

Demo account funds: 10000000.00, enough for you to do whatever you want.

2. Use a quick account for real trading

For the free version of TqSdk, each express account supports binding to up to one real account, while the Tianqin Quantitative Professional Edition supports one express account to bind any number of real accounts.
Insert image description here

The fast-term account will be automatically bound when the user uses a real-deal account until the fast-term account has no quota to bind a real-deal account (the automatic binding function requires TqSdk version > 1.8.3):

from tqsdk import TqApi, TqAccount, TqAuth, TqKq
api = TqApi(TqAccount("H海通期货", "320102", "123456"), auth=TqAuth("快期账户", "账户密码"))

If you need to register an express account or modify the real account bound to your express account, please refer to the login user management center.

注意:实盘之前请务必先模拟测试,否则学费可不是小数目。还是那句话,投资有风险,入市需谨慎!量化不是神,它只是提高了操作效率,但错误的方向,效率越高,亏损越快!

5. Quantitative strategy trading (single moving average strategy)

After binding the above account relationships, you can use quantitative strategies to conduct quantitative transactions.

#  -*- coding: utf-8 -*-
from tqsdk import TqApi, TqAuth
'''
如果当前价格大于10秒K线的MA15则开多仓 (使用 insert_order() 函数)
如果小于则平仓
'''
# 模拟使用这个api
api = TqApi(auth=TqAuth("快期账户", "账户密码"))
# 实盘使用下面这个api,模拟、实盘二选一
# api = TqApi(TqAccount("H海通期货", "320102", "123456"), auth=TqAuth("快期账户", "账户密码"))

# 获取 DCE.jm2401 10秒K线的引用
klines = api.get_kline_serial("DCE.jm2401", 10)

# 判断开仓条件
while True:
    api.wait_update()
    if api.is_changing(klines):
        ma = sum(klines.close.iloc[-15:]) / 15
        print("最新价", klines.close.iloc[-1], "MA", ma)
        if klines.close.iloc[-1] > ma:
            print("最新价大于MA: 市价开仓")
            api.insert_order(symbol="DCE.jm2401", direction="BUY", offset="OPEN", volume=5)
            break
# 判断平仓条件
while True:
    api.wait_update()
    if api.is_changing(klines):
        ma = sum(klines.close.iloc[-15:]) / 15
        print("最新价", klines.close.iloc[-1], "MA", ma)
        if klines.close.iloc[-1] < ma:
            print("最新价小于MA: 市价平仓")
            api.insert_order(symbol="DCE.jm2401", direction="SELL", offset="CLOSE", volume=5)
            break
# 关闭api,释放相应资源
api.close()

Summarize

Tianqin's tqSDK is indeed very good and has received many praises in the industry. Everything is difficult at the beginning, so here’s a good introduction. In fact, the official online instructions are so considerate. They have documented everything you can think of! In addition, we are mainly doing futures at the moment, and we will wait for the official update to see other things.

Another: The tqsdk.ta module contains a large number of technical indicators. Each technical indicator is a function, the function name is in all capital letters, the first parameter is always the K-line sequence, and the calculation results are returned in pandas.DataFrame format. This is so convenient. You can refer to the official documentation directly to call it. For more exciting content, everyone is welcome to discover and share.

appendix

Tianqin SDK installation record:

(base) C:\Users\Administrator>pip install tqsdk -U -i https://pypi.tuna.tsinghua.edu.cn/simple
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting tqsdk
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/58/9a/f8d3d7cf5d82de0559f7228b7460acfaf066d6a6c9a729c5ea75b00cbbd9/tqsdk-3.4.7-py3-none-any.whl (1.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.7/1.7 MB 18.7 MB/s eta 0:00:00
Requirement already satisfied: simplejson in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (3.19.1)
Requirement already satisfied: aiohttp in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (3.8.4)
Requirement already satisfied: websockets>=8.1 in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (10.4)
Collecting sgqlc
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/3c/82/18f202b0891bc41e556e48e72e3ec9e83362f28cfbb4744dd9bd77a3d192/sgqlc-16.3-py3-none-any.whl (81 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 81.6/81.6 kB ? eta 0:00:00
Requirement already satisfied: scipy in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (1.10.0)
Requirement already satisfied: pyjwt in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (2.4.0)
Requirement already satisfied: requests in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (2.28.2)
Requirement already satisfied: filelock in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (3.12.0)
Collecting tqsdk-sm
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/b5/af/4b92033cccb53d42cfbabfc82e41cbd372fdf0f56a3b550c00dc7064e59c/tqsdk_sm-1.0.5-py3-none-win_amd64.whl (23.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 23.0/23.0 MB 29.7 MB/s eta 0:00:00
Requirement already satisfied: pandas>=1.1.0 in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (2.0.1)
Collecting tqsdk-ctpse
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/e8/8c/6d6154174e4d5d97d2ce63c92c08ed0dcfd8ae553cf6e5a6361f7ca3db80/tqsdk_ctpse-1.0.2-py3-none-win_amd64.whl (897 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 897.3/897.3 kB 28.6 MB/s eta 0:00:00
Requirement already satisfied: numpy in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (1.23.5)
Collecting shinny-structlog
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/61/7e/e9289e6b2c677318b44e48eb8cd5bb7dc9fe786df640e78947cda7a325ae/shinny_structlog-0.0.4-py3-none-any.whl (8.8 kB)
Requirement already satisfied: certifi in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (2022.12.7)
Requirement already satisfied: psutil in d:\programdata\anaconda3\lib\site-packages (from tqsdk) (5.9.0)
Requirement already satisfied: pytz>=2020.1 in d:\programdata\anaconda3\lib\site-packages (from pandas>=1.1.0->tqsdk) (2022.7)
Requirement already satisfied: python-dateutil>=2.8.2 in d:\programdata\anaconda3\lib\site-packages (from pandas>=1.1.0->tqsdk) (2.8.2)
Requirement already satisfied: tzdata>=2022.1 in d:\programdata\anaconda3\lib\site-packages (from pandas>=1.1.0->tqsdk) (2023.3)
Requirement already satisfied: frozenlist>=1.1.1 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (1.3.3)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (2.0.4)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (4.0.2)
Requirement already satisfied: yarl<2.0,>=1.0 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (1.8.2)
Requirement already satisfied: aiosignal>=1.1.2 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (1.3.1)
Requirement already satisfied: multidict<7.0,>=4.5 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (6.0.4)
Requirement already satisfied: attrs>=17.3.0 in d:\programdata\anaconda3\lib\site-packages (from aiohttp->tqsdk) (22.1.0)
Requirement already satisfied: idna<4,>=2.5 in d:\programdata\anaconda3\lib\site-packages (from requests->tqsdk) (3.4)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\programdata\anaconda3\lib\site-packages (from requests->tqsdk) (1.26.14)
Collecting graphql-core<4.0.0,>=3.1.7
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/f8/39/e5143e7ec70939d2076c1165ae9d4a3815597019c4d797b7f959cf778600/graphql_core-3.2.3-py3-none-any.whl (202 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 202.9/202.9 kB 12.0 MB/s eta 0:00:00
Requirement already satisfied: six>=1.5 in d:\programdata\anaconda3\lib\site-packages (from python-dateutil>=2.8.2->pandas>=1.1.0->tqsdk) (1.16.0)
Installing collected packages: tqsdk-sm, tqsdk-ctpse, shinny-structlog, graphql-core, sgqlc, tqsdk
Successfully installed graphql-core-3.2.3 sgqlc-16.3 shinny-structlog-0.0.4 tqsdk-3.4.7 tqsdk-ctpse-1.0.2 tqsdk-sm-1.0.5

(base) C:\Users\Administrator>

Guess you like

Origin blog.csdn.net/popboy29/article/details/132725878