Example #1
0
            }
            q_signals.put(signal)

            knum = len(H)
            signalall = buysigdetail.count(True)
            avsigp = knum / signalall
            sigsum2 = buysigdetail[(knum - avsigp):-2].count(
                True) + sellsigdetail[(knum - avsigp):-2].count(True)
            sigsum3 = sigsum2 * 2

            pp = min((sigsum3 + 1), 8)

            order_price = tick.LastPrice

            # td.PrepareOrder(tick.InstrumentID, b, k, pp, order_price)
            log.info(log.printfNow() + '下多单:' + str(pp) + ',orderprice:' +
                     str(order_price))

            print('buy order issued.')

        if sellsigdetail[-1]:
            initFund += bkprofit * pp * instMultifier
            skprofits = []
            signal = {
                'date_time': time.time(),
                'signaltype': 'SK',
                'signalprice': tick.LastPrice
            }
            q_signals.put(signal)

            order_price = tick.LastPrice
Example #2
0
class Trader(TraderApi):
    def __init__(self,
                 broker_id,
                 investor_id,
                 password,
                 appid,
                 authcode,
                 productinfo,
                 request_id=1):
        self.request_id = request_id
        self.broker_id = broker_id.encode()
        self.investor_id = investor_id.encode()
        self.password = password.encode()
        self.appid = appid.encode()
        self.authcode = authcode.encode()
        self.productinfo = productinfo
        self.q_order = Queue.Queue()
        self.logger = Logger()

    @staticmethod
    def is_error_rsp_info(info):
        # print info
        if info.ErrorID != 0:
            print "ErrorID=", info.ErrorID, ", ErrorMsg=", info.ErrorMsg.decode(
                'gbk')
        return info.ErrorID != 0

    def OnRspError(self, pRspInfo, nRequestID, bIsLast):

        self.ErrorRspInfo(pRspInfo, nRequestID)

    def ErrorRspInfo(self, info, request_id):
        """
        :param info:
        :return:
        """
        if info.ErrorID != 0:
            print('request_id=%s ErrorID=%d, ErrorMsg=%s', request_id,
                  info.ErrorID, info.ErrorMsg.decode('gbk'))
        return info.ErrorID != 0

    def OnHeartBeatWarning(self, nTimeLapse):
        """心跳超时警告。当长时间未收到报文时,该方法被调用。
        @param nTimeLapse 距离上次接收报文的时间
        """
        print("on OnHeartBeatWarning time: ", nTimeLapse)

    def OnFrontDisconnected(self, nReason):
        print("on FrontDisConnected disconnected", nReason)

    def OnFrontConnected(self):
        print('Front connected....')
        req = ApiStruct.ReqAuthenticate(
            BrokerID=self.broker_id,
            UserID=self.investor_id,
            UserProductInfo="client_vnpy",
            # Password=self.password,
            AppID=self.appid,
            AuthCode=self.authcode)

        r = self.ReqAuthenticate(req, self.inc_request_id())
        print(r)
        print('Req Authenticate finished...')
        time.sleep(3)

        # req = ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
        #                                      UserID=self.investor_id,
        #                                      Password=self.password)
        # self.ReqUserLogin(req, self.request_id)
        # print("trader on front connection")
    def OnRspAuthenticate(self, pRspAuthenticateField, pRspInfo, nRequestID,
                          bIsLast):
        # print(pRspAuthenticateField.AppType)

        info.append(copy.deepcopy(pRspAuthenticateField))
        print('client authenticate done. Req User login....')
        time.sleep(3)
        req = ApiStruct.ReqUserLogin(BrokerID=self.broker_id,
                                     UserID=self.investor_id,
                                     Password=self.password)
        r = self.ReqUserLogin(req, self.inc_request_id())
        print(r)

    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):

        print('系统登录完成。user login done.')
        print datetime.datetime.now(
        ), u"登录交易服务器...", bIsLast, pRspInfo.ErrorMsg.decode('gbk')
        print datetime.datetime.now(), 'user_login:'******'交易服务器登录成功。', pRspUserLogin.BrokerID, pRspUserLogin.UserID

            # Logger.info('OnRspUserLogin %s' % is_last)
            req = ApiStruct.SettlementInfoConfirm(BrokerID=self.broker_id,
                                                  InvestorID=self.investor_id)
            self.ReqSettlementInfoConfirm(req, self.inc_request_id())
            print datetime.datetime.now(), 'SettlementInfo Confirm Requested.'
            print datetime.datetime.now(), "get today's trading day:", repr(
                self.GetTradingDay())

        else:
            print('something wrong, connect failed....')

        #
        #
        # if pRspInfo.ErrorID != 0:
        #     print("server OnRspUserLogin failed error_id=%s msg:%s",
        #           pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode('gbk'))
        # else:
        #     print("Trader user login successfully")
        #
        #     inv = ApiStruct.QryInvestor(BrokerID=self.broker_id, InvestorID=self.investor_id)
        #
        #     self.ReqQryInvestor(inv, self.inc_request_id())
        #
        #     req = ApiStruct.SettlementInfoConfirm(BrokerID = self.broker_id, InvestorID = self.investor_id)
        #
        #     self.ReqSettlementInfoConfirm(req, self.inc_request_id())
        #     time.sleep(1)

    def OnRspSettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo,
                                   nRequestID, bIsLast):
        print(pSettlementInfoConfirm, pRspInfo)
        """投资者结算结果确认响应"""
        print datetime.datetime.now(
        ), 'pSettlementInfoConfirm: ', pSettlementInfoConfirm
        print datetime.datetime.now(
        ), 'pRspInfo: ', pRspInfo, pRspInfo.ErrorMsg.decode('gbk')
        print datetime.datetime.now(), 'nRequestID: ', nRequestID
        print datetime.datetime.now(), 'bIsLast: ', bIsLast
        # info.append(pSettlementInfoConfirm)
        print(pRspInfo.ErrorMsg.decode("GBK"))

    def inc_request_id(self):
        self.request_id += 1
        return self.request_id

    def OnRspQryInvestor(self, pInvestor, pRspInfo, nRequestID, bIsLast):
        print(pInvestor, pRspInfo)
        print pInvestor.InvestorName.decode('gbk'), pInvestor.Address.decode(
            'gbk')

    def OnRtnOrder(self, pOrder):
        ''' 报单通知
            CTP、交易所接受报单
            Agent中不区分,所得信息只用于撤单
        '''

        q_rtn_order.put(deepcopy(pOrder))
        self.q_order.put(deepcopy(pOrder))

        # print repr(pOrder)

        self.logger.info(u'报单响应,Order=%s' % str(pOrder))
        # print pOrder
        if pOrder.OrderStatus == 'a':
            # CTP接受,但未发到交易所
            # print u'CTP接受Order,但未发到交易所, BrokerID=%s,BrokerOrderSeq = %s,TraderID=%s, OrderLocalID=%s' % (pOrder.BrokerID, pOrder.BrokerOrderSeq, pOrder.TraderID, pOrder.OrderLocalID)
            self.logger.info(
                u'TD:CTP接受Order,但未发到交易所, BrokerID=%s,BrokerOrderSeq = %s,TraderID=%s, OrderLocalID=%s'
                % (pOrder.BrokerID, pOrder.BrokerOrderSeq, pOrder.TraderID,
                   pOrder.OrderLocalID))
            # self.agent.rtn_order(pOrder)
        else:
            # print u'交易所接受Order,exchangeID=%s,OrderSysID=%s,TraderID=%s, OrderLocalID=%s' % (pOrder.ExchangeID, pOrder.OrderSysID, pOrder.TraderID, pOrder.OrderLocalID)
            self.logger.info(
                u'TD:交易所接受Order,exchangeID=%s,OrderSysID=%s,TraderID=%s, OrderLocalID=%s'
                % (pOrder.ExchangeID, pOrder.OrderSysID, pOrder.TraderID,
                   pOrder.OrderLocalID))
            # self.agent.rtn_order_exchange(pOrder)
            # self.agent.rtn_order(pOrder)

    def OnRtnTrade(self, pTrade):
        '''成交通知'''
        self.logger.info(
            u'TD:成交通知,BrokerID=%s,BrokerOrderSeq = %s,exchangeID=%s,OrderSysID=%s,TraderID=%s, OrderLocalID=%s'
            % (pTrade.BrokerID, pTrade.BrokerOrderSeq, pTrade.ExchangeID,
               pTrade.OrderSysID, pTrade.TraderID, pTrade.OrderLocalID))
        self.logger.info(u'TD:成交回报,Trade=%s' % repr(pTrade))
        pt = deepcopy(pTrade)
        # print u'报单成交:', pt.UserID, pt.InstrumentID, pt.Direction, pt.OffsetFlag, pt.Price
        q_rtn_trade.put(pt)

        # self.agent.rtn_trade(pTrade)

    def sendOrder(traderSpi, order):
        global mutex
        mutex.acquire()
        # print order

        traderSpi.ReqOrderInsert(order, traderSpi.inc_request_id())
        # DatabaseController.insert_SendOrder(order)

        # print("sendOrder = " + order.InstrumentID + " dir = " + order.Direction)
        # + " strategy = " + self.__module__)
        # time.sleep(1)
        mutex.release()

    def formatOrder(self, inst, direc, open_close, volume, price):

        orderp = ApiStruct.InputOrder(
            InstrumentID=inst,
            Direction=direc,  # ApiStruct.D_Buy or ApiStruct.D_Sell
            OrderRef=str(self.inc_request_id()),
            LimitPrice=price,
            VolumeTotalOriginal=volume,
            OrderPriceType=ApiStruct.OPT_LimitPrice,
            BrokerID=self.broker_id,
            InvestorID=self.investor_id,
            UserID=self.investor_id,
            CombOffsetFlag=open_close,  # OF_Open, OF_Close, OF_CloseToday
            CombHedgeFlag=ApiStruct.HF_Speculation,
            VolumeCondition=ApiStruct.VC_AV,
            MinVolume=1,
            ForceCloseReason=ApiStruct.FCC_NotForceClose,
            IsAutoSuspend=1,
            UserForceClose=0,
            TimeCondition=ApiStruct.TC_GFD)
        # print orderp
        return orderp

    def PrepareOrder(self, inst, direc, open_close, volume, price):
        order = self.formatOrder(inst, direc, open_close, volume, price)
        # print u'send order:', inst, u'price: ', price, u'amount:', volume
        self.sendOrder(order)

    def qryPosition(self, InstrumentID=''):

        self.requestid += 1

        if InstrumentID:
            req = ApiStruct.QryInvestorPosition(BrokerID=self.broker_id,
                                                InvestorID=self.investor_id,
                                                InstrumentID=InstrumentID)
        else:
            req = ApiStruct.QryInvestorPosition(BrokerID=self.broker_id,
                                                InvestorID=self.investor_id)

        self.ReqQryInvestorPosition(req, self.requestid)

    def OnRspQryInvestorPosition(self, pInvestorPosition, pRspInfo, nRequestID,
                                 bIsLast):
        # print pInvestorPosition
        if pInvestorPosition is not None:
            q_positions.put(copy.deepcopy(pInvestorPosition))

        # if bIsLast:
        # print pInvestorPosition,'tete'
        # print pRspInfo

    def fetch_investor_position_detail(self, instrument_id):
        '''
            获取合约的当前持仓明细,目前没用
        '''
        # logging.info(u'A:获取合约%s的当前持仓..' % (instrument_id,))
        print
        'get posi'
        req = ApiStruct.QryInvestorPositionDetail(BrokerID=self.broker_id,
                                                  InvestorID=self.investor_id,
                                                  InstrumentID=instrument_id)
        self.ReqQryInvestorPositionDetail(req, self.inc_request_id())
        # logging.info(u'A:查询持仓, 函数发出返回值:%s' % r)

    def fetch_instrument_marginrate(self, instrument_id):
        req = ApiStruct.QryInstrumentMarginRate(
            BrokerID=self.cuser.broker_id,
            InvestorID=self.cuser.investor_id,
            InstrumentID=instrument_id,
            HedgeFlag=ApiStruct.HF_Speculation)
        r = self.trader.ReqQryInstrumentMarginRate(req, self.inc_request_id())
        logging.info(u'A:查询保证金率, 函数发出返回值:%s' % r)

    def fetch_instrument(self, instrument_id):
        req = ApiStruct.QryInstrument(InstrumentID=instrument_id, )
        time.sleep(1)
        r = self.trader.ReqQryInstrument(req, self.inc_request_id())
        logging.info(u'A:查询合约, 函数发出返回值:%s' % r)

    def rsp_qry_position(self, position):
        '''
            查询持仓回报, 每个合约最多得到4个持仓回报,历史多/空、今日多/空
        '''
        logging.info(u'agent 持仓:%s' % str(position))
        if position != None:
            cur_position = self.instruments[position.InstrumentID].position
            if position.PosiDirection == ApiStruct.PD_Long:
                if position.PositionDate == ApiStruct.PSD_Today:
                    cur_position.clong = position.Position  # TodayPosition
                else:
                    cur_position.hlong = position.Position  # YdPosition
            else:  # 空头
                if position.PositionDate == ApiStruct.PSD_Today:
                    cur_position.cshort = position.Position  # TodayPosition
                else:
                    cur_position.hshort = position.Position  # YdPosition
        else:  # 无持仓信息,保持默认设置
            pass
        self.check_qry_commands()

    def rsp_qry_instrument_marginrate(self, marginRate):
        '''
            查询保证金率回报.
        '''
        self.instruments[marginRate.InstrumentID].marginrate = (
            marginRate.LongMarginRatioByMoney,
            marginRate.ShortMarginRatioByMoney)
        # print marginRate.InstrumentID,self.instruments[marginRate.InstrumentID].marginrate
        self.check_qry_commands()

    def rsp_qry_trading_account(self, account):
        '''
            查询资金帐户回报
        '''
        self.available = account.Available
        self.check_qry_commands()

    def rsp_qry_instrument(self, pinstrument):
        '''
            获得合约数量乘数.
            这里的保证金率应该是和期货公司无关,所以不能使用
        '''
        if pinstrument.InstrumentID not in self.instruments:
            logging.warning(u'A_RQI:收到未监控的合约查询:%s' %
                            (pinstrument.InstrumentID))
            return
        self.instruments[
            pinstrument.InstrumentID].multiple = pinstrument.VolumeMultiple
        self.instruments[pinstrument.InstrumentID].tick_base = int(
            pinstrument.PriceTick * 10 + 0.1)
        # print 'tick_base = %s' % (pinstrument.PriceTick,)
        self.check_qry_commands()

    def rsp_qry_position_detail(self, position_detail):
        '''
            查询持仓明细回报, 得到每一次成交的持仓,其中若已经平仓,则持量为0,平仓量>=1
            必须忽略
        '''
        print
        str(position_detail)
        self.check_qry_commands()

    def rsp_qry_order(self, sorder):
        '''
            查询报单
            可以忽略
        '''
        self.check_qry_commands()

    def rsp_qry_trade(self, strade):
        '''
            查询成交
            可以忽略
        '''
        self.check_qry_commands()
Example #3
0
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)
Example #4
0
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)