def connect(self): """ 连接API :return: """ # 创建api连接对象实例 try: if self.api is None or self.connection_status == False: self.strategy.writeCtaLog(u'开始连接通达信股票行情服务器') self.api = TdxHq_API(heartbeat=True, auto_retry=True, raise_exception=True) # 选取最佳服务器 if TdxData.best_ip is None: from pytdx.util.best_ip import select_best_ip TdxData.best_ip = select_best_ip() self.api.connect(self.best_ip, 7709) self.strategy.writeCtaLog(u'创建tdx连接, IP: {}/{}'.format( self.best_ip, 7709)) TdxData.connection_status = True except Exception as ex: self.strategy.writeCtaLog(u'连接服务器tdx异常:{},{}'.format( str(ex), traceback.format_exc())) return
def connect(self): """ 连接API :return: """ # 创建api连接对象实例 try: if self.api is None or not self.connection_status: self.write_log(u'开始连接通达信股票行情服务器') self.api = TdxHq_API(heartbeat=True, auto_retry=True, raise_exception=True) # 选取最佳服务器 if TdxStockData.best_ip is None: from pytdx.util.best_ip import select_best_ip TdxStockData.best_ip = select_best_ip() self.api.connect(self.best_ip.get('ip'), self.best_ip.get('port')) self.write_log(f'创建tdx连接, : {self.best_ip}') TdxStockData.connection_status = True except Exception as ex: self.write_log(u'连接服务器tdx异常:{},{}'.format(str(ex), traceback.format_exc())) return
def connect(self, is_reconnect: bool = False): """ 连接API :param:is_reconnect, 是否重新连接 :return: """ # 创建api连接对象实例 try: if self.api is None or not self.connection_status: self.write_log(u'开始连接通达信股票行情服务器') self.api = TdxHq_API(heartbeat=True, auto_retry=True, raise_exception=True) # 选取最佳服务器 if is_reconnect or self.best_ip is None: self.best_ip = self.config.get('best_ip', {}) if len(self.best_ip) == 0: from pytdx.util.best_ip import select_best_ip self.best_ip = select_best_ip() self.config.update({'best_ip': self.best_ip}) save_cache_config(self.config, TDX_STOCK_CONFIG) self.api.connect(self.best_ip.get('ip'), self.best_ip.get('port')) self.write_log(f'创建tdx连接, : {self.best_ip}') self.connection_status = True except Exception as ex: self.write_log(u'连接服务器tdx异常:{},{}'.format(str(ex), traceback.format_exc())) return
def best_ip(self): return select_best_ip()
else: # wave_info_display(datapd, stock, stockname) rsi_info_display(datapd, stock, stockname) # dingdang(data, stock, stockname ) if __name__ == '__main__': import time api = TdxHq_API(heartbeat=True) ttsengine = pyttsx3.init() mylog.add("stock_trading_{time}.log", encoding='utf-8') from pytdx.util.best_ip import select_best_ip stock_ip = select_best_ip('stock') print(stock_ip) future_ip = select_best_ip('future') print(future_ip) # if api.connect('119.147.212.81', 7709): if api.connect(stock_ip['ip'], stock_ip['port']): szall = api.get_security_count(0) shall = api.get_security_count(1) szsecs = api.get_security_list(0, 0) shsecs = api.get_security_list(1, 0) # szStockProcess(DAY) # shStockProcess(DAY) print('全市场轮询结束.')
import pathlib import time import pandas as pd from pytdx.hq import TdxHq_API from pytdx.util.best_ip import select_best_ip ip = select_best_ip() # ip = '180.153.18.170' # ip = '202.108.253.130' # print(ip) def _select_market_code(code): """ 1- sh 0 -sz """ code = str(code) if code[0] in ['5', '6', '9'] or code[:3] in [ "009", "126", "110", "201", "202", "203", "204" ]: return 1 return 0 def _codes(): api = TdxHq_API() with api.connect(ip):
endWork = datetime.now().strftime("%Y-%m-%d") + ' ' + workTime[1] beginWorkSeconds = time.time() - time.mktime( time.strptime(beginWork, '%Y-%m-%d %H:%M:%S')) endWorkSeconds = time.time() - time.mktime( time.strptime(endWork, '%Y-%m-%d %H:%M:%S')) if (int(dayOfWeek) in range(5) ) and int(beginWorkSeconds) > 0 and int(endWorkSeconds) < 0: return 1 else: return 0 if __name__ == '__main__': from pytdx.util.best_ip import select_best_ip stock_ip = select_best_ip('stock') print(stock_ip) # future_ip = select_best_ip('future') # print(future_ip) # if api.connect('119.147.212.81', 7709): if api.connect(stock_ip['ip'], stock_ip['port']): count = 0 while True: kezhuanzhaiProcess(M15) if workDay(): kezhuanzhaiProcess(M15) # szStockProcess(M15)
def main(ips): if len(ips) == 0: best_ip = select_best_ip() ips = [best_ip] print("Using default ip: {}".format(best_ip)) def single_client_benchmark(ip): def _log(msg): click.echo("HQ_BENCHMARK: [{:15s}] {} ".format(ip, datetime.datetime.now()) + msg) def _grouped_list(stocks): return [stocks[i:i + GET_QUOTES_PER_GROUPS] for i in range(0, len(stocks), GET_QUOTES_PER_GROUPS)] _log("start benchmark") total_time = connecting_time = get_security_count_time = get_security_list_time = get_security_quotes_time = num = 0 start_time = time.time() last_time = start_time try: api = TdxHq_API(multithread=True) port = 7709 if ":" in ip: ip, port = ip.split(':') port = int(port) with api.connect(ip=ip, port=port): _log("connected") cur_time = time.time() connecting_time = cur_time - last_time last_time = cur_time _log("connecting time is {}".format(connecting_time)) num = api.get_security_count(0) _log("all shenzhen market stock count is {}".format(num)) cur_time = time.time() get_security_count_time = cur_time - last_time last_time = cur_time _log("get_security_count_time is {}".format(get_security_count_time)) all = [] for i in range((num // 1000) + 1): offset = i * 1000 section = api.get_security_list(0, offset) all = all + section cur_time = time.time() get_security_list_time = cur_time - last_time last_time = cur_time _log("get_security_list_time is {}".format(get_security_list_time)) codes = [one['code'] for one in all] results = [] for stocks in _grouped_list(codes): req_list = [(0, code) for code in stocks] one_results = api.get_security_quotes(req_list) results = results + one_results cur_time = time.time() get_security_quotes_time = cur_time - last_time last_time = cur_time _log("get_security_quotes_time is {}".format(get_security_quotes_time)) total_time = last_time - start_time _log("total_time is {}".format(total_time)) _log("end benchmark") except Exception as e: _log("hit exception " + str(e)) return { "ip": ip, "total_time": total_time, "connecting_time": connecting_time, "get_security_count_time": get_security_count_time, "get_security_list_time": get_security_list_time, "get_security_quotes_time": get_security_quotes_time, "security_count": num } with ThreadPoolExecutor(max_workers=len(ips)) as executor: results = executor.map(single_client_benchmark, ips) rows = [] rows.append(("IP", "Total", "Connecting", "Get Count", "Get List", "Get Quotes")) for result in results: rows.append( [result['ip'], "{:0.6f}".format(result['total_time']), "{:0.6f}".format(result['connecting_time']), "{:0.6f} ({})".format(result['get_security_count_time'], result['security_count']), "{:0.6f}".format(result['get_security_list_time']), "{:0.6f}".format(result['get_security_quotes_time'])] ) print("=" * 40) print_table(rows)
def main(ips): if len(ips) == 0: best_ip = select_best_ip() ips = [best_ip] print("Using default ip: {}".format(best_ip)) def single_client_benchmark(ip): def _log(msg): click.echo("HQ_BENCHMARK: [{:15s}] {} ".format( ip, datetime.datetime.now()) + msg) def _grouped_list(stocks): return [ stocks[i:i + GET_QUOTES_PER_GROUPS] for i in range(0, len(stocks), GET_QUOTES_PER_GROUPS) ] _log("start benchmark") total_time = connecting_time = get_security_count_time = get_security_list_time = get_security_quotes_time = num = 0 start_time = time.time() last_time = start_time try: api = TdxHq_API(multithread=True) port = 7709 if ":" in ip: ip, port = ip.split(':') port = int(port) with api.connect(ip=ip, port=port): _log("connected") cur_time = time.time() connecting_time = cur_time - last_time last_time = cur_time _log("connecting time is {}".format(connecting_time)) num = api.get_security_count(0) _log("all shenzhen market stock count is {}".format(num)) cur_time = time.time() get_security_count_time = cur_time - last_time last_time = cur_time _log("get_security_count_time is {}".format( get_security_count_time)) all = [] for i in range((num // 1000) + 1): offset = i * 1000 section = api.get_security_list(0, offset) all = all + section cur_time = time.time() get_security_list_time = cur_time - last_time last_time = cur_time _log("get_security_list_time is {}".format( get_security_list_time)) codes = [one['code'] for one in all] results = [] for stocks in _grouped_list(codes): req_list = [(0, code) for code in stocks] one_results = api.get_security_quotes(req_list) results = results + one_results cur_time = time.time() get_security_quotes_time = cur_time - last_time last_time = cur_time _log("get_security_quotes_time is {}".format( get_security_quotes_time)) total_time = last_time - start_time _log("total_time is {}".format(total_time)) _log("end benchmark") except Exception as e: _log("hit exception " + str(e)) return { "ip": ip, "total_time": total_time, "connecting_time": connecting_time, "get_security_count_time": get_security_count_time, "get_security_list_time": get_security_list_time, "get_security_quotes_time": get_security_quotes_time, "security_count": num } with ThreadPoolExecutor(max_workers=len(ips)) as executor: results = executor.map(single_client_benchmark, ips) rows = [] rows.append(("IP", "Total", "Connecting", "Get Count", "Get List", "Get Quotes")) for result in results: rows.append([ result['ip'], "{:0.6f}".format(result['total_time']), "{:0.6f}".format(result['connecting_time']), "{:0.6f} ({})".format(result['get_security_count_time'], result['security_count']), "{:0.6f}".format(result['get_security_list_time']), "{:0.6f}".format(result['get_security_quotes_time']) ]) print("=" * 40) print_table(rows)
def get_ip(): print('get ip...') global ip if ip is None: ip = select_best_ip() print('ip is: ', ip)