def _order_open(self,price,direction,vol=1): """开仓""" cs = self.cs if not vol: vol = self.get_max_order_num(price) # 计算开仓数量 if direction == stbase.Constants.Long: # 买开 price = self.last_tick.price.last + 2 self.buy(self.code, price, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.LimitPrice,exchange_id=cs.exchange_id, cc = stbase.futures.Constants.ContingentConditionType.Immediately, tc = stbase.futures.Constants.TimeConditionType.IOC ) elif direction == stbase.Constants.Short: # 卖开 price = self.last_tick.price.last - 2 # self.sell('rb2001', 0, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.LimitPrice,exchange_id='SHFE') self.sell(self.code, price, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.LimitPrice, exchange_id=cs.exchange_id, cc = stbase.futures.Constants.ContingentConditionType.Immediately,tc = stbase.futures.Constants.TimeConditionType.IOC ) else: print 'Error: Empty Operatoin "order_close()" ' return data = OrderedDict(strategy_id=self.id, code=self.code, issue_time=datetime.datetime.now(), oc=stbase.Constants.Close, direction=direction, vol=vol) record = model.TradeOrder() object_assign(record, data, True) record.save() cs.open_date = datetime.datetime.now().replace(hour=0,minute=0,second=0,microsecond=0) # 记录开仓日期 cs.save()
def getHistoryBars(self,code,cycle='1m',limit=100,lasttime=None,inc_last=False): """获取历史k线 剔除最后一根活动k线(盘中不能使用最后一根k线,或许是未完成计算的中间结果) result 以时间升序排列 """ from mantis.sg.fisher.stbase.futures import BarData result = [] # stbase.BarData() stock= self.product.getOrNewTradeObject(code) cycle_cat_map = { '1m': 1,'5m': 5,'15m': 15, '30m': 30,'60m': 60,'d': 'd' } scale = cycle_cat_map[cycle] db_conn = self.cfgs.get('db_conn') if not db_conn: return [] dbname = 'Ctp_Bar_'+str(scale) coll = db_conn[dbname][code] if lasttime: if isinstance(lasttime,str): lasttime = parse(lasttime) rs = coll.find({'datetime':{'$lte':lasttime}}).sort( 'datetime',-1).limit(limit) else: rs = coll.find().sort( 'datetime',-1 ).limit(limit) rs = list(rs) rs.reverse() result = [] for r in list(rs): bar = BarData() object_assign(bar,r,add_new=True) result.append(bar) return result
def getPosition(self, code='', strategy_id='', direction=''): """查询指定 代码或者指定策略的持仓记录""" url = self.cfgs.get("td_api_url") + '/ctp/position/list' result = [] try: res = requests.get(url) values = res.json().get('result', []) for _ in values: pos = Position() object_assign(pos, _) okay = pos if code: if code != pos.InstrumentID: okay = None if okay and direction: if direction == stbase.Constants.Buy and pos.PosiDirection != stbase.futures.Constants.PositionDirection.Long: okay = None if direction == stbase.Constants.Sell and pos.PosiDirection != stbase.futures.Constants.PositionDirection.Short: okay = None if okay: result.append(pos) except: traceback.print_exc() return result
def query_resp_funds(self): """资金返回""" url = self.cfgs.get("td_api_url") + '/ctp/account' try: res = requests.get(url) data = res.json().get('result', {}) self.stat = AccountStat() object_assign(self.stat, data) except: self.logger.error("Request Trader Service Fail Down.")
def getTrades(self): url = self.cfgs.get("td_api_url") + '/ctp/trade/list' orders = [] try: res = requests.get(url) values = res.json().get('result', []) for _ in values: tr = TradeReturn() object_assign(tr, _) orders.append(tr) except: traceback.print_exc() return orders
def quoteBarRecv(self): """一次读取指定条件的k线记录,并开始回放""" symbol = self.cfgs.get('symbol') cycle =self.cfgs.get('cycle') freq = self.cfgs.get('freq',0.5) db = self.cfgs.get('db_conn')['Ctp_Bar_{}'.format(cycle)] coll = db[symbol] wait = self.cfgs.get('wait',1) print 'wait for ',wait, 'seconds ..' time.sleep(wait) start = self.cfgs.get('start') end = self.cfgs.get('end') if isinstance(start,(str,unicode)): start = parse(start) if not end: end = datetime.datetime.now() else: end = parse(end) rs = coll.find({'datetime':{'$gte':start,'$lte':end }}).sort('datetime',1) # rs = coll.find().sort('datetime',1).limit(10) for data in list(rs): if freq: time.sleep(freq) bar = BarData() object_assign(bar,data,add_new=True) # ktype = '{}m'.format(data['cycle']) if cycle in ('D','d'): bar.cycle = cycle else: bar.cycle = '{}m'.format(cycle) # 必须是 sc1907-1m 的格式 bar.code = symbol bar.time = data['datetime'] bar.sys_time = datetime.datetime.now() bar.trade_object = stbase.controller.futures.getTradeObject(symbol) self.putData(bar) # 置入处理队列等待线程读取 endflag = BarDataEndFlag() endflag.code = symbol if cycle in ('D', 'd'): endflag.cycle = cycle else: endflag.cycle = '{}m'.format(cycle) self.putData(endflag)
def _getTradeRecords(self): url = self.cfgs.get("td_api_url") + '/ctp/trade/list' orders = [] try: res = requests.get(url,timeout=3) values = res.json().get('result',[]) if not values: values =[] for _ in values: tr = TradeReturn() object_assign(tr,_) tr.normalize() orders.append(tr) except: traceback.print_exc() return orders
def quoteBarRecv(self, message, ctx): data = message data = json.loads(data) ktype = '{}m'.format(data['cycle']) code = data['symbol'] name = '{}-{}'.format(code, ktype) last = self.bar_last_data[name].get('last') # self.bar_last_data[name]['last'] = current bar = BarData() object_assign(bar, data, add_new=True) bar.cycle = ktype bar.code = code bar.sys_time = datetime.datetime.now() bar.trade_object = stbase.controller.futures.getTradeObject(code) self.putData(bar) # 置入处理队列等待线程读取
def getOrders(self, order_id='', code='', strategy_id=''): """查询委托信息,状态包括: 未成、部分成、全成、错误 strategy_id 作为 委托的 orign source 字段 """ url = self.cfgs.get("td_api_url") + '/ctp/order/list' orders = [] try: res = requests.get(url) values = res.json().get('result', []) for _ in values: order = OrderRecord() object_assign(order, _) if order_id: if order_id in (order.order_id, order.user_order_id): orders.append(order) except: traceback.print_exc() return orders
def _order_close(self,price , direction): """平仓 默认多头""" cs = self.cs vol = self.get_position(direction) if direction == stbase.Constants.Long: # 平多 price = self.last_tick.price.last - 2 self.sell(self.code,price,vol,stbase.Constants.Close,stbase.futures.Constants.OrderPriceType.LimitPrice,exchange_id=cs.exchange_id,cc = stbase.futures.Constants.ContingentConditionType.Immediately,tc = stbase.futures.Constants.TimeConditionType.IOC) elif direction == stbase.Constants.Short: # 平空 price = self.last_tick.price.last + 2 self.buy(self.code,price,vol,stbase.Constants.Close,stbase.futures.Constants.OrderPriceType.LimitPrice,exchange_id=cs.exchange_id,cc = stbase.futures.Constants.ContingentConditionType.Immediately,tc = stbase.futures.Constants.TimeConditionType.IOC) else: print 'Error: Empty Operatoin "order_close()" ' return data = OrderedDict(strategy_id=self.id, code=self.code, issue_time=datetime.datetime.now(), oc=stbase.Constants.Close, direction=direction, vol=vol) record = model.TradeRecord() object_assign(record, data, True) record.save()
def quoteTickRecv(self,message,ctx): data = message tick = json.loads(data) dt = datetime.datetime.fromtimestamp(tick['Timestamp']) tick['DateTime'] = datetime.datetime.strptime(tick['DateTime'], '%Y%m%d %H:%M:%S.%f') tick['SaveTime'] = datetime.datetime.now() code = tick['InstrumentID'] data = stbase.TickData() data.code = code data.trade_object = stbase.controller.futures.getOrNewTradeObject(code) data.sys_time = datetime.datetime.now() price = Price() price.time = data.sys_time object_assign(price,tick) data.price = price data.trade_object.price = data.price self.putData(data) # 置入处理队列等待线程读取
def eventRecv(self,data,ctx): """ctpTradeCxx 推送过来的 委托和成交事件 event : 'event_order' , 'event_trade' """ from mantis.sg.fisher.model import model from mantis.sg.fisher.ctp.errors import error_defs message = json.loads(data) event = message["event"] print event if event == "event_order": # 处理委托通知 order = OrderRecord() object_assign(order, message) order.normalize() self.orders[order.user_order_id] = order log = model.StrategyOrderLog() log.strategy_id = self.cfgs.get('strategy_id') object_assign(log,hash_object(order),True ) log.save() elif event == "event_trade": tr = TradeReturn() object_assign(tr, message) tr.normalize() log = model.StrategyTradeLog() log.strategy_id = self.cfgs.get('strategy_id') object_assign(log, hash_object(tr),True ) log.save() elif event == "event_error": log = model.StrategyErrorLog() log.strategy_id = self.cfgs.get('strategy_id') object_assign(log, message, True) errcode = message.get('errcode',0) errmsg = error_defs.get(int(errcode),'') log.detail = errmsg log.save()
def loadHistBars(self,*args,**kwargs): cfgs = {} cfgs.update(self.cfgs) cfgs.update(kwargs) symbol = cfgs.get('symbol') cycle = cfgs.get('cycle') freq = cfgs.get('freq', 0.5) dataset = cfgs.get('dataset') db = cfgs.get('db_conn')['Ctp_Bar_{}'.format(cycle)] coll = db[dataset] start = cfgs.get('start') end = cfgs.get('end') if isinstance(start, (str, unicode)): start = parse(start) if not end: end = datetime.datetime.now() else: end = parse(end) rs = coll.find({'datetime': {'$gte': start, '$lte': end}}).sort('datetime', 1) bars =[] for data in list(rs): bar = BarData() object_assign(bar, data, add_new=True) if cycle in ('D', 'd'): bar.cycle = cycle else: bar.cycle = '{}m'.format(cycle) # 必须是 sc1907-1m 的格式 bar.code = symbol bar.time = data['datetime'] bar.sys_time = datetime.datetime.now() # bar.trade_object = stbase.controller.futures.getTradeObject(symbol) # self.putData(bar) # 置入处理队列等待线程读取 bars.append(bar) return bars
def order_close(self,price , direction ,volume=1): """平仓 默认多头""" # self.test_shfe() self.siglog_print('order_close: ', price=price, direction=direction, volume=volume) self.siglog_print(**self.sig_params) if not self.order_enable: return cs = self.cs if not volume: volume = cs.open_pos times = 3 time_wait = 10 finished = False order_id = '' vol = volume for _ in xrange(times): if direction == stbase.Constants.Long: # 买开 price = self.last_tick.price.BidPrice1 # 买一价 oc = self.normalizeCloseYdFlag(cs.exchange_id) tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.sell(self.code, price, vol, oc, stbase.futures.Constants.OrderPriceType.LimitPrice, exchange_id=cs.exchange_id, cc=stbase.futures.Constants.ContingentConditionType.Immediately, tc=tc ) elif direction == stbase.Constants.Short: # 卖开 price = self.last_tick.price.AskPrice1 oc = self.normalizeCloseYdFlag(cs.exchange_id) tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.buy(self.code, price, vol, oc, stbase.futures.Constants.OrderPriceType.LimitPrice, exchange_id=cs.exchange_id, tc=tc ) self.log_print(level=model.TradeMessageLog.INFO, title='order_close_limitprice', message='price={} direction={} volume={} order_id={}'.format(price, direction, vol,order_id)) num = self.product.trader.waitOrder(order_id, 10) if num == vol: finished = True break # cancelOrder self.cancelOrder(order_id) vol = volume - num if vol <= 0: finished = True break # 执行市价单 # pos = self.get_position(direction) # pos_water = pos if not finished: order_id = '' finished = False # vol = pos_water - pos_down price = 0 self.log_print(level=model.TradeMessageLog.INFO, title='order_close_anyprice', message='price={} direction={} volume={}'.format(price, direction, vol)) if direction == stbase.Constants.Long: # 买开 oc = self.normalizeCloseYdFlag(cs.exchange_id) tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.buy(self.code, price, vol, oc, stbase.futures.Constants.OrderPriceType.AnyPrice, exchange_id=cs.exchange_id, tc=tc) elif direction == stbase.Constants.Short: # 卖开 oc = self.normalizeCloseYdFlag(cs.exchange_id) tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.sell(self.code, price, vol, oc, stbase.futures.Constants.OrderPriceType.AnyPrice, exchange_id=cs.exchange_id, tc=tc) self.log_print(level=model.TradeMessageLog.INFO, title='order_close_anyprice', message='<< Return order_id={}'.format(order_id)) num = self.product.trader.waitOrder(order_id, 10) if num != vol: finished = False self.log_print(level=model.TradeMessageLog.ERROR, title='order_close_anyprice_error', message='{} order volume:{} , traded num:{}'.format(order_id, vol, num)) else: finished = True # 限价->市价 均委托不成功,则报警并退出 if not finished: self.log_print(level=model.TradeMessageLog.INFO, title='order_close_error', message='Order Failed , Terminating..') self.onTerminated() return # 记录成交委托事件 data = OrderedDict(strategy_id=self.id, code=self.code, issue_time=datetime.datetime.now(), oc=stbase.Constants.Close, direction=direction, vol=volume) record = model.TradeOrder() object_assign(record, data, True) record.save() cs.open_date = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) # 记录开仓日期 cs.save() self.log_print(level=model.TradeMessageLog.INFO, title='order_close_okay', message=' Order Success!')
def order_open(self,price,direction,volume =1): """开仓 n次超时限价委托保证所有量成交,否则下市价单,最终未成功报警处理,程序退出 """ self.siglog_print('order_open: ',price=price,direction=direction,volume = volume) self.siglog_print(**self.sig_params) if not self.order_enable : return cs = self.cs if not volume: volume = self.get_max_order_num(price) # 计算开仓数量 # pos_water = self.get_position(direction) # pos_up = pos_water + volume times = 3 time_wait = 10 finished = False order_id = '' # vol = pos_up - pos_water vol = volume for _ in xrange(times): self.log_print(level=model.TradeMessageLog.INFO, title='order_open_limitprice', message='price={} direction={} volume={}'.format(price, direction, vol)) if direction == stbase.Constants.Long: # 买开 price = self.last_tick.price.BidPrice1 # price = 4920 tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.buy(self.code, price, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.LimitPrice,exchange_id=cs.exchange_id, cc = stbase.futures.Constants.ContingentConditionType.Immediately, tc = tc ) elif direction == stbase.Constants.Short: # 卖开 price = self.last_tick.price.AskPrice1 # price = 4900 tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.sell(self.code, price, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.LimitPrice, exchange_id=cs.exchange_id,tc = tc ) self.log_print(level=model.TradeMessageLog.INFO, title='order_open_limitprice', message='<< Return order_id={}'.format(order_id)) num = self.product.trader.waitOrder(order_id,10) if num == vol: finished = True break # cancelOrder self.cancelOrder(order_id) # vol = volume - num if vol <= 0 : finished = True break if not finished: order_id = '' # if pos_water < pos_up: # finished = False # vol = pos_up - pos_water price = 0 self.log_print(level=model.TradeMessageLog.INFO, title='order_open_anyprice', message='price={} direction={} volume={}'.format(price, direction, vol)) if direction == stbase.Constants.Long: # 买开 tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.buy(self.code, price, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.AnyPrice,exchange_id=cs.exchange_id, tc = tc) elif direction == stbase.Constants.Short: # 卖开 tc = self.normalizeTimeContition(stbase.futures.Constants.TimeConditionType.GFD) order_id = self.sell(self.code, price, vol, stbase.Constants.Open,stbase.futures.Constants.OrderPriceType.AnyPrice, exchange_id=cs.exchange_id,tc = tc ) self.log_print(level=model.TradeMessageLog.INFO, title='order_open_anyprice', message='<< Return order_id={}'.format(order_id)) num = self.product.trader.waitOrder(order_id,10) if num != vol: finished = False self.log_print(level=model.TradeMessageLog.ERROR, title='order_open_anyprice_error', message='{} order volume:{} , traded num:{}'.format(order_id,vol,num )) else: finished = True #限价->市价 均委托不成功,则报警并退出 if not finished: self.log_print(level=model.TradeMessageLog.INFO, title='order_open_error',message='委托失败, 关闭..') self.onTerminated() return #记录成交委托事件 data = OrderedDict(strategy_id=self.id, code=self.code, issue_time=datetime.datetime.now(), oc=stbase.Constants.Open, direction=direction, vol=volume) record = model.TradeOrder() object_assign(record, data, True) record.save() cs.open_date = datetime.datetime.now().replace(hour=0,minute=0,second=0,microsecond=0) # 记录开仓日期 cs.open_pos = volume # 记录开仓数量 cs.save() self.log_print(level=model.TradeMessageLog.INFO, title='order_open_okay', message='委托成功')