def get_position(engine): client = api.use('ths') client.connect('D:/software/ths2/xiadan.exe') pos = client.position print(pos) now = datetime.now().strftime('%Y-%m-%d') data = [] row_name_to_sql = {'account_no': '股东帐户', 'ticker': '证券代码', 'name_cn': '证券名称', 'qty': '股票余额', 'available_qty': '可用余额', 'avg_cost': '成本价', 'pnl': '盈亏比(%)' } for posi in pos: row = [] row.append(posi[row_name_to_sql['account_no']]) row.append(now) row.append(posi[row_name_to_sql['ticker']]) row.append(posi[row_name_to_sql['name_cn']]) row.append(posi[row_name_to_sql['qty']]) row.append(posi[row_name_to_sql['available_qty']]) row.append(posi[row_name_to_sql['avg_cost']]) row.append(posi[row_name_to_sql['pnl']]) data.append(row) account_holding_service_impl.restore(engine, data)
def run(): executors = { 'default': { 'type': 'threadpool', 'max_workers': 10 }, 'processpool': ProcessPoolExecutor(max_workers=5) } scheduler = BlockingScheduler() scheduler.configure(executors=executors) client = api.use('ths', debug=False) client.connect(r"c:\\workspace\\同花顺\\\\xiadan.exe", timeout=5) client.enable_type_keys_for_editor() # add job for computing trendency of all stock scheduler.add_job(join_quant_follower_sell, 'cron', day_of_week='mon-fri', hour=9, minute=27, args=[client]) scheduler.add_job(join_quant_follower_buy, 'cron', day_of_week='mon-fri', hour=9, minute=31, args=[client]) # join_quant_follower_sell(client,session) # join_quant_follower_buy(client,session) try: scheduler.start() except (KeyboardInterrupt, SystemExit): scheduler.remove_all_jobs()
# -*- coding: utf-8 -*- import sys from easytrader import api client = api.use('yh_client') client.prepare('yh_client.json') result = client.balance print(result)
def test(): # join_quant_follower() client = api.use('ths', debug=False) # client.connect(r"D:\\同花顺软件\\同花顺\\xiadan.exe", timeout=5) # client.connect(r"D:\\software\\同花顺独立下单\\xiadan.exe",timeout=5) client.connect(r"c:\\workspace\\同花顺\\xiadan.exe", timeout=5) client.enable_type_keys_for_editor() help_msg = """1--buyF1 2--sellF2 3--chedanF3 4--searchF4:chicang 5--F4:today:trader 6--F4:today:entrusts """ print(help_msg) msg = input("please input your choice:") while True: if msg == '1': msg = input( "limit buy, please input your ticker,price and amount:") words = msg.split(' ') client.buy(words[0], float(words[1]), amount=int(words[2])) elif msg == '1.1': msg = input("market buy, please input your ticker and amount:") words = msg.split(' ') client.market_buy(words[0], amount=int(words[1]), ttype=u'1-对手方最优价格申报') elif msg == '2': msg = input( "limit sell, please input your ticker,price and amount:") words = msg.split(' ') client.sell(words[0], float(words[1]), amount=int(words[2])) elif msg == '2.1': msg = input("market sell, please input your ticker and amount:") words = msg.split(' ') client.market_sell(words[0], amount=int(words[1]), ttype=u'1-对手方最优价格申报') elif msg == '3': client.cancel_entrust(input('order no:')) elif msg == '3.1': print(client.cancel_entrusts) elif msg == '3.2': print(client.cancel_all_entrust()) elif msg == '3.3': print(client.cancel_all_sell_entrust()) elif msg == '3.4': print(client.cancel_all_buy_entrust()) elif msg == '4': print(client.balance) elif msg == '4.1': pos = client.position print(client.position) elif msg == '5': print(client.today_trades) elif msg == '6': print(client.today_entrusts) elif msg == '7': # account_type=input("account type:") # account_no=input('account no:') print(client.switch_trade_account(u'上海A股', u'A446850006')) else: break print(help_msg) msg = input("please input your choice:")
class Istrate(abc.ABC): rerunList = list() # 策略序列 client = api.use('htzq_client') # 客户端对象 def __init__(self,name,step = 0,share = None, price = 0, num = 0, change = 0, have = 0,waittime = 7 ,bug = False): self.step = step # 0为开仓状态,5为进行开仓,10开仓完毕,15进行调仓状态,20为清仓状态 self.have = have self.MaxHave = 20 self.state = '常' self.price = price day = time.strftime("%Y-%m-%d", time.localtime()) filename = config.homePath + day +name +'['+share.code+']'+'.log' name = name+'['+share.code+']' self.sellEntrust = 'null' self.buyEntrust = 'null' self.entrusts = [] self.waittime = waittime self.nowwaittime = waittime if not bug: self.readConfig(filename) self.logger = stratelog.stratelog(name,filename,self) self.name = name self.share = share self.num = num self.oneHand = num * share.oneHand self.change = change # 读取配置价格 def readConfig(self,filename): # 日志模式 未实现 if os.path.exists(filename): f = open(filename,encoding = 'utf8') line = f.readlines() try: last_line = (line[-1])[:-1].split(',') self.step = int(last_line[1]) state = last_line[3] self.price = float(last_line[5]) self.have = int(last_line[7]) self.buyEntrust = last_line[9] self.sellEntrust = last_line[11] self.buyPrice = self.price - self.change self.sellPrice = self.price + self.change except BaseException: print('日志读取失败') def buy(self): resoult = Istrate.client.aout_buy(self.share.code ,self.price ,self.oneHand) if resoult['state'] == 'success': self.buyEntrust = resoult['成交合同'] return True else: print('交易失败') print(resoult['content']) return False def buys(self,price,change,n): # 梯度买入 buyEntrusts = [] for i in range(n): resoult = Istrate.client.aout_buy(self.share.code ,price + change * i ,self.oneHand) if resoult['state'] == 'success': e = entrustobj(entrustcode = resoult['成交合同'], price = price + change * i) buyEntrusts.append(e) else: print('交易失败') print(resoult['content']) return False return buyEntrusts def sells(self,price,change,n): # 梯度卖出 sellsEntrusts = [] for i in range(n): resoult = Istrate.client.aout_sell(self.share.code ,price - change * i ,self.oneHand) if resoult['state'] == 'success': e = entrustobj(entrustcode = resoult['成交合同'], price = price - change * i) sellsEntrusts.append(e) else: print('交易失败') print(resoult['content']) return False return sellsEntrusts def buy_sell(self): resoult = Istrate.client.aout_buy_sell(self.share.code ,self.buyPrice ,self.sellPrice ,self.oneHand) if resoult['state'] == 'success': self.sellEntrust = resoult['卖出合同'] self.buyEntrust = resoult['买入合同'] return True else: if '错误合同' in resoult: if '资金不足' in resoult['content']: self.sellEntrust = resoult['错误合同'] self.buyEntrust = resoult['错误合同'] return True else: self.logger.info(resoult['content']) return False # 开仓条件 def start(self): return True # 调仓条件 def adjust(self): return True # 清除条件及操作 def end(self): return True # 取消多个合同 def cancel_entrusts(self,df,entrusts): entrustIndex = [] for entrust in entrusts: if len(df.loc[df['合同编号'] == entrust]) == 0: pass else: entrustIndex.append(int(df.loc[df['合同编号'] == entrust].index[0]) + 1) entrustIndex.sort(reverse=True) for index in entrustIndex: self.client.have_cancel_entrust(index) # 取消单个合同 def cancel_entrust(self,df,entrust): # 不存在 if len(df.loc[df['合同编号'] == entrust]) == 0: print('合同消失') return False else: print(int(df.loc[df['合同编号'] == entrust].index[0])) self.client.have_cancel_entrust(int(df.loc[df['合同编号'] == entrust].index[0]) + 1) return True @abc.abstractmethod def setPrice(self,price): pass # 时间周期 def wait_Time(self): if self.nowwaittime == 0: self.nowwaittime = self.waittime return True else: self.nowwaittime = self.nowwaittime - 1 return False @classmethod def initClient(cls): cls.client.prepare(config_path = config.homePath + 'password.txt') @classmethod def timeSlot(cls): while True: s = 3 time.sleep(s) if len(cls.rerunList) > 0 and config.strateQueue.qsize() == 0: config.strateQueue.put(cls.rerunList) @classmethod def work(cls): cls.initClient() thread2 = threading.Thread(target=cls.timeSlot,args=('')) thread2.start() while True: data = config.strateQueue.get() if isinstance(data,list): runList = [] for strate in data: if strate.wait_Time(): runList.append(strate) if len(runList)>0: print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ) df = cls.client.getEntrust() # print(df) for strate in runList: strate.run(df) else: if data.step == 0 or data.step == 10: data.run() cls.rerunList.append(data) else: cls.rerunList.append(data)
import sys, time sys.path.append(".") from strate.config import config from easytrader import api, exceptions user = api.use('htzq_client') user.prepare(config_path=config.homePath + 'password.txt') # for i in range(9): # time.sleep(5) # print(user.getEntrust()['证券代码']) # print(user.aout_buy('002127','0.07771','100')) # 撤单 # user._switch_left_menus(["撤单[F3]"]) # user.have_cancel_entrust(4)