onequant-pyautogui

发布时间 2023-12-25 23:24:30作者: liuweipaul123
import os
import time
import socket
from datetime import datetime
import datetime
# from wsgiref import headers

import pandas as pd
from cmath import isnan
import random
import csv
import copy
import codecs
from multiprocessing import Pool

import datetime
import json
import time
import requests
from tkinter import filedialog, messagebox
import tkinter as tk
import random
from tkinter.ttk import Combobox
from tkinter import messagebox
from tkinter import *
from tkinter.messagebox import *
from tkinter import font
import threading
import keyboard
import time


class Application(Frame):
    def __int__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        # self.createWidget01()
        self.collect_Algo = []
        self.collect_Algo_param = {}
        self.running = False
        self.thread = None
        self.pythonGUI()

    def pythonGUI(self):
        # 登录客户端
        self.loginClient_var = IntVar()
        self.loginClient = Checkbutton(root, text="登录客户端", font=('仿宋体', 10, 'bold'), fg="blue",variable=self.loginClient_var)
        self.loginClient.place(x=5, y=7)
        Label(root, text="---------------------------------------------------------------------:", fg="orange",
              font=('仿宋体', 30, 'bold')).place(x=5, y=23)

        # Label(root, text="提示:必须选择至少一个算法", font=('仿宋体', 10, 'bold'), fg="red").place(x=5, y=5)
        self.smartOrder_var0 = IntVar()
        self.smartOrder_var1 = IntVar()
        self.smartOrder_var2 = IntVar()
        self.smartOrder_var3 = IntVar()
        self.smartOrder_var4 = IntVar()
        self.smartOrder_var5 = IntVar()
        self.smartOrder = Checkbutton(root, text='快捷交易:', font=('仿宋体', 10, 'bold'), fg="blue",
                                   variable=self.smartOrder_var0, onvalue=1, offvalue=0,
                                   command=self.smartOrderFun)
        self.smartOrder.place(x=5, y=60)
        self.smartOrder1 = Checkbutton(root, text="限价", font=('仿宋体', 10, 'bold'), fg="green",variable=self.smartOrder_var1)
        self.smartOrder1.place(x=100, y=60)
        self.smartOrder2 = Checkbutton(root, text="市价", font=('仿宋体', 10, 'bold'), fg="green",variable=self.smartOrder_var2)
        self.smartOrder2.place(x=180, y=60)
        self.smartOrder3 = Checkbutton(root, text="跟价", font=('仿宋体', 10, 'bold'), fg="green", variable=self.smartOrder_var3)
        self.smartOrder3.place(x=260, y=60)
        self.smartOrder4 = Checkbutton(root, text="金额", font=('仿宋体', 10, 'bold'), fg="green", variable=self.smartOrder_var4)
        self.smartOrder4.place(x=340, y=60)
        self.smartOrder5 = Checkbutton(root, text="算法", font=('仿宋体', 10, 'bold'), fg="green", variable=self.smartOrder_var5)
        self.smartOrder5.place(x=420, y=60)



        self.HXAlgo_var0 = IntVar()
        self.HXAlgo_var1 = IntVar()
        self.HXAlgo_var2 = IntVar()

        self.HXAlgo1 = Checkbutton(root, text='HXAlgo:', font=('仿宋体', 10, 'bold'), fg="blue",
                                   variable=self.HXAlgo_var0, onvalue=1, offvalue=0,
                                   command=self.HXAlgo)
        self.HXAlgo1.place(x=5, y=100)
        self.HXAlgo2 = Checkbutton(root, text="HX_SMART_TWAP", font=('仿宋体', 10, 'bold'), fg="green",
                                   variable=self.HXAlgo_var1)
        self.HXAlgo2.place(x=100, y=100)
        self.HXAlgo3 = Checkbutton(root, text="HX_SMART_VWAP", font=('仿宋体', 10, 'bold'), fg="green",
                                   variable=self.HXAlgo_var2)
        self.HXAlgo3.place(x=280, y=100)

        self.FTAlgo_var0 = IntVar()
        self.FTAlgo_var1 = IntVar()

        self.FTAlgo0 = Checkbutton(root, text='FTAlgo:', font=('仿宋体', 10, 'bold'), fg="blue",
                                   variable=self.FTAlgo_var0, onvalue=1, offvalue=0,
                                   command=self.FTAlgo)
        self.FTAlgo0.place(x=5, y=125)
        self.FTAlgo1 = Checkbutton(root, text="FT_AI_WAP", font=('仿宋体', 10, 'bold'), fg="green",
                                   variable=self.FTAlgo_var1)
        self.FTAlgo1.place(x=100, y=125)

        self.QNDAlgo_var0 = IntVar()
        self.QNDAlgo_var1 = IntVar()
        self.QNDAlgo_var2 = IntVar()

        self.QNDAlgo1 = Checkbutton(root, text='QNDAlgo:', font=('仿宋体', 10, 'bold'), fg="blue",
                                    variable=self.QNDAlgo_var0, onvalue=1, offvalue=0,
                                    command=self.QNDAlgo)
        self.QNDAlgo1.place(x=5, y=150)
        self.QNDAlgo2 = Checkbutton(root, text="QNDTWAP", font=('仿宋体', 10, 'bold'), fg="green",
                                    variable=self.QNDAlgo_var1)
        self.QNDAlgo2.place(x=100, y=150)
        self.QNDAlgo3 = Checkbutton(root, text="QNDVWAP", font=('仿宋体', 10, 'bold'), fg="green",
                                    variable=self.QNDAlgo_var2)
        self.QNDAlgo3.place(x=280, y=150)

        self.YRAlgo_var0 = IntVar()
        self.YRAlgo_var1 = IntVar()

        self.YRAlgo0 = Checkbutton(root, text='YRAlgo:', font=('仿宋体', 10, 'bold'), fg="blue",
                                   variable=self.YRAlgo_var0, onvalue=1, offvalue=0,
                                   command=self.YRAlgo)
        self.YRAlgo0.place(x=5, y=175)
        self.YRAlgo1 = Checkbutton(root, text="YRVWAP", font=('仿宋体', 10, 'bold'), fg="green",
                                   variable=self.YRAlgo_var1)
        self.YRAlgo1.place(x=100, y=175)

        Label(root, text="---------------------------------------------------------------------:", fg="orange",
              font=('仿宋体', 30, 'bold')).place(x=5, y=190)

        Button(root, text="输入资金账号", font=('仿宋体', 10, 'bold'), fg="blue", command=self.btnAcctFun).place(x=5,
                                                                                                                 y=225)

        Button(root, text="输入股票代码", font=('仿宋体', 10, 'bold'), fg="blue", command=self.btnSymbolFun).place(
            x=200, y=225)

        # Label(root, text="资金账号:",font=('仿宋体', 10, 'bold'),fg="blue").place(x=5, y=235)
        # self.acctType_acct = Text(root, font=('仿宋体', 10, 'bold'),height=1.3, width=80,fg="green")
        # self.acctType_acct.insert('1.0', "UF0_890500027916,UM0_20100051859")
        # self.acctType_acct.place(x=80, y=235)

        Label(root, text="每秒订单量:", font=('仿宋体', 10, 'bold'), fg="blue").place(x=5, y=264)
        self.targetVol = Text(root, font=('仿宋体', 10, 'bold'), height=1.3, width=10, fg="green")
        self.targetVol.insert('1.0', "10")
        self.targetVol.place(x=90, y=264)

        Label(root, text="运行结束时间:", font=('仿宋体', 10, 'bold'), fg="blue").place(x=200, y=264)
        self.runStopTime = Text(root, font=('仿宋体', 10, 'bold'), height=1.3, width=10, fg="green")
        self.runStopTime.insert('1.0', "230000")
        self.runStopTime.place(x=295, y=264)

        Label(root, text="批号起始值:", font=('仿宋体', 10, 'bold'), fg="blue").place(x=5, y=292)
        self.beginNum = Text(root, font=('仿宋体', 10, 'bold'), height=1.3, width=10, fg="green")
        self.beginNum.insert('1.0', "1")
        self.beginNum.place(x=90, y=292)

        Label(root, text="批号结束值:", font=('仿宋体', 10, 'bold'), fg="blue").place(x=200, y=292)
        self.endNum = Text(root, font=('仿宋体', 10, 'bold'), height=1.3, width=10, fg="green")
        self.endNum.insert('1.0', "50")
        self.endNum.place(x=295, y=292)

        Label(root, text="算法结束时间:", font=('仿宋体', 10, 'bold'), fg="blue").place(x=5, y=320)
        self.algoStopTimeSet = Text(root, font=('仿宋体', 10, 'bold'), height=1.3, width=10, fg="green")
        self.algoStopTimeSet.insert('1.0', "180000")
        self.algoStopTimeSet.place(x=100, y=324)
        self.algoStopTimeSet.bind("<Button-1>", self.algoStopTimeSet_bind)  # 点击输入框会清空算法结束时间单选框单选框

        global algoStopTime_var
        self.algoStopTime_var = StringVar()
        self.algoStopTime_var.set("6")
        # Radiobutton是单选文本框
        self.algoStopTime1 = Radiobutton(root, text="+5", font=('仿宋体', 10, 'bold'), fg="green", value="5",variable=self.algoStopTime_var, state="normal")
        self.algoStopTime1.place(x=180, y=320)
        self.algoStopTime2 = Radiobutton(root, text="+10", font=('仿宋体', 10, 'bold'), fg="green", value="10",
                                         variable=self.algoStopTime_var, state="normal")
        self.algoStopTime2.place(x=230, y=320)
        self.algoStopTime3 = Radiobutton(root, text="+20", font=('仿宋体', 10, 'bold'), fg="green", value="20",
                                         variable=self.algoStopTime_var, state="normal")
        self.algoStopTime3.place(x=280, y=320)
        self.algoStopTime4 = Radiobutton(root, text="+30", font=('仿宋体', 10, 'bold'), fg="green", value="30",
                                         variable=self.algoStopTime_var, state="normal")
        self.algoStopTime4.place(x=330, y=320)
        self.algoStopTime5 = Radiobutton(root, text="+60", font=('仿宋体', 10, 'bold'), fg="green", value="60",
                                         variable=self.algoStopTime_var, state="normal")
        self.algoStopTime5.place(x=380, y=320)
        Label(root, text="提示:+5表示算法只运行5分钟", font=('仿宋体', 10, 'bold'), fg="red").place(x=450, y=320)
        # 点击单选框会清空算法结束时间输入框
        self.algoStopTime1.config(command=lambda: self.radiobutton_command(self.algoStopTime1))
        self.algoStopTime2.config(command=lambda: self.radiobutton_command(self.algoStopTime1))
        self.algoStopTime3.config(command=lambda: self.radiobutton_command(self.algoStopTime1))
        self.algoStopTime4.config(command=lambda: self.radiobutton_command(self.algoStopTime1))
        self.algoStopTime5.config(command=lambda: self.radiobutton_command(self.algoStopTime1))

        self.label_orderNum = Label(root, text="生成订单数量为0", fg="red", font=('仿宋体', 10, 'bold'))
        self.label_orderNum.place(x=30, y=350)

        self.label_runStopNum = Label(root, text="运行结束批号值为0", fg="red", font=('仿宋体', 10, 'bold'))
        self.label_runStopNum.place(x=200, y=350)
        self.num = 0

        Label(root, text="---------------------------------------------------------------------:", fg="orange",
              font=('仿宋体', 30, 'bold')).place(x=5, y=365)

        self.btn_Algo = Button(root, text="onequant", font=('times', 19, 'bold'), bg='orange', command=self.toggle_running)
        self.btn_Algo.place(x=5, y=400)

        # self.photo = PhotoImage(file="E:/桌面/lwpaul/algoImport/imgs/logo.gif")
        # # image_create(END, image=self.photo)
        # Label(root, image=self.photo).place(x=5, y=350)

        # self.clock = Label(root, font=('times', 20, 'bold'), bg='orange')
        self.clock_second = 1000
        self.clock = Button(root, font=('times', 19, 'bold'), bg='orange', command=self.photoFun)
        self.clock.place(x=150, y=400)
        self.time_update()


    def btnSaveSymbolFun(self):  # 保存股票
        try:
            os.remove(symbol_file)
        except:
            print(symbol_file + "文件不存在")

        # 生成资金账号的CSV文件
        with open(symbol_file, "a+", newline='') as file:
            csv_file = csv.writer(file)
            datas = [["symbol"]]
            csv_file.writerows(datas)

        text_saveAcct = self.text_symbol.get(1.0, END)
        comma = 0  # 点的个数
        for i in text_saveAcct:
            if i == ".":
                comma = comma + 1
            if comma >= 2:
                break
        print("comma", comma)

        print("acctType112233", text_saveAcct)
        if comma == 1:
            print(333)
            symbol = text_saveAcct.replace("\n", "")
            print("acctType12", symbol)
            Parameter = []
            Parameters = []
            Parameter.append(symbol)
            Parameters.append(Parameter)

            with open(symbol_file, "a+", newline='') as file:
                csv_file = csv.writer(file)
                csv_file.writerows(Parameters)
        else:
            text_saveAcct_split = text_saveAcct.split("\n")
            print("15", text_saveAcct_split)
            for i in range(len(text_saveAcct_split)):
                if text_saveAcct_split[i] != "":
                    symbol = text_saveAcct_split[i]

                    print("symbol9999", symbol)
                    Parameter = []
                    Parameters = []
                    Parameter.append(symbol)
                    Parameters.append(Parameter)

                    with open(symbol_file, "a+", newline='') as file:
                        csv_file = csv.writer(file)
                        csv_file.writerows(Parameters)

    def btnSymbolFun(self):  # 输入股票
        root_btnSymbol = Tk()
        root_btnSymbol.geometry("200x500+230+200")
        self.btnSaveSymbol = Button(root_btnSymbol, text="点击保存", font=('仿宋体', 10, 'bold'), fg="blue",
                                    command=self.btnSaveSymbolFun)
        self.btnSaveSymbol.pack()
        self.text_symbol = Text(root_btnSymbol, height=50, width=42, fg='green', font=("仿宋体", 12))  # "helvetica"
        self.text_symbol.pack(side=LEFT)
        # 在文本框开头插入一段话
        filename = "symbol.csv"
        current_directory = os.getcwd()  # 获取当前目录
        print("current_directory", current_directory)
        file_path = os.path.join(current_directory, filename)  # 构建文件路径
        print("file_path", file_path)
        if os.path.isfile(file_path):  # 检查文件是否存在并且是.csv文件
            data = pd.read_csv(symbol_file, encoding="gbk")
            if len(data["symbol"]) == 0:
                self.text_symbol.insert('1.0', '000001.SZ\n300001.SZ\n600000.SH\n688001.SH')
            else:
                data_text = ""
                for i in range(len(data["symbol"])):
                    data_text = data_text + data["symbol"][i] + "\n"
                print("data_text", data_text)
                self.text_symbol.insert('1.0', data_text)
        else:
            self.text_symbol.insert('1.0', '000001.SZ\n300001.SZ\n600000.SH\n688001.SH')

        scrollbar = Scrollbar(root_btnSymbol, command=self.text_symbol.yview)
        scrollbar.pack(side=LEFT, fill=Y)
        self.text_symbol.configure(yscrollcommand=scrollbar.set)
        root_btnSymbol.mainloop()

    def btnSaveAcctFun(self):  # 保存资金账号
        try:
            os.remove(Acct_file)
        except:
            print(Acct_file + "文件不存在")

        # 生成资金账号的CSV文件
        with open(Acct_file, "a+", newline='') as file:
            csv_file = csv.writer(file)
            datas = [["acctType", "acct"]]
            csv_file.writerows(datas)

        text_saveAcct = self.text_widget.get(1.0, END)
        comma = 0  # 逗号的个数
        for i in text_saveAcct:
            if i == ",":
                comma = comma + 1
            if comma >= 2:
                break
        print("comma", comma)

        print("acctType112233", text_saveAcct)
        if comma == 1:
            print(333)
            acctType_acct = text_saveAcct.replace("\n", "").split(",")
            print("acctType12", text_saveAcct.split(","))
            print("acctType13", acctType_acct)
            acctType = acctType_acct[0]
            acct = acctType_acct[1]
            print("acctType", acctType)
            print("acct", acct)
            Parameter = []
            Parameters = []
            Parameter.append(acctType)
            Parameter.append(acct)
            Parameters.append(Parameter)

            with open(Acct_file, "a+", newline='') as file:
                csv_file = csv.writer(file)
                csv_file.writerows(Parameters)
        else:
            text_saveAcct_split = text_saveAcct.split("\n")
            print("15", text_saveAcct_split)
            for i in range(len(text_saveAcct_split) - 1):
                if text_saveAcct_split[i] != "":
                    acctType_acct = text_saveAcct_split[i].split(",")
                    acctType = acctType_acct[0]
                    acct = acctType_acct[1]
                    print("acctType", acctType)
                    print("acct", acct)
                    Parameter = []
                    Parameters = []
                    Parameter.append(acctType)
                    Parameter.append(acct)
                    Parameters.append(Parameter)

                    with open(Acct_file, "a+", newline='') as file:
                        csv_file = csv.writer(file)
                        csv_file.writerows(Parameters)

    def btnAcctFun(self):  # 输入资金长账号
        root_btnAcct = Tk()
        root_btnAcct.geometry("200x500+230+200")
        self.btnSaveAcct = Button(root_btnAcct, text="点击保存", font=('仿宋体', 10, 'bold'), fg="blue",
                                  command=self.btnSaveAcctFun)
        self.btnSaveAcct.pack()
        self.text_widget = Text(root_btnAcct, height=50, width=42, fg='green', font=("仿宋体", 12))  # "helvetica"
        self.text_widget.pack(side=LEFT)
        # 在文本框开头插入一段话
        filename = "Acct.csv"
        current_directory = os.getcwd()  # 获取当前目录
        print("current_directory", current_directory)
        file_path = os.path.join(current_directory, filename)  # 构建文件路径
        print("file_path", file_path)
        if os.path.isfile(file_path):  # 检查文件是否存在
            data = pd.read_csv(Acct_file, encoding="gbk")
            if len(data["acctType"]) == 0:
                self.text_widget.insert('1.0', 'UF0,89050027916\nUM0,20100051859')
            else:
                data_text = ""
                for i in range(len(data["acctType"])):
                    data_text = data_text + data["acctType"][i] + "," + str(data["acct"][i]) + "\n"
                print("data_text", data_text)
                self.text_widget.insert('1.0', data_text)
        else:
            self.text_widget.insert('1.0', 'UF0,89050027916\nUM0,20100051859')

        scrollbar = Scrollbar(root_btnAcct, command=self.text_widget.yview)
        scrollbar.pack(side=LEFT, fill=Y)
        self.text_widget.configure(yscrollcommand=scrollbar.set)
        root_btnAcct.mainloop()

    def time_update(self):
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        weekday = datetime.datetime.now().strftime("%A")
        self.clock.config(text=f"日期:{current_time}  星期:{weekday}")
        if self.clock_second == 1000:
            self.master.after(1000, self.time_update)
        else:
            time.sleep(1)
            self.master.after(1000, self.time_update)

    def photoFun(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            print("ip", ip)
        except:
            ip = "127.0.0.1"
        finally:
            s.close()

        messages = ["不要拍我", "今天是星期五", "我能倒着背出滕王阁序", "我猜你此刻不想下DMA算法",
                        "不好,今天下班忘记打卡了",
                        "面朝大海,春暖花开", "忘记了时光与风", "上班又迟到了,都怪早上下雨"]

        choice_messages = random.choice(messages)
        self.clock["text"] = choice_messages
        self.clock_second = 3000

    def algoStopTimeSet_bind(self, event):
        self.algoStopTime_var.set("6")

    def radiobutton_command(self, event):
        print("555", self.algoStopTime_var.get())
        self.algoStopTimeSet.delete(1.0, END)

    # def radiobutton_command1(self):
    #     print("555", self.algoStopTime_var.get())

    def smartOrderFun(self):
        if self.smartOrder_var0.get() == 1:
            self.smartOrder_var1.set(1)
            self.smartOrder_var2.set(1)
            self.smartOrder_var3.set(1)
            self.smartOrder_var4.set(1)
            self.smartOrder_var5.set(1)
        else:
            self.smartOrder_var1.set(0)
            self.smartOrder_var2.set(0)
            self.smartOrder_var3.set(0)
            self.smartOrder_var4.set(0)
            self.smartOrder_var5.set(0)

    def XTAlgo(self):
        print("111", self.XTAlgo_var1.get())
        if self.XTAlgo_var1.get() == 1:
            self.XTAlgo_var2.set(1)
            self.XTAlgo_var3.set(1)
            self.XTAlgo_var4.set(1)
        else:
            self.XTAlgo_var2.set(0)
            self.XTAlgo_var3.set(0)
            self.XTAlgo_var4.set(0)

    def KFAlgo(self):
        print("111", self.KFAlgo_var1.get())
        if self.KFAlgo_var1.get() == 1:
            self.KFAlgo_var2.set(1)
            self.KFAlgo_var3.set(1)
            self.KFAlgo_var4.set(1)
            self.KFAlgo_var5.set(1)
            self.KFAlgo_var6.set(1)
        else:
            self.KFAlgo_var2.set(0)
            self.KFAlgo_var3.set(0)
            self.KFAlgo_var4.set(0)
            self.KFAlgo_var5.set(0)
            self.KFAlgo_var6.set(0)

    def HXAlgo(self):
        print("111", self.HXAlgo_var0.get())
        if self.HXAlgo_var0.get() == 1:
            self.HXAlgo_var1.set(1)
            self.HXAlgo_var2.set(1)

        else:
            self.HXAlgo_var1.set(0)
            self.HXAlgo_var2.set(0)

    def FTAlgo(self):
        print("111", self.FTAlgo_var0.get())
        if self.FTAlgo_var0.get() == 1:
            self.FTAlgo_var1.set(1)

        else:
            self.FTAlgo_var1.set(0)

    def QNDAlgo(self):
        print("111", self.QNDAlgo_var0.get())
        if self.QNDAlgo_var0.get() == 1:
            self.QNDAlgo_var1.set(1)
            self.QNDAlgo_var2.set(1)

        else:
            self.QNDAlgo_var1.set(0)
            self.QNDAlgo_var2.set(0)

    def YRAlgo(self):
        print("111", self.YRAlgo_var0.get())
        if self.YRAlgo_var0.get() == 1:
            self.YRAlgo_var1.set(1)

        else:
            self.YRAlgo_var1.set(0)

    def do_something():
        while True:
            print("执行任务")
            time.sleep(2)

    # 创建线程并启动
    t = threading.Thread(target=do_something, daemon=True)
    t.start()
    # 等待esc键按下
    keyboard.wait('ctrl+c')
    
    def toggle_running(self):
        if self.running:
            # 如果程序正在运行,停止运行
            self.label_orderNum.config(text="生成订单数量为" + str(self.num))
            self.label_runStopNum.config(text="运行结束批号值为" + str(
                self.num + int(self.beginNum.get(1.0, END)) + int(self.targetVol.get(1.0, END))))
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            self.thread.join()
            # 等待线程结束
        else:
            # 如果程序没有运行,启动运行
            self.btn_Algo["text"] = "STOP"
            self.btn_Algo["bg"] = "red"
            self.running = True
            self.thread = threading.Thread(target=self.run_loop)
            #  创建新线程来运行run_loop方法
            self.thread.start()
            # 启动线程

    def run_loop(self):
        try:
            os.remove(algoStart_file)
        except:
            print(algoStart_file + "文件不存在")

        try:
            os.remove(algoStop_file)
        except:
            print(algoStop_file + "文件不存在")

        try:
            os.remove(algoExecStatic_file)
        except:
            print(algoExecStatic_file + "文件不存在")
        try:
            os.remove(assetInfo_file)
        except:
            print(assetInfo_file + "文件不存在")
        try:
            os.remove(compactInfo_file)
        except:
            print(compactInfo_file + "文件不存在")
        try:
            os.remove(crediStockInfo_file)
        except:
            print(crediStockInfo_file + "文件不存在")
        try:
            os.remove(crediTargetStockInfo_file)
        except:
            print(crediTargetStockInfo_file + "文件不存在")
        try:
            os.remove(orderUpdate_file)
        except:
            print(orderUpdate_file + "文件不存在")
        try:
            os.remove(positionInfo_file)
        except:
            print(positionInfo_file + "文件不存在")
        try:
            os.remove(tradeUpdate_file)
        except:
            print(tradeUpdate_file + "文件不存在")
        try:
            os.remove(TradeMaxNo_file)
        except:
            print(TradeMaxNo_file + "文件不存在")
        try:
            os.remove(OrderMaxNo_file)
        except:
            print(OrderMaxNo_file + "文件不存在")

        with open(algoStart_file, "a+", newline='') as file:
            csv_file = csv.writer(file)
            datas = [["updTime", "custAlgoNo", "acctType", "acct", "symbol", "tradeSide",
                      "targetVol", "targetAmt", "algoId", "algoParam"]]
            csv_file.writerows(datas)

        with open(algoStop_file, "a+", newline='') as file:
            csv_file = csv.writer(file)
            datas = [["updTime", "custAlgoNo", "acctType", "acct"]]
            csv_file.writerows(datas)

        beginNum = int(self.beginNum.get(1.0, END))
        endNum = int(self.endNum.get(1.0, END))
        targetVol = int(self.targetVol.get(1.0, END))
        runStopTime = int(self.runStopTime.get(1.0, END))
        algoStopTimeSet = str(self.algoStopTimeSet.get(1.0, END)).replace("\n", "")
        algoStopTime = self.algoStopTime_var.get()
        if algoStopTime == "6":
            print(6666)
        print("algoStopTime", algoStopTime)

        # 搜集勾选的算法
        if self.OQAlgo_var2.get() == 1:
            self.collect_Algo.append("OQ-TWAP")
        if self.OQAlgo_var3.get() == 1:
            self.collect_Algo.append("OQ-VWAP")
        if self.OQAlgo_var4.get() == 1:
            self.collect_Algo.append("OQ-POV")

        if self.XTAlgo_var2.get() == 1:
            self.collect_Algo.append("XT-TWAP")
        if self.XTAlgo_var3.get() == 1:
            self.collect_Algo.append("XT-VWAP")
        if self.XTAlgo_var4.get() == 1:
            self.collect_Algo.append("XT-VP")

        if self.KFAlgo_var2.get() == 1:
            self.collect_Algo.append("KF-POV")
        if self.KFAlgo_var3.get() == 1:
            self.collect_Algo.append("KF-TWAP-CORE")
        if self.KFAlgo_var4.get() == 1:
            self.collect_Algo.append("KF-TWAP-PLUS")
        if self.KFAlgo_var5.get() == 1:
            self.collect_Algo.append("KF-VWAP-CORE")
        if self.KFAlgo_var6.get() == 1:
            self.collect_Algo.append("KF-VWAP-PLUS")

        if self.HXAlgo_var1.get() == 1:
            self.collect_Algo.append("HX_SMART_TWAP")
        if self.HXAlgo_var2.get() == 1:
            self.collect_Algo.append("HX_SMART_VWAP")

        if self.FTAlgo_var1.get() == 1:
            self.collect_Algo.append("FT_WAP")

        if self.QNDAlgo_var1.get() == 1:
            self.collect_Algo.append("QND-TWAP")
        if self.QNDAlgo_var2.get() == 1:
            self.collect_Algo.append("QND-VWAP")

        if self.YRAlgo_var1.get() == 1:
            self.collect_Algo.append("YR-VWAP")

        print("collect_Algo", self.collect_Algo)

        if self.collect_Algo == [] and algoStopTimeSet == "" and self.algoStopTime_var.get() == "6":
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            showinfo(title="友情提示", message="1,请至少选择一个算法\n2,请设置算法结束时间")
            return
        elif self.collect_Algo == []:
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            showinfo(title="友情提示", message="1,请至少选择一个算法")
            return
        elif algoStopTimeSet == "" and self.algoStopTime_var.get() == "6":
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            showinfo(title="友情提示", message="1,请设置算法结束时间")
            return
        elif len(str(runStopTime)) > 6:
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            showinfo(title="友情提示", message="运行结束时间格式填写有误")
            return
        elif len(str(runStopTime)) == 6:
            if int(str(runStopTime)[0:2]) > 23:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                showinfo(title="友情提示", message="运行结束时间格式填写有误")
                return

            elif int(str(runStopTime)[2:4]) > 59:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                showinfo(title="友情提示", message="运行结束时间格式填写有误")
                return

            elif int(str(runStopTime)[4:6]) > 59:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                showinfo(title="友情提示", message="运行结束时间格式填写有误")
                return
        elif len(str(runStopTime)) == 5:
            if int(str(runStopTime)[1:3]) > 59:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                showinfo(title="友情提示", message="运行结束时间格式填写有误")
                return
            elif int(str(runStopTime)[3:5]) > 59:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                showinfo(title="友情提示", message="运行结束时间格式填写有误")
                return

        filename = "Acct.csv"
        current_directory = os.getcwd()  # 获取当前目录
        print("current_directory", current_directory)
        file_path = os.path.join(current_directory, filename)  # 构建文件路径
        print("file_path", file_path)
        if os.path.isfile(file_path):  # 检查文件是否存在
            data = pd.read_csv(Acct_file, encoding="gbk")
            if len(data["acctType"]) == 0:  # 判断文件内容是否为空
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                messagebox.showinfo("提示", "请输入资金账号")
                return
        else:
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            messagebox.showinfo("提示", "请输入资金账号")
            return

        filename = "symbol.csv"
        current_directory = os.getcwd()  # 获取当前目录
        print("current_directory", current_directory)
        file_path = os.path.join(current_directory, filename)  # 构建文件路径
        print("file_path", file_path)
        if os.path.isfile(file_path):  # 检查文件是否存
            data = pd.read_csv(symbol_file, encoding="gbk")
            if len(data["symbol"]) == 0:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                messagebox.showinfo("提示", "请输入股票")
                return
        else:
            self.btn_Algo["text"] = "ALGO"
            self.btn_Algo["bg"] = "orange"
            self.running = False
            messagebox.showinfo("提示", "请输入股票")
            return

        acctType_acct = []  # 获取资金账号
        data_acctType_acct = pd.read_csv(Acct_file, encoding="gbk")
        for i in range(len(data_acctType_acct["acctType"])):
            acctType_acct.append(data_acctType_acct["acctType"][i] + "_" + str(data_acctType_acct["acct"][i]))

        collect_symbol = []  # 获取股票代码
        data_symbol = pd.read_csv(symbol_file, encoding="gbk")
        for i in range(len(data_symbol["symbol"])):
            collect_symbol.append(data_symbol["symbol"][i])

        for i in range(beginNum, endNum, targetVol):
            if not self.running:
                # 检查程序是否需要停止
                break  # 停止循环
            for j in range(targetVol):
                self.num = i + j
                print("self.num", self.num)
                time.sleep(1 / targetVol)

                # print("999",1/targetVol)

                choice_acctType_acct = random.choice(acctType_acct)
                acctType = choice_acctType_acct.split("_")[0]
                acct = choice_acctType_acct.split("_")[1]
                symbol = random.choice(collect_symbol)
                algoStype = random.choice(self.collect_Algo)
                # algoParm = "beginTime="+beginTime+";"+"endTime="+self.algoStopTimeSet+";"
                Parameter = []
                Parameters = []
                Parameter.append("93000")
                Parameter.append(self.num)
                Parameter.append(acctType)
                Parameter.append(acct)
                Parameter.append(symbol)
                Parameter.append("1")
                Parameter.append("200")
                Parameter.append("0")
                Parameter.append(algoStype)
                beginTime = str(datetime.datetime.now().strftime("%H%M%S"))
                if algoStopTime == "6":
                    endTime = algoStopTimeSet
                else:
                    endTime = (datetime.datetime.now() + datetime.timedelta(minutes=int(algoStopTime))).strftime(
                        "%H%M%S")

                if algoStype in ["OQ-TWAP", "OQ-VWAP", "OQ-POV"]:
                    Parameter.append(
                        "beginTime=" + beginTime + ";endTime=" + endTime + ";limitPrice=0;participateRate=0.15;minAmount=0;tradingStyle=2;notBuyOnLLAndSellOnHL=0;custBatchNo=")
                elif algoStype in ["XT-TWAP", "XT-VWAP", "XT-VP"]:
                    Parameter.append(
                        "beginTime=" + beginTime + ";endTime=" + endTime + ";limitPrice=0;PartRate=0.20;MinAmount=0;m_nStopTradeForOwnHiLow=0;custBatchNo=")
                elif algoStype == "KF-POV":
                    Parameter.append(
                        "beginTime=" + beginTime + ";endTime=" + endTime + ";maxpercentageF=0.2;priceF=0;UpLimitF=0.05;DownLimitF=0.05;limitAction=0;afterAction=0;custBatchNo=")
                elif algoStype in ["KF-TWAP-CORE", "KF-TWAP-PLUS", "KF-VWAP-CORE", "KF-VWAP-PLUS"]:
                    Parameter.append(
                        "beginTime=" + beginTime + ";endTime=" + endTime + ";priceF=0;UpLimitF=0.05;DownLimitF=0.05;limitAction=0;afterAction=0;custBatchNo=")
                elif algoStype in ["HX_SMART_TWAP", "HX_SMART_VWAP"]:
                    Parameter.append("HXAlgo")
                elif algoStype == "FT_WAP":
                    Parameter.append("beginTime=" + beginTime + ";endTime=" + endTime)
                elif algoStype in ["QND-TWAP", "QND-VWAP"]:
                    Parameter.append(
                        "beginTime=" + beginTime + ";endTime=" + endTime + ";allowTradeAtLimit=0;allowTradeAfterEnd=0")
                elif algoStype == "YR-VWAP":
                    Parameter.append("beginTime=" + beginTime + ";endTime=" + endTime + ";limitRule=0")
                Parameters.append(Parameter)

                with open(algoStart_file, "a+", newline='') as file:
                    csv_file = csv.writer(file)
                    csv_file.writerows(Parameters)
            print("881", int(datetime.datetime.now().strftime("%H%M%S")), "   ", runStopTime)
            if int(datetime.datetime.now().strftime("%H%M%S")) >= runStopTime or self.num >= endNum:
                self.btn_Algo["text"] = "ALGO"
                self.btn_Algo["bg"] = "orange"
                self.running = False
                messagebox.showinfo("提示", "运行结束时间到了或者到了批号结束值")

                return


if __name__ == '__main__':
    date = str(datetime.datetime.now().strftime("%Y%m%d"))
    algoStart_file = os.getcwd() + "\\" + "algoStart_" + date + ".csv"
    algoStop_file = os.getcwd() + "\\" + "algoStop_" + date + ".csv"
    algoExecStatic_file = os.getcwd() + "\\" + "algoExecStatic_" + ".csv"
    assetInfo_file = os.getcwd() + "\\" + "assetInfo_" + date + ".csv"
    compactInfo_file = os.getcwd() + "\\" + "compactInfo_" + date + ".csv"
    crediStockInfo_file = os.getcwd() + "\\" + "crediStockInfo_" + date + ".csv"
    crediTargetStockInfo_file = os.getcwd() + "/" + "crediTargetStockInfo_" + date + ".csv"
    orderUpdate_file = os.getcwd() + "\\" + "orderUpdate_" + date + ".csv"
    positionInfo_file = os.getcwd() + "\\" + "positionInfo_" + date + ".csv"
    tradeUpdate_file = os.getcwd() + "\\" + "tradeUpdate_" + date + ".csv"
    TradeMaxNo_file = os.getcwd() + "\\" + "TradeMaxNo.txt"
    OrderMaxNo_file = os.getcwd() + "\\" + "OrderMaxNo.txt"

    Acct_file = os.getcwd() + "/" + "Acct" + ".csv"
    symbol_file = os.getcwd() + "/" + "symbol" + ".csv"

    # 初始化窗口
    root = Tk()

    root.title("生成算法单导入文件")
    root.geometry("700x470+350+100")
    app = Application().__int__(master=root)
    root.mainloop()