def _showloop(self): while cv2.waitKey(10) not in [Keycode.ESCAPE, Keycode.Q, Keycode.q]: image = self.capture.read() image = image.transpose(Image.FLIP_LEFT_RIGHT) image = Util.resize_image(image, self.size) array = np.asarray(image) array = Util.mount_roi(array, self.roi, color=(74, 20, 140), thickness=2) crop = _crop_array(array, self.roi) # process image for any gestures if self.verbose: segments, event = grdetect(crop, verbose=self.verbose) self.image = Image.fromarray(segments) self.event = event else: event = grdetect(crop, verbose=self.verbose) #self.image = Image.fromarray(segments) self.event = event #self.image = Image.fromarray(segments) #self.event = event cv2.imshow(PyGR.TITLE, array) cv2.destroyWindow(PyGR.TITLE)
def notifyTrade(security): currentTimeString = util.getYMDHMS() duo = str(int(dao.readDuoPosition(security=security))) kon = str(int(dao.readKongPosition(security=security))) max = str(int(dao.readMaxPosition(security=security))) a = '<p>duo: <strong>' + duo + '</strong></p><p>kon: <strong>' + kon + '</strong></p><p>max: <strong>' + max + '</strong></p>' sendEmail(subject='[' + str(currentTimeString) + '] 触发交易动作_' + security, content='' + a)
def prepare(): #securities securities = [ item['code'] for item in dao.select( "select distinct code from t_security_concept", ()) ] me.setdefault('securities', securities) #code_items_rel code_items_rel = {} starttime = util.preOpenDate(util.getLastestOpenDate(), Prepare_TimeLen) total = dao.select( 'select count(0) count from t_security_daily where date>=%s order by date desc', (starttime))[0]['count'] fromindex = 0 pagesize = 100 count = 0 while True: print("Range: " + str(fromindex) + "->" + str(fromindex + pagesize)) tem_codes = me['securities'][fromindex:(fromindex + pagesize)] items = dao.select( 'select code, date, pre_close, high, low, close, open from t_security_daily where code in %s and date>=%s order by date desc', (tem_codes, starttime)) for item in items: code = item['code'] date = item['date'] if code not in code_items_rel.keys(): code_items_rel.setdefault(code, [item]) else: code_items_rel[code].append(item) count = count + 1 log.log('Code: ' + code + " Date: " + date) if tem_codes.__len__() != pagesize or count >= total: break fromindex = fromindex + pagesize me.setdefault('code_items_rel', code_items_rel) #code_lastestClose_rel code_lastestItem_rel = {} items = dao.select( 'select code, date, pre_close, high, low, close, open from t_security_daily where date in (select max(date) max from t_security_daily) order by date desc', ()) for item in items: code = item['code'] code_lastestItem_rel.setdefault(code, item) me.setdefault('code_lastestItem_rel', code_lastestItem_rel)
def _get_contours(array): major = Util.get_opencv_version()[0] if major == 3: _, contours, _ = cv2.findContours(array, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) else: _, contours = cv2.findContours(array, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) return contours
def _get_roi(size, ratio=0.42, position='tl'): ''' 根据缩放比计算指定的举行区域的坐标 Parameters :param size: 图像大小 :param ratio: 缩放比 :param position: 缩放方式 ''' width, height = Util.round_int(size[0] * ratio), Util.round_int(size[1] * ratio) if position == 'tl': x, y = 0, 0 elif position == 'tr': x, y = size[0] - width, 0 elif position == 'bl': x, y = 0, size[1] - height elif position == 'br': x, y = size[0] - width, size[1] - height return (x, y, width, height)
def listen(): denyCodes = [] code_items_rel = me['code_items_rel'] code_preCloseDistance_rel = me['code_preCloseDistance_rel'] candidates = me['candidates'] codes = [item[0] for item in candidates] while True: if util.getHMS() > '15:00:00': break ret = util.getRealTime_Prices(codes) code_price_rel = ret['code_price_rel'] code_rate_rel = ret['code_rate_rel'] for code in code_price_rel.keys(): if code not in code_rate_rel.keys( ) or code_rate_rel[code] > Listen_CurrentLimitRate: continue if code in denyCodes: continue nowDistance = 0 for item in code_items_rel[code]: close = float(item['close']) if code_price_rel[code] >= close: nowDistance = nowDistance + 1 else: break distance = nowDistance - code_preCloseDistance_rel[code] #print(distance) # 发现符合标的,发送通知给我审核 if distance > Filter_High_Distance: try: requests.get( 'http://95.163.200.245:64210/smtpclient/zhuizhang_allow_security_buy/' + code + '/[email protected]') except: time.sleep(5) log.log("Send: " + code + " Distance: " + str(distance)) denyCodes.append(code) time.sleep(10)
def _get_tip_position(array, contour, verbose=False): approx_contour = cv2.approxPolyDP(contour, 0.08 * cv2.arcLength(contour, True), True) convex_points = cv2.convexHull(approx_contour, returnPoints=True) cx, cy = 999, 999 for point in convex_points: cur_cx, cur_cy = point[0][0], point[0][1] if verbose: cv2.circle(array, (cur_cx, cur_cy), 4, _COLOR_GREEN, 4) if (cur_cy < cy): cx, cy = cur_cx, cur_cy (screen_x, screen_y) = pyautogui.size() height, width, _ = array.shape x = Util.round_int((float(cx)) / (width - 0) * (screen_x + 1)) y = Util.round_int((float(cy)) / (height - 0) * (screen_y + 1)) return (array, (x, y))
def init(): #(1) 更新t_position,没有就插入 dao.updateAllPosition(max, jqdata_security) #(2) 更新CTA_setting.json with open('CTA_setting.json', 'w') as json_file: json_file.write( json.dumps([{ "name": strategy, "className": strategy, "vtSymbol": util.get_CTA_setting_dominant_future( jqSecurity=jqdata_security) }])) print "################# My t_position and CTA_setting.json REFRESH! ######################"
def runParentProcess(): """父进程运行函数""" # 创建日志引擎 le = LogEngine() le.setLogLevel(le.LEVEL_INFO) le.addConsoleHandler() le.info(u'启动CTA策略守护父进程') DAY_START = time(8, 45) # 日盘启动和停止时间 DAY_END = time(15, 30) NIGHT_START = time(20, 45) # 夜盘启动和停止时间 NIGHT_END = time(2, 45) p = None # 子进程句柄 while True: currentTime = datetime.now().time() recording = False # 判断当前处于的时间段 if ((currentTime >= DAY_START and currentTime <= DAY_END) or (currentTime >= NIGHT_START) or (currentTime <= NIGHT_END)): recording = True # 记录时间则需要启动子进程 if recording and p is None: if util.isOpenFromJqdata() is False: sleep(3600) continue le.info(u'启动子进程') p = multiprocessing.Process(target=runChildProcess) p.start() le.info(u'子进程启动成功') # 非记录时间则退出子进程 if not recording and p is not None: le.info(u'关闭子进程') p.terminate() p.join() p = None le.info(u'子进程关闭成功') sleep(5)
def init(): #(1) 更新t_position,没有就插入 dao.updateAllPosition(duo=duo, kon=kon, max=max, security=jqdata_security) #(2) 更新CTA_setting.json vtSymbol = util.get_CTA_setting_dominant_future(jqSecurity=jqdata_security) #(3)riskcontrol重设 controlRisk = ControlRisk(security=jqdata_security, ctaEngine=None) controlRisk.releaseAll() controlRisk.setOpenKonPrice(price=init_realOpenKonPrice) controlRisk.setOpenDuoPrice(price=init_realOpenDuoPrice) if init_realOpenDuoPrice is not None or init_realOpenKonPrice is not None: controlRisk.activeLocking() with open('CTA_setting.json', 'w') as json_file: json_file.write( json.dumps([{ "name": strategy, "className": strategy, "vtSymbol": vtSymbol }])) print "################# My t_position and CTA_setting.json REFRESH! ######################"
def start(startTime=None, jqSecurity=None, frequency=None, enableBuy=None, enableShort=None): security = jqSecurity #'FG9999.XZCE' 'RB9999.XSGE' 'JM9999.XDCE' status = Status() frequency = frequency strategyBase = MutilEMaStrategyBase(security=security, status=status, ctaTemplate=None, frequency=frequency, jqDataAccount='13268108673', jqDataPassword='******', enableTrade=False, enableBuy=enableBuy, enableShort=enableShort) times = util.getTimeSerial(startTime, count=1000 * 800, periodSec=12) for t in times: if strategyBase.startJudgeAndRefreshStatus(t): strategyBase.trade(None)
requests.get( 'http://95.163.200.245:64210/smtpclient/zhuizhang_allow_security_buy/' + code + '/[email protected]') except: time.sleep(5) log.log("Send: " + code + " Distance: " + str(distance)) denyCodes.append(code) time.sleep(10) log.log("Start Mode_ZhuiZhang") prepareComplete = False filterComplete = False while True: today = util.getYMD() now = util.getHMS() if prepareComplete is False and (util.isOpen(today) and now > '09:00:00'): log.log('start prepare...') prepare() prepareComplete = True if filterComplete is False and (util.isOpen(today) and now > '09:00:00'): log.log('start filter...') filter() filterComplete = True if util.isOpen(today) and '09:30:00' < now < '15:00:00': log.log('start listen...') listen() me = {} prepareComplete = False filterComplete = False
def notifyVolumeUnusual(security): currentTimeString = util.getYMDHMS() a = '<a href="http://107.182.31.161:5288/">查看行情</a>' sendEmail(subject='[' + str(currentTimeString) + '] 瞬间成交量大增_' + security, content='' + a)
close_rate = round((close - pre_close) / pre_close * 100, 2) open_rate = round((open - pre_close) / pre_close * 100, 2) high_rate = round((high - pre_close) / pre_close * 100, 2) if open_rate > 5: continue if high_rate >= 9.89: highIsZhangting_count = highIsZhangting_count + 1 if close_rate >= 9.89: closeIsZhangting_count = closeIsZhangting_count + 1 _log("Success Code: " + code) if high_rate >= 9.89 and close_rate < 9.89: _log("Fail Code: " + code) if highIsZhangting_count == 0: _log("tradingDate: " + tradingDate + " sr: 0.00") else: _log("tradingDate: " + tradingDate + " sr: " + str(round(closeIsZhangting_count / highIsZhangting_count * 100, 2))) tradingDate = '2018-08-17' while True: _log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Start Testing: " + tradingDate) prepare(tradingDate) testZhangtingSuccessRate(tradingDate) tradingDate = util.preOpenDate(tradingDate, 1) me = {}
def controlOnTick(self, tick): if self.realOpenDuoPrice is not None and self.realOpenKonPrice is not None: smtp.notifyError('realOpenDuoPrice和realOpenKonPrice都不为空,将中止进程') exit() # 监听区域!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!########################################## # 持有多仓风控计算实时盈亏 rate = None if self.realOpenKonPrice is not None: openPrice = self.realOpenKonPrice rate = round((openPrice - tick.lastPrice) / openPrice, 8) * 100 print '[' + str( util.getYMDHMS()) + '] RiskControl realOpenKonPrice: ' + str( self.realOpenDuoPrice) + ' rate: ' + str(rate) if rate < RiskControlRate: self.lockActionToken = True # 发出放狗指令 if self.locking is True and rate > -RiskControlRate: self.unlockActionToken = True # 发出放狗指令 # 持有空仓风控计算实时盈亏 elif self.realOpenDuoPrice is not None: openPrice = self.realOpenDuoPrice rate = round((tick.lastPrice - openPrice) / openPrice, 8) * 100 print '[' + str( util.getYMDHMS()) + '] RiskControl realOpenDuoPrice: ' + str( self.realOpenDuoPrice) + ' rate: ' + str(rate) if rate < RiskControlRate: self.lockActionToken = True # 发出放狗指令 if self.locking is True and rate > -RiskControlRate: self.unlockActionToken = True # 发出放狗指令 #Return的话,说明还没有开仓,或者开仓时候没有设置这两个值 if self.realOpenDuoPrice is None and self.realOpenKonPrice is None: return # 动作执行区域!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!########################################## # 锁动作执行 if self.lockActionToken is True and self.locking is False: if self.realOpenKonPrice is not None: if self.ctaEngine is not None: self.ctaEngine.cover( tick.upperLimit * 0.995, int32(self.maxPosition) ) # 平空!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! smtp.notifyLockKon(security=self.security) if self.realOpenDuoPrice is not None: if self.ctaEngine is not None: self.ctaEngine.sell( tick.lowerLimit * 1.005, int32(self.maxPosition) ) # 平多!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! smtp.notifyLockDuo(security=self.security) self.locking = True # 持久化,下次策略重载时风控对象重新初始化从数据库读取 dao.activeLocking(security=self.security) self.lockActionToken = False # 解锁动作执行 if self.unlockActionToken is True and self.locking is True: if self.realOpenKonPrice is not None: if self.ctaEngine is not None: smtp.notifyUnLockKon(security=self.security) if self.realOpenDuoPrice is not None: if self.ctaEngine is not None: smtp.notifyUnLockDuo(security=self.security) self.locking = False # 持久化,下次策略重载时风控对象重新初始化从数据库读取 dao.releaseLocking(security=self.security) self.unlockActionToken = False
def notifyError(content): currentTimeString = util.getYMDHMS() sendEmail(subject='[' + str(currentTimeString) + '] 错误:' + content, content=str(content))
def grdetect(array, verbose=False): event = Event(Event.NONE) copy = array.copy() array = _remove_background(array) # 移除背景, add by wnavy ''' gray = Util.to_grayscale(array) # 转化为灰度图像 blur = cv2.GaussianBlur(gray, ksize = _DEFAULT_GAUSSIAN_BLUR_KERNEL, sigmaX = 0) # 高斯滤波 _, thresh = cv2.threshold(blur, 0, 255, _DEFAULT_THRESHOLD_TYPE) # 图像二值化 ''' thresh = _bodyskin_detetc(array) if verbose: cv2.imshow('pygr.HoverPad.roi.threshold', thresh) contours = _get_contours(thresh.copy()) largecont = max(contours, key=lambda contour: cv2.contourArea(contour)) if verbose: roi = cv2.boundingRect(largecont) copy = Util.mount_roi(copy, roi, color=_COLOR_RED) convexHull = cv2.convexHull(largecont) if verbose: _draw_contours(copy, contours, -1, _COLOR_RED, 0) _draw_contours(copy, [largecont], 0, _COLOR_GREEN, 0) _draw_contours(copy, [convexHull], 0, _COLOR_GREEN, 0) hull = cv2.convexHull(largecont, returnPoints=False) defects = cv2.convexityDefects(largecont, hull) if defects is not None: copy, ndefects = _get_defects_count(copy, largecont, defects, verbose=verbose) if ndefects == 0: copy, tip = _get_tip_position(copy, largecont, verbose=verbose) event.setTip(tip) # TODO: check for a single finger. # event.setType(Event.ROCK) event.setType(Event.ZERO) elif ndefects == 1: # TODO: check for an Event.LIZARD # event.setType(Event.SCISSOR) event.setType(Event.TWO) elif ndefects == 2: # event.setType(Event.SPOCK) event.setType(Event.THREE) elif ndefects == 3: event.setType(Event.FOUR) elif ndefects == 4: # event.setType(Event.PAPER) event.setType(Event.FIVE) if verbose: cv2.imshow('pygr.HoverPad.roi', copy) if verbose: return copy, event else: return event
def log(content): string = "[Time: " + util.getYMDHMS() + "]: " + str(content) print(string) return string
def notifyCloseDuo(security, currentTimeString=None): if currentTimeString is None: currentTimeString = util.getYMDHMS() a = '<a href="http://107.182.31.161:5288/">查看行情</a>' sendEmail(subject='[' + str(currentTimeString) + '] Duo平_' + security, content='' + a)
def notifyLockDuo(security): currentTimeString = util.getYMDHMS() a = '<a href="http://107.182.31.161:5288/">查看行情</a>' sendEmail(subject='[' + str(currentTimeString) + '] 锁多(平多仓)_' + security, content='' + a)