def makeTd(): td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(1) td.SubscribePrivateTopic(1) td.Init() return td
instlist = ['rb1905'] md = MyMdApi(instruments=instlist, broker_id=BROKER_ID, investor_id=INVESTOR_ID, password=PASSWORD) md.Create(INVESTOR_ID + "data") md.RegisterFront(ADDR_MD) md.Init() td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(2) td.SubscribePrivateTopic(2) td.Init() lastErrorID = 0 bkprofits = [] skprofits = [] sigprofit_info = [] posratio = [] skprofit = 0 bkprofit = 0 def today(): '''return today'''
def MovingBreak(): lastErrorID = 0 logfilename = BROKER_ID + '_' + INVESTOR_ID + '_交易日志' + str(today) + '.log' log = Logger(logfilename=logfilename) pc_grid = grid s = S = ApiStruct.D_Sell b = B = ApiStruct.D_Buy k = K = ApiStruct.OF_Open p = P = ApiStruct.OF_Close pj = PJ = ApiStruct.OF_CloseToday pz = PZ = ApiStruct.OF_CloseYesterday # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 # 登录行情服务器 md = MyMdApi(instruments=['rb1905'], broker_id=BROKER_ID, investor_id='*', password='******') md.Create(INVESTOR_ID + "data") md.RegisterFront(ADDR_MD) md.Init() td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(2) td.SubscribePrivateTopic(2) td.Init() last_time = None buy_order = 0 sell_order = 0 bp_total = 0 sp_total = 0 bk_limit = 1 sk_limit = 1 up_trader_flag = False down_trader_flag = False buy_rec = list() sell_rec = list() while True: if not q_server_info.empty(): info = q_server_info.get() # print info.ErrorID lastErrorID = info.ErrorID print('the last ErrorID is: ', lastErrorID) if lastErrorID != 0: # print 'release the api...' # td.Release() print(datetime.now(), 'reconnect the trading server.') del td sleep(60) td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(2) td.SubscribePrivateTopic(2) # td.ReqUserLogout() td.Init() sleep(60) if not q_depth_market_data.empty(): tick = q_depth_market_data.get() tickToBar(tick,granularity=180) D_open = tick.OpenPrice lastk = get_last_k_line(bars, inst, granularity) last_k_line = get_last_k_line(bars, inst, granularity) print((lastk, datetime.now())) O = get_k_line_column(bars, inst, granularity, ohlc='open') H = get_k_line_column(bars, inst, granularity, ohlc='high') L = get_k_line_column(bars, inst, granularity, ohlc='low') C = get_k_line_column(bars, inst, granularity, ohlc='close') # print(H[-3:],L[-3:], type(H[-1])) HL = HLV(H, L) MHL = max(HL) MminHL = min(HL) AVHL = sum(HL) / len(HL) vgrid = int(AVHL * 0.8) # calculate the uppper and lower band HV = HHV(H, 23) LV = LLV(L, 23) # #middle line Mid = MID(HV, LV) # 根据叮当值调整仓位控制参数 # bk_limit = 2 if C[-1] > Mid[-1] else 0 # bk_limit = 2 # sk_limit = 2 if C[-1] < Mid[-1] else 0 # sk_limit = 2 # print tick.InstrumentID, strategy_inst if lastk is not None and tick.InstrumentID == strategy_inst: if last_time != last_k_line['date_time']: last_time = last_k_line['date_time'] up_trader_flag = False down_trader_flag = False dingdang = 'Buy!' if tick.LastPrice > Mid[-1] else 'Sell' bkvol = buy_order - sp_total if buy_order - sp_total > 0 else 0 skvol = sell_order - bp_total if sell_order - bp_total > 0 else 0 # bkvol = get_day_bkvol(td, strategy_inst) # skvol = get_day_skvol(td, strategy_inst) # outformat = "当前时间:{tick.UpdateTime}, High:{last_k_line['high']}" # print(outformat) print('当前时间: ', tick.UpdateTime, 'HIGH:', last_k_line['high'], ' ', 'LOW:', last_k_line[ 'low'], '当前价: ', tick.LastPrice, '叮当值:', Mid[ -1], dingdang, 'buy_limit:', bk_limit, 'sell_limit:', sk_limit) print('buy_order: ', buy_order, 'sell_order: ', sell_order, BROKER_ID, INVESTOR_ID, tick.InstrumentID, 'sp_total: ', sp_total, 'bp_total: ', bp_total, '日多:', bkvol, '日空:', skvol) if not up_trader_flag and tick.LastPrice > last_k_line['high'] and bkvol < bk_limit: # 下多单 print(bkvol, bk_limit) up_trader_flag = True order_price = tick.LastPrice buy_rec.append([datetime.now(), order_price]) # if sell_order > 0: # td.PrepareOrder(tick.InstrumentID, B, P, sell_order, order_price) # sell_order -= sell_order td.PrepareOrder(tick.InstrumentID, b, k, single_volume, order_price) log.info(log.printfNow() + '下空单:' + str(single_volume) + ',orderprice:' + str( order_price) + 'skvol:' + str(skvol) + 'sk_limit:' + str(sk_limit)) # td.PrepareOrder(tick.InstrumentID, s, pz, single_volume, tick.LastPrice) info = 'buy: ' + tick.InstrumentID +' '+ str(order_price) mailsender(info, receivers) print('下多单', tick.InstrumentID, INVESTOR_ID, str(single_volume) + ',orderprice:' + str( order_price) + 'skvol:' + str(skvol) + 'sk_limit:' + str(sk_limit)) print('lastHigh:', last_k_line['high'], 'lastLow: ', last_k_line[ 'low'], 'lastPrice: ', tick.LastPrice) if not down_trader_flag and tick.LastPrice < last_k_line['low'] and skvol < sk_limit: # 下空单 down_trader_flag = True order_price = tick.LastPrice # if buy_order > 0: # td.PrepareOrder(tick.InstrumentID, S, P, buy_order, tick.LastPrice - pc_grid) # buy_order -= buy_order td.PrepareOrder(tick.InstrumentID, s, k, single_volume, order_price) log.info(log.printfNow() + '下空单:' + str(single_volume) + ',orderprice:' + str( order_price) + 'skvol:' + str(skvol) + 'sk_limit:' + str(sk_limit)) # td.PrepareOrder(tick.InstrumentID, b, pz, single_volume, tick.LastPrice) info = 'sell: ' + tick.InstrumentID + ' ' + str(order_price) mailsender(info, receivers) print('下空单', tick.InstrumentID, INVESTOR_ID, ', orderprice:' + str(order_price) + ', skvol:' + str( skvol) + ', sk_limit:' + str(sk_limit)) print('lastHigh:', last_k_line['high'], 'lastLow: ', last_k_line[ 'low'], 'lastPrice: ', tick.LastPrice) if not q_bar.empty(): bartmp = q_bar.get() bars[barinterval].append(bartmp) if not q_rtn_order.empty(): rtn_order = q_rtn_order.get() print(rtn_order) print('下单成功,请注意。。。') if not q_rtn_trade.empty(): rtn_td = q_rtn_trade.get() print('下单成交', rtn_td) ''' Trade(BrokerID='0127', InvestorID='200277', InstrumentID='ni1811', OrderRef='69169', UserID='200277', ExchangeID='SHFE', TradeID=' 652868', Direction='0', OrderSysID=' 2413585', ParticipantID='0011', ClientID='01789993', TradingRole='\x00', ExchangeInstID='ni1811', OffsetFlag='0', HedgeFlag='1', Price=112560.0, Volume=1, TradeDate='20180727', TradeTime='23:52:48', TradeType='\x00', PriceSource='\x00', TraderID='0011c6c', OrderLocalID=' 684', ClearingPartID='0011', BusinessUnit='', SequenceNo=1536, TradingDay='20180730', SettlementID=1, BrokerOrderSeq=2310, TradeSource='0') ''' # k if rtn_td.Direction == B: # 方向 多 if rtn_td.OffsetFlag == K and rtn_td.InstrumentID == strategy_inst: # 多单开仓成交,下平仓指令, 开盘价+30 buy_order += rtn_td.Volume order_price = rtn_td.Price + grid bkvol += rtn_td.Volume td.PrepareOrder(rtn_td.InstrumentID, s, pj, rtn_td.Volume, order_price) info = tick.InstrumentID + '多单建仓成交,平仓单挂单。。。' + str(order_price) print(info) # mailsender(info, receivers) elif rtn_td.OffsetFlag in [P, PJ, PZ] and rtn_td.InstrumentID == strategy_inst: # 平仓, print(rtn_td) bp_total += rtn_td.Volume sell_order -= rtn_td.Volume skvol -= rtn_td.Volume info = '平仓单成交。。。' print(info) # mailsender(info,receivers) elif rtn_td.Direction == S: # 方向:空 if rtn_td.OffsetFlag == K and rtn_td.InstrumentID == strategy_inst: # 开仓 # 空单建仓成交 sell_order += rtn_td.Volume skvol += rtn_td.Volume order_price = rtn_td.Price - grid td.PrepareOrder(rtn_td.InstrumentID, b, pj, rtn_td.Volume, order_price) info = '空单建仓成交,平仓单挂单。。。' print(info) # mailsender(info, receivers) elif rtn_td.OffsetFlag in [P, PJ, PZ] and rtn_td.InstrumentID == strategy_inst: sp_total += rtn_td.Volume buy_order -= rtn_td.Volume bkvol -= rtn_td.Volume info = '平仓单成交' + str(rtn_td.TradeTime)+ rtn_td.InstrumentID print(info) # mailsender(info, receivers) print(rtn_td.TradeTime, rtn_td.InstrumentID)
def main(): # account_base =r'conf' # # master2 = r'CTP_tgjy_thm.json' # master_user = getAccountinfo(master2) # master_user = accounts724['sim2'] follow_user = accounts_simstd['sim1'] fltd = MyTradeApi(broker_id=follow_user['broker_id'], investor_id=follow_user['investor_id'], passwd=follow_user['passwd']) fltd.Create("fltd_trader") fltd.RegisterFront(follow_user['addr_td']) fltd.SubscribePublicTopic(1) fltd.SubscribePrivateTopic(1) fltd.Init() # mastertd = MyTradeApi(broker_id=master_user['broker_id'], investor_id=master_user['investor_id'], passwd=master_user['passwd']) mastertd = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) mastertd.Create("master_trader") mastertd.RegisterFront(ADDR_TD) mastertd.SubscribePublicTopic(2) mastertd.SubscribePrivateTopic(2) mastertd.Init() master_order_list = [] follow_order_list = [] while True: time.sleep(0.2) if not mastertd.q_order.empty(): order = mastertd.q_order.get() print(order) print(order.StatusMsg.decode('gbk'), order.OrderStatus) print((order.InsertTime, order.ActiveTime, order.UpdateTime, order.SuspendTime, order.CancelTime)) if order.OrderStatus == '5': print('主账户撤单成功:', order.InvestorID, order.InstrumentID, order.OrderRef, from_ctp_direction(order.Direction), from_ctp_offsetflag(order.CombOffsetFlag), order.CombOffsetFlag, order.LimitPrice, order.VolumeTotalOriginal) print(order.ExchangeID, order.OrderSysID) if order.OrderStatus == '3': print('主账户下单成功:', order.InvestorID, order.InstrumentID, order.OrderRef, from_ctp_direction(order.Direction), from_ctp_offsetflag(order.CombOffsetFlag), order.CombOffsetFlag, order.LimitPrice, order.VolumeTotalOriginal) print(order.ExchangeID, order.OrderSysID) instid = order.InstrumentID Direction = order.Direction CombOffsetFlag = order.CombOffsetFlag order_price = int(order.LimitPrice) order_volume = order.VolumeTotal order_ref = order.OrderRef # 子账户下单 考虑子账户用主账户的orderRef, 需要修改ctpapi. fltd.PrepareOrder(instid, Direction, CombOffsetFlag, order_volume, order_price) if not fltd.q_order.empty(): forder = fltd.q_order.get() print(forder) if forder.OrderStatus == '3': print('子账户下单成功', forder.InvestorID, forder.InstrumentID, forder.OrderRef, from_ctp_direction(forder.Direction), from_ctp_offsetflag(forder.CombOffsetFlag), forder.LimitPrice, forder.VolumeTotalOriginal) print(forder.ExchangeID, forder.OrderSysID) '''
def tradingRecorder(account): #accont 为ctp账号文件 try: BROKER_ID, INVESTOR_ID, PASSWORD, ADDR_MD, ADDR_TD = getAccountinfo( account) except: print('account file error of not existing... quit!') return global lastErrorID today = datetime.now().strftime("%Y-%m-%d") logfilename = BROKER_ID + '_' + INVESTOR_ID + '_交易日志' + str(today) + '.log' # log = Logger(logfilename=logfilename) # config = incept_config() # load_data_from_file() # init_k_line_pump() # # workdays = TradingPeriod.get_workdays(begin=config['begin'], end=config['end']) # workdays_exchange_trading_period_by_ts = \ # TradingPeriod.get_workdays_exchange_trading_period( # _workdays=workdays, exchange_trading_period=EXCHANGE_TRADING_PERIOD) # # if workdays_exchange_trading_period_by_ts.has_key(today): # trading_period_by_ts = workdays_exchange_trading_period_by_ts[today] # else: # print('Not trading day, return to system.') # return # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 # 登录行情服务器 # md = MyMdApi(instruments=inst, broker_id=BROKER_ID, investor_id=INVESTOR_ID, password=PASSWORD) # md.Create(INVESTOR_ID + "data") # md.RegisterFront(ADDR_MD) # md.Init() print(('-' * 50)) td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(0) td.SubscribePrivateTopic(0) td.Init() # dt = td.getTradingday() # 初始化日志文件 with open(logfilename, 'w') as f: print('initializing log file.') # td. Release() # td.ReqUserlogout() # tt = getPos(td,strategy_inst) # print tt while True: # td.fetch_investor_position_detail('SM905') if not q_server_info.empty(): info = q_server_info.get() # print info.ErrorID lastErrorID = info.ErrorID print('the last ErrorID is: ', lastErrorID, INVESTOR_ID, BROKER_ID) if lastErrorID != 0: # print 'release the api...' # td.Release() print('reconnect the trading server.') del td td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(0) td.SubscribePrivateTopic(0) # td.ReqUserLogout() td.Init() sleep(60) if not q_rtn_order.empty(): rtn_order = q_rtn_order.get() print(rtn_order.OrderRef, rtn_order, '\n') print(rtn_order.InstrumentID, rtn_order.Direction, rtn_order.CombOffsetFlag, rtn_order.LimitPrice, rtn_order.VolumeTotalOriginal, rtn_order.OrderSubmitStatus, rtn_order.VolumeTraded, rtn_order.VolumeTotal, rtn_order.InsertTime, end=' ') orderList.append(rtn_order), '\n' if len(orderList) > 0: with open(logfilename, 'a') as f: for ord in orderList[:]: f.writelines(str(ord) + '\n') orderList.remove(ord) # f.writelines(json.dumps(ord, ensure_ascii=False) + '\n') if not q_rtn_trade.empty(): rtn_trade = q_rtn_trade.get() print(rtn_trade)
def DingDangNo6(): logfilename = BROKER_ID + '_' + INVESTOR_ID + '_交易日志' + str(today) + '.log' log = Logger(logfilename=logfilename) config = incept_config() load_data_from_file() init_k_line_pump() workdays = TradingPeriod.get_workdays(begin=config['begin'], end=config['end']) workdays_exchange_trading_period_by_ts = \ TradingPeriod.get_workdays_exchange_trading_period( _workdays=workdays, exchange_trading_period=EXCHANGE_TRADING_PERIOD) inst = 'rb1905' granularity = 780 serverport = 'http://192.168.1.19:8008' bars = dict() barss = load_data_from_server(server_base=serverport, instruments_id=inst, granularity=granularity) barinterval = inst + '_' + str(granularity) bars[barinterval] = barss if today in workdays_exchange_trading_period_by_ts: trading_period_by_ts = workdays_exchange_trading_period_by_ts[today] else: print('Not trading day, return to system.') return pc_grid = grid s = S = ApiStruct.D_Sell b = B = ApiStruct.D_Buy k = K = ApiStruct.OF_Open p = P = ApiStruct.OF_Close pj = PJ = ApiStruct.OF_CloseToday pz = PZ = ApiStruct.OF_CloseYesterday # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 # 登录行情服务器 md = MyMdApi(instruments=inst, broker_id=BROKER_ID, investor_id=INVESTOR_ID, password=PASSWORD) md.Create(INVESTOR_ID + "data") md.RegisterFront(ADDR_MD) md.Init() td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(1) td.SubscribePrivateTopic(1) td.Init() last_time = None up_trader_flag = False down_trader_flag = False while True: if not q_depth_market_data.empty(): tick = q_depth_market_data.get() sewing_data_to_file_and_depositary(depth_market_data=tick) last_k_line = get_last_k_line(instrument_id=inst[0], interval=period) DayOpen = tick.OpenPrice DayHigh = tick.HighestPrice DayLow = tick.LowestPrice H = get_k_line_column(strategy_inst, strategy_period, ohlc='high') L = get_k_line_column(strategy_inst, strategy_period, ohlc='low') C = get_k_line_column(strategy_inst, strategy_period, ohlc='close') HL = HLV(H, L) MHL = max(HL) MminHL = min(HL) AVHL = sum(HL) / len(HL) vgrid = int(AVHL * 0.8) # calculate the uppper and lower band HV = HHV(H, 23) LV = LLV(L, 23) # #middle line DingDang = MID(HV, LV) allsig = cross(C, DingDang)[0] * 2 if last_k_line is not None and tick.InstrumentID == strategy_inst: if last_time != last_k_line['date_time']: last_time = last_k_line['date_time'] up_trader_flag = False down_trader_flag = False dingdang = 'Buy!' if tick.LastPrice > Mid[-1] else 'Sell' bkvol = buy_order - sp_total if buy_order - sp_total > 0 else 0 skvol = sell_order - bp_total if sell_order - bp_total > 0 else 0 # bkvol = get_day_bkvol(td, strategy_inst) # skvol = get_day_skvol(td, strategy_inst) print('当前时间: ', tick.UpdateTime, 'HIGH:', last_k_line['high'], ' ', 'LOW:', last_k_line['low'], '当前价: ', tick.LastPrice, '叮当值:', Mid[-1], dingdang, 'buy_limit:', bk_limit, 'sell_limit:', sk_limit) print('buy_order: ', buy_order, 'sell_order: ', sell_order, BROKER_ID, INVESTOR_ID, tick.InstrumentID, 'sp_total: ', sp_total, 'bp_total: ', bp_total, '日多:', bkvol, '日空:', skvol) if (not up_trader_flag and not last_k_line['low'] == last_k_line['high']) and tick.LastPrice > \ last_k_line['high'] and tick.LastPrice - last_k_line['high'] < 30 and bkvol < bk_limit: # 下多单 print(bkvol, bk_limit) up_trader_flag = True order_price = tick.LastPrice buy_rec.append([datetime.now(), order_price]) # if sell_order > 0: # td.PrepareOrder(tick.InstrumentID, B, P, sell_order, tick.LastPrice + pc_grid) # sell_order -= sell_order td.PrepareOrder(tick.InstrumentID, b, k, single_volume, order_price) log.info(log.printfNow() + '下空单:' + str(single_volume) + ',orderprice:' + str(order_price) + 'skvol:' + str(skvol) + 'sk_limit:' + str(sk_limit)) # td.PrepareOrder(tick.InstrumentID, s, pz, single_volume, tick.LastPrice) print() print( '下多单', tick.InstrumentID, INVESTOR_ID, str(single_volume) + ',orderprice:' + str(order_price) + 'skvol:' + str(skvol) + 'sk_limit:' + str(sk_limit)) print('lastHigh:', last_k_line['high'], 'lastLow: ', last_k_line['low'], 'lastPrice: ', tick.LastPrice) if (not down_trader_flag and not last_k_line['low'] == last_k_line['high']) and tick.LastPrice < \ last_k_line['low'] and (last_k_line['low'] - tick.LastPrice < 30) and skvol < sk_limit: # 下空单 down_trader_flag = True order_price = tick.LastPrice # if buy_order > 0: # td.PrepareOrder(tick.InstrumentID, S, P, buy_order, tick.LastPrice - pc_grid) # # buy_order -= buy_order td.PrepareOrder(tick.InstrumentID, s, k, single_volume, order_price) log.info(log.printfNow() + '下空单:' + str(single_volume) + ',orderprice:' + str(order_price) + 'skvol:' + str(skvol) + 'sk_limit:' + str(sk_limit)) # td.PrepareOrder(tick.InstrumentID, b, pz, single_volume, tick.LastPrice) print() print( '下空单', tick.InstrumentID, INVESTOR_ID, ', orderprice:' + str(order_price) + ', skvol:' + str(skvol) + ', sk_limit:' + str(sk_limit)) print('lastHigh:', last_k_line['high'], 'lastLow: ', last_k_line['low'], 'lastPrice: ', tick.LastPrice) if not q_rtn_order.empty(): rtn_order = q_rtn_order.get() print(rtn_order) print('下单成功,请注意。。。') if not q_rtn_trade.empty(): rtn_td = q_rtn_trade.get() print(rtn_td) ''' Trade(BrokerID='0127', InvestorID='200277', InstrumentID='ni1811', OrderRef='69169', UserID='200277', ExchangeID='SHFE', TradeID=' 652868', Direction='0', OrderSysID=' 2413585', ParticipantID='0011', ClientID='01789993', TradingRole='\x00', ExchangeInstID='ni1811', OffsetFlag='0', HedgeFlag='1', Price=112560.0, Volume=1, TradeDate='20180727', TradeTime='23:52:48', TradeType='\x00', PriceSource='\x00', TraderID='0011c6c', OrderLocalID=' 684', ClearingPartID='0011', BusinessUnit='', SequenceNo=1536, TradingDay='20180730', SettlementID=1, BrokerOrderSeq=2310, TradeSource='0') ''' # k if rtn_td.Direction == B: # 方向 多 if rtn_td.OffsetFlag == K and rtn_td.InstrumentID == strategy_inst: # 多单开仓成交,下平仓指令, 开盘价+30 buy_order += rtn_td.Volume order_price = rtn_td.Price + grid td.PrepareOrder(rtn_td.InstrumentID, s, pj, rtn_td.Volume, order_price) print('多单建仓成交,平仓单挂单。。。') elif rtn_td.OffsetFlag in [ P, PJ, PZ ] and rtn_td.InstrumentID == strategy_inst: # 平仓, bp_total += rtn_td.Volume elif rtn_td.Direction == S: # 方向:空 if rtn_td.OffsetFlag == K and rtn_td.InstrumentID == strategy_inst: # 开仓 # 空单建仓成交 sell_order += rtn_td.Volume order_price = rtn_td.Price - grid td.PrepareOrder(rtn_td.InstrumentID, b, pj, rtn_td.Volume, order_price) print('空单建仓成交,平仓单挂单。。。') elif rtn_td.OffsetFlag in [ P, PJ, PZ ] and rtn_td.InstrumentID == strategy_inst: sp_total += rtn_td.Volume print(rtn_td.TradeTime, rtn_td.InstrumentID)
def Strategy_fairy_std(): pc_grid = grid s = S = ApiStruct.D_Sell b = B = ApiStruct.D_Buy k = K = ApiStruct.OF_Open p = P = ApiStruct.OF_Close pj = PJ = ApiStruct.OF_CloseToday pz = PZ = ApiStruct.OF_CloseYesterday # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 # 登录行情服务器 md = MyMdApi(instruments=inst, broker_id=BROKER_ID, investor_id=INVESTOR_ID, password=PASSWORD) md.Create(INVESTOR_ID + "data") md.RegisterFront(ADDR_MD) md.Init() td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(1) td.SubscribePrivateTopic(1) td.Init() last_time = None buy_order = 0 sell_order = 0 up_trader_flag = False down_trader_flag = False while True: if not q_depth_market_data.empty(): tick = q_depth_market_data.get() sewing_data_to_file_and_depositary(depth_market_data=tick) last_k_line = get_last_k_line(instrument_id=inst[0], interval=period) # print last_k_line['low'], last_k_line['high'], tick.LastPrice if last_k_line is not None and tick.InstrumentID == strategy_inst: if last_time != last_k_line['date_time']: last_time = last_k_line['date_time'] up_trader_flag = False down_trader_flag = False print u'当前时间: ', tick.UpdateTime, u'HIGH: ', last_k_line[ 'high'], u'LOW: ', last_k_line[ 'low'], u'当前价: ', tick.LastPrice print u'buy_order: ', buy_order, u'sell_order: ', sell_order, BROKER_ID, INVESTOR_ID, tick.InstrumentID if (not up_trader_flag and not last_k_line['low'] == last_k_line['high'] ) and tick.LastPrice > last_k_line[ 'high'] and buy_order <= buy_limit: # 下多单 up_trader_flag = True # if sell_order > 0: # td.PrepareOrder(tick.InstrumentID, B, P, sell_order, tick.LastPrice + pc_grid) # sell_order -= sell_order td.PrepareOrder(tick.InstrumentID, b, k, single_volume, tick.LastPrice - 30) buy_order += single_volume td.PrepareOrder(tick.InstrumentID, s, pj, single_volume, tick.LastPrice + 30) pc_grid -= step pc_grid = max(6, pc_grid) print print u'下多单', tick.InstrumentID, INVESTOR_ID print u'lastHigh:', last_k_line[ 'high'], u'lastLow: ', last_k_line[ 'low'], 'lastPrice: ', tick.LastPrice # if (not down_trader_flag and not last_k_line['low'] == last_k_line['high']) and tick.LastPrice < last_k_line['low']: # # 下空单 # down_trader_flag = True # # # if buy_order > 0: # # td.PrepareOrder(tick.InstrumentID, S, P, buy_order, tick.LastPrice - pc_grid) # # # # buy_order -= buy_order # # td.PrepareOrder(tick.InstrumentID, s, k, single_volume, tick.LastPrice) # sell_order += single_volume # # td.PrepareOrder(tick.InstrumentID, b, pj, single_volume, tick.LastPrice - 4) # # pc_grid -= step # pc_grid = max(6, pc_grid) # # print # print u'下空单', tick.InstrumentID, INVESTOR_ID # print u'lastHigh:', last_k_line['high'], u'lastLow: ', last_k_line['low'], 'lastPrice: ', tick.LastPrice # if not q_rtn_trade.empty(): rtn_td = q_rtn_trade.get() print rtn_td ''' Trade(BrokerID='0127', InvestorID='200277', InstrumentID='ni1811', OrderRef='69169', UserID='200277', ExchangeID='SHFE', TradeID=' 652868', Direction='0', OrderSysID=' 2413585', ParticipantID='0011', ClientID='01789993', TradingRole='\x00', ExchangeInstID='ni1811', OffsetFlag='0', HedgeFlag='1', Price=112560.0, Volume=1, TradeDate='20180727', TradeTime='23:52:48', TradeType='\x00', PriceSource='\x00', TraderID='0011c6c', OrderLocalID=' 684', ClearingPartID='0011', BusinessUnit='', SequenceNo=1536, TradingDay='20180730', SettlementID=1, BrokerOrderSeq=2310, TradeSource='0') ''' print rtn_td.TradeTime, rtn_td.InstrumentID time.sleep(0.2)
def Strategy_fairy_std(): pc_grid = grid s = S = ApiStruct.D_Sell b = B = ApiStruct.D_Buy k = K = ApiStruct.OF_Open p = P = ApiStruct.OF_Close pj = PJ = ApiStruct.OF_CloseToday pz = PZ = ApiStruct.OF_CloseYesterday # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 # 登录行情服务器 md = MyMdApi(instruments=inst, broker_id=BROKER_ID, investor_id=INVESTOR_ID, password=PASSWORD) md.Create(INVESTOR_ID+"data") md.RegisterFront(ADDR_MD) md.Init() td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(1) td.SubscribePrivateTopic(1) td.Init() last_time = None buy_order = 0 sell_order = 0 up_trader_flag = False down_trader_flag = False while True: if not q_depth_market_data.empty(): tick = q_depth_market_data.get() sewing_data_to_file_and_depositary(depth_market_data=tick) last_k_line = get_last_k_line(instrument_id=inst[0], interval= period) # print last_k_line['low'], last_k_line['high'], tick.LastPrice if last_k_line is not None and tick.InstrumentID == strategy_inst: if last_time != last_k_line['date_time']: last_time = last_k_line['date_time'] up_trader_flag = False down_trader_flag = False print u'当前时间: ',tick.UpdateTime,u'HIGH: ',last_k_line['high'],u'LOW: ', last_k_line['low'], u'当前价: ', tick.LastPrice print u'buy_order: ', buy_order, u'sell_order: ', sell_order, BROKER_ID, INVESTOR_ID, tick.InstrumentID if (not up_trader_flag and not last_k_line['low'] == last_k_line['high']) and tick.LastPrice > last_k_line['high']: # 下多单 up_trader_flag = True # if sell_order > 0: # td.PrepareOrder(tick.InstrumentID, B, P, sell_order, tick.LastPrice + pc_grid) # sell_order -= sell_order td.PrepareOrder(tick.InstrumentID, b, k, single_volume, tick.LastPrice) buy_order += single_volume td.PrepareOrder(tick.InstrumentID, s, pj, single_volume, tick.LastPrice + 5) pc_grid -= step pc_grid = max(6,pc_grid) print print u'下多单', tick.InstrumentID, INVESTOR_ID print u'lastHigh:', last_k_line['high'], u'lastLow: ',last_k_line['low'], 'lastPrice: ', tick.LastPrice if (not down_trader_flag and not last_k_line['low'] == last_k_line['high']) and tick.LastPrice < last_k_line['low']: # 下空单 down_trader_flag = True # if buy_order > 0: # td.PrepareOrder(tick.InstrumentID, S, P, buy_order, tick.LastPrice - pc_grid) # # buy_order -= buy_order td.PrepareOrder(tick.InstrumentID, s, k, single_volume, tick.LastPrice) sell_order += single_volume td.PrepareOrder(tick.InstrumentID, b, pj, single_volume, tick.LastPrice - 4) pc_grid -= step pc_grid = max(6, pc_grid) print print u'下空单', tick.InstrumentID, INVESTOR_ID print u'lastHigh:', last_k_line['high'], u'lastLow: ', last_k_line['low'], 'lastPrice: ', tick.LastPrice if not q_rtn_trade.empty(): rtn_td = q_rtn_trade.get() print rtn_td print rtn_td.TradeTime, rtn_td.InstrumentID time.sleep(0.2)
def dingdang_three(): config = incept_config() load_data_from_file() init_k_line_pump() workdays = TradingPeriod.get_workdays(begin=config['begin'], end=config['end']) workdays_exchange_trading_period_by_ts = \ TradingPeriod.get_workdays_exchange_trading_period( _workdays=workdays, exchange_trading_period=EXCHANGE_TRADING_PERIOD) pc_grid = grid s = S = ApiStruct.D_Sell b = B = ApiStruct.D_Buy k = K = ApiStruct.OF_Open p = P = ApiStruct.OF_Close pj = PJ = ApiStruct.OF_CloseToday pz = PZ = ApiStruct.OF_CloseYesterday # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 # 登录行情服务器 md = MyMdApi(instruments=inst, broker_id=BROKER_ID, investor_id=INVESTOR_ID, password=PASSWORD) md.Create(INVESTOR_ID + "data") md.RegisterFront(ADDR_MD) md.Init() td = MyTradeApi(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD) td.Create(LOGS_DIR + INVESTOR_ID + "_trader") td.RegisterFront(ADDR_TD) td.SubscribePublicTopic(1) td.SubscribePrivateTopic(1) td.Init() last_time = None buy_order = 0 sell_order = 0 bp_total = 0 sp_total = 0 bk_limit = 0 sk_limit = 2 up_trader_flag = False down_trader_flag = False while True: if not q_depth_market_data.empty(): tick = q_depth_market_data.get() sewing_data_to_file_and_depositary(depth_market_data=tick) last_k_line = get_last_k_line(instrument_id=inst[0], interval=strategy_period) D_open = tick.OpenPrice H = get_k_line_column(strategy_inst, strategy_period, ohlc='high') L = get_k_line_column(strategy_inst, strategy_period, ohlc='low') C = get_k_line_column(strategy_inst, strategy_period, ohlc='close') if last_k_line is not None and tick.InstrumentID == strategy_inst: HL = HLV(H, L) MHL = max(HL) MminHL = min(HL) AVHL = sum(HL) / len(HL) vgrid = int(AVHL * 0.8) # calculate the uppper and lower band HV = HHV(H, 23) LV = LLV(L, 23) # #middle line Mid = MID(HV, LV) ups = crossup(C, Mid) dns = crossup(Mid, C) avp = len(ups) / (ups.count(True) + dns.count(True)) uptotal = ups.count(True) dntotal = dns.count(True) print(ups.count(True), dns.count(True), avp) print('Mid:', Mid[-23:]) print('C:', C[-23:]) print('ups:', ups[-23:]) print('dns:', dns[-23:]) print() if last_time != last_k_line['date_time']: last_time = last_k_line['date_time'] up_trader_flag = False down_trader_flag = False dingdang = 'Buy!' if tick.LastPrice > Mid[-1] else 'Sell' bkvol = buy_order - sp_total if buy_order - sp_total > 0 else 0 skvol = sell_order - bp_total if sell_order - bp_total > 0 else 0 # bkvol = get_day_bkvol(td, strategy_inst) # skvol = get_day_skvol(td, strategy_inst) print('当前时间: ', tick.UpdateTime, 'HIGH:', last_k_line['high'], ' ', 'LOW:', last_k_line['low'], '当前价: ', tick.LastPrice, '叮当值:', Mid[-1], dingdang) print('buy_order: ', buy_order, 'sell_order: ', sell_order, BROKER_ID, INVESTOR_ID, tick.InstrumentID, 'sp_total: ', sp_total, 'bp_total: ', bp_total, '日多:', bkvol, '日空:', skvol) if ups[-1] and not up_trader_flag: # 下多单 print(bkvol, bk_limit) up_trader_flag = True # if sell_order > 0: # td.PrepareOrder(tick.InstrumentID, B, PJ, sell_order, tick.LastPrice + pc_grid) td.PrepareOrder(tick.InstrumentID, b, k, single_volume, tick.LastPrice) print() print('下多单', tick.InstrumentID, INVESTOR_ID) print('lastHigh:', last_k_line['high'], 'lastLow: ', last_k_line['low'], 'lastPrice: ', tick.LastPrice) if dns[-1] and not down_trader_flag: # 下空单 down_trader_flag = True # if buy_order > 0: # td.PrepareOrder(tick.InstrumentID, S, PJ, buy_order, tick.LastPrice) td.PrepareOrder(tick.InstrumentID, s, k, single_volume, tick.LastPrice) print() print('做空信号发出,下空单', tick.InstrumentID, INVESTOR_ID) print('lastHigh:', last_k_line['high'], 'lastLow: ', last_k_line['low'], 'lastPrice: ', tick.LastPrice) if not q_rtn_order.empty(): rtn_order = q_rtn_order.get() print(rtn_order) print('下单成功,请注意。。。') if not q_rtn_trade.empty(): rtn_td = q_rtn_trade.get() print(rtn_td) ''' Trade(BrokerID='0127', InvestorID='200277', InstrumentID='ni1811', OrderRef='69169', UserID='200277', ExchangeID='SHFE', TradeID=' 652868', Direction='0', OrderSysID=' 2413585', ParticipantID='0011', ClientID='01789993', TradingRole='\x00', ExchangeInstID='ni1811', OffsetFlag='0', HedgeFlag='1', Price=112560.0, Volume=1, TradeDate='20180727', TradeTime='23:52:48', TradeType='\x00', PriceSource='\x00', TraderID='0011c6c', OrderLocalID=' 684', ClearingPartID='0011', BusinessUnit='', SequenceNo=1536, TradingDay='20180730', SettlementID=1, BrokerOrderSeq=2310, TradeSource='0') ''' #k if rtn_td.Direction == B: # 方向 多 if rtn_td.OffsetFlag == K and rtn_td.InstrumentID == strategy_inst: #多单开仓成交,下平仓指令, 开盘价+30 buy_order += rtn_td.Volume order_price = rtn_td.Price + grid # td.PrepareOrder(rtn_td.InstrumentID, s, pj, rtn_td.Volume, order_price) print('多单建仓成交,平仓单挂单。。。') elif rtn_td.OffsetFlag in [ P, PJ, PZ ] and rtn_td.InstrumentID == strategy_inst: #平仓, bp_total += rtn_td.Volume elif rtn_td.Direction == S: #方向:空 if rtn_td.OffsetFlag == K and rtn_td.InstrumentID == strategy_inst: # 开仓 #空单建仓成交 sell_order += rtn_td.Volume order_price = rtn_td.Price - grid # td.PrepareOrder(rtn_td.InstrumentID, b, pj, rtn_td.Volume, order_price) print('空单建仓成交,平仓单挂单。。。') elif rtn_td.OffsetFlag in [ P, PJ, PZ ] and rtn_td.InstrumentID == strategy_inst: sp_total += rtn_td.Volume print(rtn_td.TradeTime, rtn_td.InstrumentID)