===================================================================
TDX_交易機(jī)器人(Python程序自動(dòng)化)<2020.12.19開(kāi)發(fā)> Update:2021.1.2
===================================================================
開(kāi)關(guān)
run_on_off = 1
=================================================
app_title='中國(guó)銀河證券海王星V2*'
app_path=r'C:\中國(guó)銀河證券海王星\TdxW.exe'
賬號(hào)/密碼
----------------
id='1025*******8'
password='******'
----------------
工作時(shí)段( 0-不限制;1-限制 )
-----------------------------
time_work = 1
time_start=80500
time_end =150200
下單時(shí)段( 0-不限制鞍陨;1-限制 )
-----------------------------
time_trade = 1
time1= 93000
time2=245700
-----------------------------
下單方式(0-測(cè)試單喉恋;1-任意時(shí)間反番;2-固定時(shí)間失驶;3-尾盤(pán)時(shí)間队询;4-最優(yōu)時(shí)間)
--------------------------------------------------------------------
Trade_mode = 1
--------------------------------------------------------------------
短線交易開(kāi)關(guān)
Short_mode = 1
配置和安裝方法
======================================================================================
特別重要提示:新包安裝后浙滤,請(qǐng)重新進(jìn)入python才起作用伶授。
1.定時(shí)器
pip3 install schedule
d:\python37\python.exe -m pip install --upgrade pip
path d:\python37\scripts
2.Python自動(dòng)化模塊
pip3 install pywinauto
pip3 install pywin32 如果報(bào)錯(cuò)沃呢,采用下述方式:pip3 install pypiwin32
(win32api年栓,win32gui,win32con)
pip3 install pymouse
pip3 install pyUserInput
3.圖像處理
pip3 install PILLOW
圖片處理
pip3 install opencv-python
4.OCR 光學(xué)文字識(shí)別軟件
======================================================================================
pip3 install pytesseract
pip3 install tesseract
下載安裝 Tesseract-OCR 軟件并設(shè)好路徑:
-----------------------------------------------------------------------------------
https://digi.bib.uni-mannheim.de/tesseract/
最新: tesseract-ocr-w64-setup-v5.0.0-alpha.20201127.exe
CMD 中設(shè)置路徑:path C:\Program Files\Tesseract-OCR
路徑修改:python37\Lib\site-packages\pytesseract\pytesseract.py
改為: tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
-----------------------------------------------------------------------------------
tesseract --list-langs 查看語(yǔ)言包
默認(rèn)英文薄霜,中文語(yǔ)言包需要放到 C:\Program Files\Tesseract-OCR\tessdata
tesseract --help-psm 查看psm 參數(shù)設(shè)置方法
參數(shù)設(shè)置:config='-l chi_sim --psm 7 -c tessedit_char_whitelist=0123456789'
======================================================================================
基礎(chǔ)知識(shí)介紹
==========================================================================
數(shù)據(jù)分析: pandas, numpy
文本處理: re
爬蟲(chóng): requests, pyQuery, Selenium, BeautifulSoup, Scrapy, pyspider, cola
網(wǎng)頁(yè)應(yīng)用: Django, flask, grab
辦公自動(dòng)化: 可以編輯excel的xlrd, openpyxl和編輯world的docx
金融: mplfinance,talib
==========================================================================
模塊導(dǎo)入
---------------------------------
導(dǎo)入時(shí)間
import time
import datetime
OS和Win32
import os
import win32gui # Win 圖形界面接口某抓,主要負(fù)責(zé)操作窗口切換以及窗口中元素
import win32api # Win 開(kāi)發(fā)接口模塊,主要負(fù)責(zé)模擬鍵盤(pán)和鼠標(biāo)操作
import win32con # 全面的庫(kù)函數(shù)惰瓜,提供Win32gui和Win32api需要的操作參數(shù)
import win32ui
自動(dòng)化
from pywinauto import application
from pywinauto.keyboard import send_keys
import pywinauto.mouse
鍵盤(pán)鼠標(biāo)
from pymouse import PyMouse
from pykeyboard import PyKeyboard
定義鍵鼠
m = PyMouse()
k = PyKeyboard()
正則函數(shù)
import re
OCR光學(xué)文字識(shí)別
import pytesseract
屏幕抓圖
from PIL import Image,ImageGrab
---------------------------------
時(shí)間函數(shù)
def tm():
time_now = datetime.datetime.now()
hour = time_now.hour
minute = time_now.minute
second = time_now.second
timex=10000hour+100minute+second
# tm_format='%Y-%m-%d %H:%M:%S'
times=time_now.strftime('%H:%M:%S')
return time_now,hour,minute,second,timex,times
時(shí)間差
def d_tm(time_start):
time_end=datetime.datetime.now()
delta_ts=(time_end-time_start).seconds
delta_tm=int((time_end-time_start).seconds/60)
return delta_ts,delta_tm
圖像識(shí)別
def scan_image(left,top,right,bottom,check_code,check_len,method,limit):
z=''
lenz=0
codez='0'
# 抓取屏幕圖片
img = ImageGrab.grab(bbox=(left,top,right,bottom))
# 灰度轉(zhuǎn)換
if check_code=='gray':
img = img.convert('L')
# 二值轉(zhuǎn)換
if check_code=='binary':
img = img.convert('L')
threshold = 200
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
img = img.point(table, '1')
# 測(cè)試圖片
if method=='save':
img.save('test.png')
# 識(shí)別文本
if limit=='num':
# 僅限數(shù)字
z = pytesseract.image_to_string(img,config='--psm 7 -c tessedit_char_whitelist=0123456789').replace(' ','')
elif limit=='eng':
# 僅限字母和數(shù)字
z = pytesseract.image_to_string(img,config='--psm 7 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz').replace(' ','')
elif limit=='chi':
# 中文語(yǔ)言包
z = pytesseract.image_to_string(img,config='-l chi_sim --psm 7').replace(' ','')
else:
# 無(wú)限制
z = pytesseract.image_to_string(img,config='--psm 7').replace(' ','')
# 刪除最后兩位特殊字符
z = z[:-2]
# 生成掃描文本的長(zhǎng)度和末位字符
if len(z)>0:
lenz=len(z)
codez=z[-1]
# 校驗(yàn)(未通過(guò)長(zhǎng)度或末位字符校驗(yàn)否副,則初始化為'0')
if method=='check' and (check_len>0 or check_code!=''):
if check_len>0 and lenz==check_len and check_code=='':
pass
elif check_len==0 and check_code!='' and codez==check_code:
pass
elif check_len>0 and lenz==check_len and check_code!='' and codez==check_code:
pass
else:
j=1
z=''
if check_len>0:
j=check_len
elif lenz>0:
j=lenz
z=z.zfill(j)
# 返回值
return z
信標(biāo)機(jī)掃描
def Scanner(left,top,right,bottom):
z = scan_image(left,top,right,bottom,'9',15,'check','num')
if z[14]!='9':
z=('掃','描','遮','蓋','','','0','','0','0','0','','0','0','0')
stk_code=z[0]+z[1]+z[2]+z[3]+z[4]+z[5]
tradel=z[6]
tradeln=z[7]+z[8]+z[9]
trades=z[10]
tradesn=z[11]+z[12]+z[13]
check=z[14]
return (stk_code,tradel,tradeln,trades,tradesn,check)
定義窗口檢測(cè)函數(shù)
def find_win(title):
ws=0
for i in range(10):
try:
h=pywinauto.findwindows.find_window(title_re=title,found_index=0)
ws=1
break
except:
ws=0
return ws
控件函數(shù)
def find_ocr(ocr_title,ocr_id,ocr_type,handle,index,method,note):
lxy=(0,0,0,0)
app_s1=0
ocr_s1=0
ocr_win=0
ocr_state=''
error_code='ok'
# 檢測(cè)app連接
try:
h1=pywinauto.findwindows.find_window(title_re=app_title,found_index=0)
app_s1=1
except:
error_code='Error(app)'
# 檢測(cè)ocr_win連接
if app_s1==1:
try:
app=application.Application(backend='uia').connect(handle=h1)
app.window(handle=h1).set_focus()
if method=='printall':
app.window(handle=h1).print_control_identifiers()
ocr_win=ocr_win=app.window(handle=h1).child_window(title_re=ocr_title,auto_id=ocr_id,control_type=ocr_type,handle=handle,found_index=index)
if ocr_win.exists()==True:
lstr=str(ocr_win.rectangle())
lstr_xy=re.findall("\d+",lstr)
lxy=(int(lstr_xy[0]),int(lstr_xy[1]),int(lstr_xy[2]),int(lstr_xy[3]))
ocr_s1=1
except:
error_code='Error(ocr)'
# 響應(yīng)事件
if app_s1==1 and ocr_s1==1:
try:
if len(str(method))>0:
if method=='click':
if note=='auto':
ocr_win.click()
else:
ocr_win.click_input()
elif method=='focus':
ocr_win.set_focus()
elif method=='print':
ocr_win.print_control_identifiers()
elif method=='press':
ocr_win.click_input()
k.press_keys(str(note))
elif method=='set':
ocr_win.set_text(str(note))
elif method=='send':
ocr_win.click_input()
send_keys(str(note))
elif method=='move':
m.move(int((lxy[0]+lxy[2])/2),int((lxy[1]+lxy[3])/2))
elif method=='enabled':
ocr_state=ocr_win.is_enabled()
elif method=='get':
ocr_state=ocr_win.get_properties()
elif method=='texts':
ocr_state=ocr_win.texts()
except:
error_code='Method Error'
# 返回結(jié)果
return app_s1,ocr_s1,ocr_win,ocr_state,error_code,lxy
控件(隱藏/顯示)函數(shù)
def hide_ocr(mode,handle,title):
# 句柄優(yōu)先,無(wú)句柄再找標(biāo)題
if handle!=None:
handle=handle
else:
handle=win32gui.FindWindow(None,title)
# 進(jìn)行隱藏/顯示操作
if mode==0:
win32gui.PostMessage(handle,win32con.WM_CLOSE,0,0)
win32gui.ShowWindow(handle,win32con.WM_DESTROY)
elif mode==1:
win32gui.ShowWindow(handle,win32con.SW_SHOWNORMAL)
else:
return handle
向通達(dá)信廣播股票代碼
def BroadCast(Message,Code):
if str(Message)=='Stock':
if str(Code)[0]=='6':
codex='7'+str(Code)
else:
codex='6'+str(Code)
else:
codex=int(Code)
UWM_STOCK = win32api.RegisterWindowMessage('Stock')
win32gui.PostMessage(win32con.HWND_BROADCAST,UWM_STOCK,int(codex),0)
關(guān)閉彈窗('今日不再提示''無(wú)此操作方式')
def close_note():
# 登錄時(shí)可能的彈窗
s1=find_ocr('今日不再提示','508','CheckBox',None,0,'click','auto')
if s1[1]==1:
find_ocr('關(guān)閉','509','Button',None,0,'click','auto')
# 盤(pán)中可能的彈窗
s2=find_ocr('今日不再提示','1914','CheckBox',None,0,'click','auto')
if s2[1]==1:
find_ocr('關(guān)閉','2','Button',None,0,'click','auto')
# 盤(pán)中可能的彈窗
s3=('','1474','Edit',None,0,'','')
if s3[1]==1:
find_ocr('關(guān)閉','2','Button',None,0,'click','auto')
鎖定交易
def lock_trade():
# 如果處于鎖定界面
find_ocr('取消','443','Button',None,0,'click','auto')
# 如果處于交易界面
find_ocr('鎖定','','',None,0,'click','auto')
退出app
def app_exit():
find_ocr('','9601','Pane',None,0,'click','manul')
find_ocr('退出','961','Button',None,0,'click','auto')
# 如果提示下載盤(pán)后日線數(shù)據(jù)
note=find_ocr('提示','','Pane',None,0,'','auto')
if note[1]==1:
find_ocr('確定','1','Button',None,0,'click','auto')
time.sleep(1)
定義登錄函數(shù)
==============================================================
def select(trade_type):
z=(0,0,0)
if trade_type==1:
z=find_ocr('普通交易','2264','RadioButton',None,0,'click','auto')
elif trade_type==2:
z=find_ocr('信用交易','2265','RadioButton',None,0,'click','auto')
return z
def login(id,password,login_mode,trade_type):
# (1) 行情
if login_mode==2:
login2=find_ocr('','365','Pane',None,0,'focus','manul')
# 按鈕存在崎坊,點(diǎn)擊進(jìn)入
if login2[1]==1:
find_ocr('','365','Pane',None,0,'click','manul')
# 按鈕不存在
elif login2[1]==0:
# 如果 App 已經(jīng)啟動(dòng)备禀,不用再登錄
if login2[0]==1:
return
else:
app=application.Application(backend='uia').start(app_path)
app.top_window().set_focus()
find_ocr('','365','Pane',None,0,'click','manul')
return
# (2) 獨(dú)立交易
if login_mode==3:
login3=find_ocr('','366','Pane',None,0,'focus','manul')
# 按鈕存在,點(diǎn)擊準(zhǔn)備登錄
if login3[1]==1:
find_ocr('','366','Pane',None,0,'click','manul')
# 按鈕不存在
elif login3[1]==0:
# 如果 App 已經(jīng)啟動(dòng),先退出再登錄
if login3[0]==1:
app_exit()
app=application.Application(backend='uia').start(app_path)
app.top_window().set_focus()
find_ocr('','366','Pane',None,0,'click','manul')
select(trade_type)
# (3) 行情 + 交易
if login_mode==1:
# 檢驗(yàn)“登錄模式”和“交易類型”控件
login1=find_ocr('','364','Pane',None,0,'focus','manul')
# 如果App未啟動(dòng)曲尸,先啟動(dòng)
if login1[0]==0:
app=application.Application(backend='uia').start(app_path)
app.top_window().set_focus()
# 點(diǎn)擊登錄頁(yè)面
find_ocr('','364','Pane',None,0,'click','manul')
# 測(cè)試模式選擇按鈕
seltype=select(trade_type)
# 如果 App 已啟動(dòng)赋续,但不存在登錄界面,說(shuō)明是熱啟動(dòng)
if seltype[0]==1 and seltype[1]==0:
for i in range(5):
# 如果交易已登錄另患,且未鎖定纽乱,無(wú)需登錄,直接跳出
lock_ocr=find_ocr('鎖定','','',None,0,'','auto')
if lock_ocr[1]==1:
return
# 如果交易鎖定柴淘,直接解鎖
find_ocr('交易密碼','1130','Text',None,0,'focus','manul')
unlock_ocr=find_ocr('交易密碼','1130','Text',None,0,'press',str(password))
if unlock_ocr[1]==1:
find_ocr('確定','442','Button',None,0,'click','auto')
return
# 如果交易隱藏迫淹,調(diào)出界面
if lock_ocr[1]==0 and unlock_ocr[1]==0:
# 隱藏彈窗
hide_ocr(0,None,'即時(shí)播報(bào)')
# 激活 K 線界面秘通,調(diào)出(交易/登錄/解鎖)界面
find_ocr('','59648','Pane',None,0,'send','.8{VK_RETURN}')
# 如果調(diào)出的是登錄界面为严,則跳出循環(huán)準(zhǔn)備登錄
seltype=select(trade_type)
if seltype[1]==1:
break
# 賬號(hào)登錄
#------------------------------
# 先輸入密碼
find_ocr('','234','Pane',None,0,'press',str(password))
# 后輸入客戶號(hào)
find_ocr('','1001','Edit',None,0,'set',str(id))
# 驗(yàn)證碼識(shí)別
#------------------------------
# 安全框坐標(biāo)
safe_win=find_ocr('主站測(cè)速','1896','ComboBox',None,0,'','auto')
# 驗(yàn)證碼坐標(biāo)
check_win=find_ocr('','235','Pane',None,0,'','manul')
x1=int(check_win[5][2]+1.5(check_win[5][0]-safe_win[5][2]))
y1=check_win[5][1]
x2=int(check_win[5][2]+0.38(check_win[5][2]-safe_win[5][0]))
y2=check_win[5][3]
# 嘗試登錄(不超過(guò) 20 次嘗試...)
for j in range(1,20):
#-------------------------------------------------------------------
# 間隔時(shí)間,控制控件檢測(cè)速度
time.sleep(0.1)
# 檢驗(yàn)驗(yàn)證碼輸入框是否可用
check_ocr=find_ocr('','235','Pane',None,0,'enabled','auto')
# 如果可用肺稀,輸入驗(yàn)證碼登錄
if check_ocr[3]==True and check_ocr[4]=='ok':
# 提取圖片驗(yàn)證碼
z=scan_image(x1,y1,x2,y2,'',4,'check','num')
# 輸入驗(yàn)證碼
check_ocr=find_ocr('','235','Pane',None,0,'press',str(z))
# 點(diǎn)擊登錄
find_ocr('','1','Pane',None,0,'click','manul')
time.sleep(0.1)
else:
break
#-------------------------------------------------------------------
# 關(guān)閉彈窗
close_note()
快速交易
==============================================================
def fast_trade(order,sk_code,num,ratio,on_off):
# 登錄交易
login(id,password,1,1)
# 循環(huán)至快速交易界面
for j in range(5):
# 隱藏彈窗
hide_ocr(0,None,'即時(shí)播報(bào)')
# 向通達(dá)信廣播股票代碼消息
BroadCast('Stock',sk_code)
# 快速買(mǎi)入
if order==1 or order==2 or order==3 or order==4:
# 激活 K 線界面第股,調(diào)出(閃電買(mǎi)入)界面
find_ocr('','59648','Pane',None,0,'send','21{VK_RETURN}')
time.sleep(0.3)
# 檢測(cè)買(mǎi)入界面控件
# ----------------------------------------------------------------------
if ratio==0:
fast_win=find_ocr('買(mǎi)入數(shù)量','12007','Edit',None,0,'set',str(num))
elif ratio==1:
fast_win=find_ocr('全部','1495','Button',None,0,'click','auto')
elif ratio==2:
fast_win=find_ocr('1/2','8909','RadioButton',None,0,'click','auto')
elif ratio==3:
fast_win=find_ocr('1/3','8910','RadioButton',None,0,'click','auto')
elif ratio==4:
fast_win=find_ocr('1/4','8911','RadioButton',None,0,'click','auto')
elif ratio==5:
fast_win=find_ocr('1/5','8913','RadioButton',None,0,'click','auto')
# ----------------------------------------------------------------------
# 快速賣出
elif order==5 or order==6 or order==7 or order==8:
# 激活 K 線界面楚里,調(diào)出(閃電賣出)界面
find_ocr('','59648','Pane',None,0,'send','23{VK_RETURN}')
time.sleep(0.3)
# 檢測(cè)賣出界面控件
# ----------------------------------------------------------------------
if ratio==0:
fast_win=find_ocr('賣出數(shù)量','12007','Edit',None,0,'set',str(num))
elif ratio==1:
fast_win=find_ocr('全部','1495','Button',None,0,'click','auto')
elif ratio==2:
fast_win=find_ocr('1/2','8903','RadioButton',None,0,'click','auto')
elif ratio==3:
fast_win=find_ocr('1/3','8905','RadioButton',None,0,'click','auto')
elif ratio==4:
fast_win=find_ocr('1/4','8907','RadioButton',None,0,'click','auto')
elif ratio==5:
fast_win=find_ocr('1/5','8913','RadioButton',None,0,'click','auto')
# ----------------------------------------------------------------------
# 檢測(cè)到控件動(dòng)作,跳出
if fast_win[1]==1:
break
# ------------------------
# 買(mǎi)單確認(rèn)
if order==1 or order==2 or order==3 or order==4:
#-----------------------------------------------------------
find_ocr('買(mǎi) 入','1','Button',None,0,'click','auto')
# 數(shù)量有效性
#------------------------------------------------------------
note=find_ocr('提示','','Pane',None,0,'','auto')
if note[1]==1:
find_ocr('確認(rèn)','7015','Button',None,0,'click','auto')
# 交易界面取消
find_ocr('取 消','2','Button',None,0,'click','auto')
#------------------------------------------------------------
# 交易開(kāi)關(guān)
if on_off=='on':
# 買(mǎi)入確認(rèn)
find_ocr('買(mǎi)入確認(rèn)','7015','Button',None,0,'click','auto')
# 提示(成交結(jié)果)
note=find_ocr('提示','','Pane',None,0,'','auto')
if note[1]==1:
find_ocr('確認(rèn)','7015','Button',None,0,'click','auto')
elif on_off=='off':
off=find_ocr('取消','7016','Button',None,0,'click','auto')
if off[1]==1:
# 交易界面取消
find_ocr('取 消','2','Button',None,0,'click','auto')
#-----------------------------------------------------------
# 賣單確認(rèn)
elif order==5 or order==6 or order==7 or order==8:
#-----------------------------------------------------------
find_ocr('賣 出','1','Button',None,0,'click','auto')
# 數(shù)量有效性
#-----------------------------------------------------------
note=find_ocr('提示','','Pane',None,0,'','auto')
if note[1]==1:
find_ocr('確認(rèn)','7015','Button',None,0,'click','auto')
# 交易界面取消
find_ocr('取 消','2','Button',None,0,'click','auto')
#-----------------------------------------------------------
# 交易開(kāi)關(guān)
if on_off=='on':
# 賣出確認(rèn)
find_ocr('賣出確認(rèn)','7015','Button',None,0,'click','auto')
# 提示(成交結(jié)果)
note=find_ocr('提示','','Pane',None,0,'','auto')
if note[1]==1:
find_ocr('確認(rèn)','7015','Button',None,0,'click','auto')
elif on_off=='off':
off=find_ocr('取消','7016','Button',None,0,'click','auto')
if off[1]==1:
# 交易界面取消
find_ocr('取 消','2','Button',None,0,'click','auto')
#-----------------------------------------------------------
#
# 查看持倉(cāng)
find_ocr('持倉(cāng)','','Button',None,0,'click','auto')
# 鎖定交易
lock_trade()
歡迎函數(shù)
def welcome():
print('')
print('')
print(' # -----------------------------------------------------------------')
print('')
print(' TDX_交易機(jī)器人( Ver.2021.1.1 ) 啟動(dòng)蒸眠!')
print('')
print(' TDX_機(jī)器人實(shí)盤(pán)侦厚,將在每天: ',time_end,' 退出扯夭!')
print('')
print(' 為方便觀測(cè)亏推,本窗口將保持開(kāi)啟斥赋!關(guān)閉本窗口將退出機(jī)器人看盤(pán)旭蠕! ')
print('')
print(' # -----------------------------------------------------------------')
print('')
print(' 交易時(shí)點(diǎn)( 09:50, 11:00, 13:15, 14:50 ),短線(09:30-15:00) ')
print('')
print('')
print(' 啟動(dòng)中 ... ')
print('')
print('')
print('')
print('')
分單計(jì)算器
def calc(total,r1,r2,r3,r4):
x1=totalr1
x2=(total-x1)r2
x3=(total-x1-x2)r3
x4=(total-x1-x2-x3)r4
x=x1+x2+x3+x4
return int(x),int(x1),int(x2),int(x3),int(x4)
====================
主程序
====================
if run_on_off==1:
welcome()
login(id,password,1,1)
time.sleep(3)
--------------
--------------
wx_init=0
tm_init=tm()[0]
--------------
t1=0
t2=0
t3=0
t4=0
buycount=0
selcount=0
--------------
while (run_on_off==1):
# 接入 app
# -----------------------------------
wx=find_win(app_title)
if wx==1:
tm_start=tm_init
# 首次進(jìn)入第 9 秒自檢枯跑,此后每隔 7 分鐘執(zhí)行一次自檢
if d_tm(tm_start)[1]>=7 or (wx_init==0 and d_tm(tm_start)[0])>=9:
print('')
print(' 狀態(tài)自檢......')
print('-------------------------------------------')
close_note()
lock_trade()
print('-------------------------------------------')
print(' 自檢結(jié)束......')
print('')
wx_init=1
tm_init=tm()[0]
else:
time.sleep(3)
login(id,password,2,1)
# 間隔時(shí)間
time.sleep(3)
# 掃描區(qū)
# ---------------------------------------------
imgxy1=(12,112,142,142) # 1920x1080,100% 縮放
imgxy2=(20,205,260,255) # 3860x2160,175% 縮放
# ---------------------------------------------
# 自動(dòng)選擇
for i in range(2):
imgxy=locals()['imgxy'+str(i+1)]
# --------------
# 掃描信號(hào)
z=Scanner(imgxy[0],imgxy[1],imgxy[2],imgxy[3])
if z[5]=='9':
break
# 編碼解析
# ---------------------------------------------------------------- 初始化
stk_code='000063'
tradel=0
tradel_num=0
trades=0
trades_num=0
# ---------------------------------------------------------------- 解 碼
check=z[5] # 校驗(yàn)碼 ('9'-正常黄虱,'0'-異常)
if check=='9':
stk_code=z[0] # 股票代碼
tradel=int(z[1]) # 長(zhǎng)線交易信號(hào) ( [1—4] 買(mǎi)入稚矿,[5—8] 賣出 )
tradel_num=int(z[2])*100 # 長(zhǎng)線交易數(shù)量 ( 1-代表100股,最大999*100股 )
trades=int(z[3]) # 短線交易信號(hào) ( [1—4] 買(mǎi)入捻浦,[5—8] 賣出 )
trades_num=int(z[4])*100 # 短線交易數(shù)量 ( 1-代表100股晤揣,最大999*100股 )
# --------------------------------------------------------------------------
# 記錄交易時(shí)間
# --------------------
zm = tm()
hour = zm[1]
minute = zm[2]
second = zm[3]
timex = zm[4]
time_str = zm[5]
# --------------------
# 下單策略
# --------------------------------------------------------參數(shù)區(qū)
Place_Order='no'
long_buy=(tradel==1 or tradel==2 or tradel==3 or tradel==4)
long_sel=(tradel==5 or tradel==6 or tradel==7 or tradel==8)
long_Trade=(long_buy or long_sel)
short_buy=(trades==1 or trades==2 or trades==3 or trades==4)
short_sel=(trades==5 or trades==6 or trades==7 or trades==8)
short_Trade=(short_buy or short_sel)
Time1=(hour== 9 and minute>=50 and minute<=60)
Time2=(hour==11 and minute>= 0 and minute<=10)
Time3=(hour==13 and minute>=15 and minute<=25)
Time4=(hour==14 and minute>=50 and minute<=60)
Trade_time=(timex>=time1 and timex<=time2) or time_trade==0
# ---------------------------------------------------------策略區(qū)
orderx=(0,'000063',0,0,'off')
# ---------------------------------------------------------
# 長(zhǎng)線信號(hào)
# --------
# 測(cè)試下單
if Trade_mode==0 and long_Trade==True and t1==0:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,0,'off')
t1=1
# 盤(pán)中下單
if Trade_mode==1 and Trade_time==True and long_Trade==True and t2==0:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,1,'on')
t2=1
# 分批下單
if Trade_mode==2 and Trade_time==True and long_Trade==True and (t1==0 or t2==0 or t3==0 or t4==0):
# ---------------------------------------------------------------
if Time1==True and t1==0:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,4,'on')
t1=1
if Time2==True and t2==0:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,3,'on')
t2=1
if Time3==True and t3==0:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,2,'on')
t3=1
if Time4==True and t4==0:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,1,'on')
t4=1
# ---------------------------------------------------------------
# 最優(yōu)下單
if Trade_mode==3 and Trade_time==True and long_Trade==True and t3==0:
# 出現(xiàn)最優(yōu)信號(hào),立即下單
if (long_buy==True and short_buy==True) or (long_sel==True and short_sel==True):
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,1,'on')
t3=1
# 若無(wú)最優(yōu)信號(hào)朱灿,尾盤(pán)下單
elif Time4==True:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,1,'on')
t3=1
# 尾盤(pán)下單
if Trade_mode==4 and Trade_time==True and long_Trade==True and t4==0 and Time4==True:
Place_Order='yes'
orderx=(tradel,stk_code,tradel_num,1,'on')
t4=1
# 短線信號(hào)
# ----------------------------------------------------------------------------------
# 盤(pán)中下單
if Short_mode==1 and Trade_time==True and short_buy==True and buycount==0:
Place_Order='yes'
if Trade_mode==0:
orderx=(trades,stk_code,tradel_num,4,'off')
else:
orderx=(trades,stk_code,tradel_num,4,'on')
buycount=1
if Short_mode==1 and Trade_time==True and short_sel==True and selcount==0:
Place_Order='yes'
if Trade_mode==0:
orderx=(trades,stk_code,tradel_num,4,'off')
else:
orderx=(trades,stk_code,tradel_num,4,'on')
selcount=1
# ----------------------------------------------------------------------------------
# 訂單信息
# ----------------------------------------------------------------------
if Place_Order=='yes' and long_Trade == True and long_buy == True:
print(z,'買(mǎi)入',(t1,t2,t3,t4),(buycount,selcount),'時(shí)間:',time_str)
elif Place_Order=='yes' and long_Trade == True and long_sel == True:
print(z,'賣出',(t1,t2,t3,t4),(buycount,selcount),'時(shí)間:',time_str)
elif check!='9':
print(z,'異常',(t1,t2,t3,t4),(buycount,selcount),'時(shí)間:',time_str)
else:
print(z,'wait',(t1,t2,t3,t4),(buycount,selcount),'時(shí)間:',time_str)
# -----------------------------------------------------------------------
# 下單交易
if Place_Order=='yes':
print('')
print(' 準(zhǔn)備交易......')
print('-------------------------------------------')
fast_trade(orderx[0],orderx[1],orderx[2],orderx[3],orderx[4])
print(' 已經(jīng)下單:',orderx)
print('-------------------------------------------')
print(' 交易結(jié)束......')
print('')
# 定時(shí)退出
# ---------------------------------------------------------------------------
if (timex>=time_start and timex<time_end) or time_work==0:
pass
else:
print('')
print('')
print(' # -----------------------------------------------------------------')
print('')
print(' TDX_機(jī)器人已經(jīng)下班昧识!')
print('')
print(' TDX_機(jī)器人定時(shí)器可能仍在運(yùn)行中!')
print('')
print(' 如果想明天 ',time_start,' 繼續(xù)盗扒,請(qǐng)保持本窗口,不要關(guān)閉跪楞! ')
print('')
print(' # -----------------------------------------------------------------')
print('')
print('')
app_exit()
break