def log(): global pre print('如有任何问题,请联系[email protected]') _path = Path('Config.txt') if not _path.exists(): print('Config.txt不存在,请构建Config.txt,格式如下\n' '第1行:IP;' '第2行:port;' '第3行:账号;' '第4行:密码;' '第5行:authcode;' '第6行:订阅品种,譬如COMEX F GC 1902;' '如果有多个品种,累加即可,格式同第6行' ) else: _config = _path.lines() _send = False if pre == _config else True pre = _config es = ESQuote() es.config_re_login(60) # 重连时间,s es.config_account(ip=_config[0], port=_config[1], username=_config[2], password=_config[3], authcode=_config[4], send=_send) for i in _config[5:]: es.config_subscribes(i) es.reading_out()
def log(string): now = ar.now() filename = Pth(f"Bin/Log/{now.format('YYYY-MM-DD')}.txt") file_exists(filename.parent) string = f'{now.format("YYYY-MM-DD HH:mm:ss.SSSSSS")}\t{string}' string = string.replace('\n', '+') filename.write_text(string + '\n', append=True, encoding='gbk') print(string)
def send(msg): name = f"Bin\\{''.join(msg[:3])}.txt" content = { _name: _values for _name, _values in zip(names, msg) } Path(name).write_text(str(content).replace("'", '"'))
def __get_redis(): redis_conf = {'socket_timeout': 3} for line in Path('Bin/Config/Redis.txt').lines(): if ':' in line: _key, value = [j.strip() for j in line.split(':')] redis_conf[_key] = value if value != 'None' else None pool = redis.ConnectionPool(**redis_conf) r = redis.Redis(connection_pool=pool) log('start Redis->' + ','.join(redis_conf)) return r
def __get_socket(): hostname, port = [ i.strip() for i in Path('Bin/Config/Socket.txt').lines() if i.strip() ] port = int(port) srv = socket.socket() # 创建一个socket srv.bind(('', port)) srv.listen(5) log(f"socket等待{hostname}:{port}的链接") connect_socket, addr = srv.accept() print('链接IP', addr) log(f"socket链接成功") return connect_socket
def trade_time(): holiday = loads(Path('Bin/Config/Holiday.json').text()) tz = ar.now().tzinfo # everyday now = ar.now() everyday_close_time, everyday_open_time = holiday['everyday'][0] everyday_close_time = f"{now.format('YYYY-MM-DD')} {everyday_close_time}" everyday_open_time = f"{now.format('YYYY-MM-DD')} {everyday_open_time}" everyday_close_time = ar.get(everyday_close_time).replace(tzinfo=tz) everyday_open_time = ar.get(everyday_open_time).replace(tzinfo=tz) target_time = now if now.isoweekday() == 1 and now < everyday_open_time: # 工作日 target_time = everyday_open_time elif 2 <= now.isoweekday() <= 5 and everyday_close_time <= now < everyday_open_time: target_time = everyday_open_time elif now.isoweekday() == 6 and now > everyday_close_time: target_time = everyday_open_time.shift(days=2) elif now.isoweekday() == 7: target_time = everyday_open_time.shift(days=1) diff = target_time.float_timestamp - now.float_timestamp if diff > 0: print(f'常规休眠{diff}s,待{target_time}启动!') sleep(diff) # holiday for close_time, open_time in holiday['holiday']: now = ar.now() close_time = ar.get(close_time).replace(tzinfo=tz) open_time = ar.get(open_time).replace(tzinfo=tz) if close_time <= now < open_time: diff = open_time.float_timestamp - now.float_timestamp if diff > 0: print(f'节假日休眠{diff}s,待{open_time}启动!') sleep(diff) print('交易时间')
def send(msg): name = f"Bin//{''.join(msg[:3])}.txt" Path(name).write_text(','.join(msg))
def __config_tool(self): self.way = Path('Bin/Config/Publish.txt').text().strip() if self.way == '1': # redis tool = self.__get_redis() def send(msg): chanel = ''.join(msg[:3]) tool.publish(chanel, ','.join(msg)) # names = [[f'QBidPrice{i}', f'QBidQty{i}', f'QAskPrice{i}', f'QAskQty{i}'] for i in range(1, 21)] # names = ['ExchangeNo', 'CommodityNo', 'Contract.ContractNo1', 'DateTimeStamp', 'QPreClosingPrice', # 'QPreSettlePrice', 'QPrePositionQty', 'QOpeningPrice', 'QLastPrice', 'QHighPrice', 'QLowPrice', # 'QHisHighPrice', 'QHisLowPrice', 'QLimitUpPrice', 'QLimitDownPrice', 'QTotalQty', 'QTotalTurnover', # 'QPositionQty', 'QAveragePrice', 'QClosingPrice', 'QSettlePrice', 'QLastQty', 'QImpliedBidPrice', # 'QImpliedBidQty', 'QImpliedAskPrice', 'QImpliedAskQty', 'QPreDelta', 'QCurrDelta', 'QInsideQty', # 'QOutsideQty', 'QTurnoverRate', 'Q5DAvgQty', 'QPERatio', 'QTotalValue', 'QNegotiableValue', # 'QPositionTrend', 'QChangeSpeed', 'QChangeRate', 'QChangeValue', 'QSwing', 'QTotalBidQty', # 'QTotalAskQty'] + [j for i in names for j in i] # # if self.way == '1': # redis # tool = self.__get_redis() # # def send(msg): # chanel = ''.join(msg[:3]) # content = {_name: _values for _name, _values in zip(names, msg)} # tool.publish(chanel, dumps(content)) elif self.way == '2': # socket tool = self.__get_socket() def send(msg): tool.send(bytes(','.join(msg), encoding='gbk')) elif self.way == '3': # 文本 def send(msg): name = f"Bin//{''.join(msg[:3])}.txt" Path(name).write_text(','.join(msg)) elif self.way == '4': # udp clients = loads(Path('Bin/Config/UDPAccount.json').text()) # 使用合约来确定客户ip,比如COMEXGC2009:101.0.0.0 con2ip = {} for client, contracts in clients.items(): client = client.split(',') client = client[0], int(client[1]) for contract in contracts: contract = contract.split(' ') contract = contract[0] + contract[2] + contract[3] if contract in con2ip.keys(): con2ip[contract].append(client) else: con2ip[contract] = [client] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def send(msg): contract = ''.join(msg[:3]) for ip in con2ip.get(contract, []): print(contract, ip) s.sendto(','.join(msg).encode(), ip) else: send = print self.tool = send
class Contract: clients = loads(Path('Bin/Config/UDPAccount.json').text())