tqsdk中的异步模式模板

天勤量化中异步是很好的一个方式, 这个带有一个tkinter的图形界面。
可以正常退出

以下是一个模板,

点击查看代码
import sys
import traceback
from tqsdk import TqApi, TqAuth
import time
import os
import re
import pandas as pd
import numpy as np
import datetime
import asyncio
import tkinter as tk
import threading

chan_dict={}                                                                                    #全局变量,存储update_chan
async def trade_x(symbol,period):
    money=20000 #单笔保证金
    klines=await api.get_kline_serial(symbol,int(period.replace('m','')) * 60,data_length=1200) #获取k线数据
    q =await  api.get_quote(symbol)                                                             #获取quote数据
    min_step=q.price_tick                                                                       #最下跳动
    contract_size=q.volume_multiple                                                             #合约大小

    async with api.register_update_notify() as update_chan:                                      
        chan_dict[symbol+'_'+period]=update_chan
        async for _ in update_chan:
            if _=='close_me':                                                                    #退出机制
                await update_chan.close()
                del chan_dict[symbol+'_'+period]

                break
            if not api.is_serial_ready(klines):                                                   #数据准备
                print(symbol,period,'klines还没准备好')
                return
            if np.isnan(q.ask_price1) or np.isnan(q.bid_price1):
                print(symbol,period,'q is nan')
                return 
         

            if api.is_changing(klines.iloc[-1],'datetime'):                                      
                 ##  相当于on_bar,k线结束的逻辑代码在这里实现
                pass
                                
            if api.is_changing(klines.iloc[-1],['close']):
                ##  相当于on_tick ,tick数据的last_price价格发生变化时,触发的代码段在这里实现
                pass


class MY_GUI():                                                                         ### 图形界面段
    def __init__(self,window,api):
        self.api=api
        self.window=window
        self.window.geometry('200x100+400+300')
        self.button1=tk.Button(self.window,text='关闭',command=self.on_closing)
        self.button1.pack(side='left',anchor='sw',padx=0,pady=0)
        self.window.protocol("WM_DELETE_WINDOW",self.on_closing)                          #绑定关闭函数
        self.close_status=False
    def on_closing(self):                         
        self.close_status=True
        chan_list=list(chan_dict.values())
        for chan in chan_list:
            chan.send_nowait('close_me')                                                   #关闭所有的协程
            print('关闭',chan)
        self.api._set_wait_timeout()
        self.window.destroy()                               
                
def api_run(api,X_GUI):                                                                   #子进程,阻塞监听数据
            
    while True:
        if X_GUI.close_status:                                                             
            break
        api.wait_update()    
    api.close()

if __name__ == "__main__":
    try:
        api = TqApi(auth=TqAuth("你的userid", "你的密码"))
        symbol_list=['DCE.m2501','SHFE.cu2409']
        for period in ['5m','15m']:
            for symbol in symbol_list:
                api.create_task(trade_x(symbol,period))                                  #创建协程任务
        root=tk.Tk()
        X_GUI=MY_GUI(root,api)
        api_run_thread=threading.Thread(target=api_run,args=(api,X_GUI,),name='图形')     #子线程监控
        api_run_thread.start()
        root.mainloop()
    except Exception as e:
        print('Future Server Erro',e)    
posted @ 2024-08-09 22:09  远方_2408  阅读(57)  评论(0)    收藏  举报