示例#1
0
def dingdang(data, stock, stockname):
    strategy = '叮当三号'
    bars = {stock: PytdxToAwpBar(data)}

    # print(bars[stock])
    O = get_k_line_column(bars[stock], ohlc='open')
    H = get_k_line_column(bars[stock], ohlc='high')
    L = get_k_line_column(bars[stock], ohlc='low')
    C = get_k_line_column(bars[stock], ohlc='close')

    uperband = HHV(H, 23)
    lowerband = LLV(L, 23)
    dingdangline = MID(uperband, lowerband)
    signalList = cross(C, dingdangline)
    buysigdetail = CROSS(C, dingdangline)
    sellsigdetail = CROSS(dingdangline, C)

    try:
        knum = len(H)
        signalall = buysigdetail.count(True) * 2
        avsigp = int(knum / signalall)

        if buysigdetail[-1]:
            print(stockname, '发出买入信号。。。')
            ttsengine.say(strategy + stockname + '发出买入信号。')
            ttsengine.runAndWait()
            # playsound('2.wav')
            print(stock, '最近的买入信号:', avsigp, buysigdetail[(knum - avsigp):])
            # sleep(1)

            sleep(2)
        elif sellsigdetail[-1]:
            print(stockname, '发出卖出信号。。。')
            ttsengine.say(strategy + stockname + '发出卖出信号。')
            ttsengine.runAndWait()
            # playsound('Alarm04.wav')
            print(stock, '最近的卖出信号:', avsigp, sellsigdetail[(knum - avsigp):])
            # sleep(1)

            sleep(2)

        print('-' * 50)
    except:
        pass
def dingdangNo6():
    st = time.time()

    lastsig = ''
    initFund = 500000
    fundNow = initFund
    fundTemp = fundNow
    pp = 0
    fundList = list()

    initFundReal = 500000
    fundNowReal = initFundReal
    fundTempReal = fundNowReal
    sigAllReal = list()
    PPReal = 0
    fundListReal = list()
    skprofitReal = 0
    bkprofitReal = 0

    profitlist = []
    losslist = []





    Signals = list()


    skprofit = 0
    bkprofit = 0

    bkloss = 0
    skloss = 0

    feeRatio = 0.0065
    instMultifier = 10
    signalslist = list()

    while True:

        if not q_depth_market_data.empty():
            tick = q_depth_market_data.get()

            tickToBar(tick, granularity)

            # dayopen = tick.OpenPrice
            # dayhigh = tick.HighestPrice
            # daylow = tick.LowestPrice
            # dayavp = int(tick.AveragePrice / 10)
            # BB = (tick.LastPrice - daylow) / (dayhigh - daylow) if dayhigh != daylow else 0.5
            # siglast = min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail))

            # quote_info = "合约:{0},当前价格:{price},时间:{ttime},日内振幅:{1},价格位置:{2} 做多信号:{3},做空信号:{4}"
            # # print quote_info.format(tick.InstrumentID,dayhigh - daylow,BB, buysigdetail.count(True),sellsigdetail.count(True), price=tick.LastPrice, ttime = tick.UpdateTime)
            # quote_info1 = "合约:{instid},日内振幅:{zhenfu},价格位置:{BB:.3f} 做多信号:{buynum},做空信号:{sellnum},信号距离:{siglast}"

            # info= {'instid': tick.InstrumentID,
            # 'zhenfu' : dayhigh - daylow,
            # 'buynum' : buysigdetail.count(True),
            # 'sellnum' : sellsigdetail.count(True),
            # 'BB':BB,
            # 'siglast': siglast}
            # # print quote_info1.format(**info)

            # knum = len(H)
            # signalall = buysigdetail.count(True)
            # avsigp = knum / signalall
            # buysigprice = C[len(C) - be_apart_from(buysigdetail)]
            # sellsigprice = C[len(C) - be_apart_from(sellsigdetail)]
            # sellsigprice1 = C[-1] if sellsigdetail[-1] else 0   # 另外一种方法。
            #
            # lastsig = 'SK' if be_apart_from(buysigdetail) > be_apart_from(sellsigdetail) else 'BK'

        if not q_signals.empty():
            lastsigdict = q_signals.get()
            allSignal.append(lastsigdict)

            print(lastsigdict)

            # 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')
            #
            # lastk = get_last_k_line(bars, 'rb1905', 780)
            # print lastk
            #
            # uperband = HHV(H, 23)
            # lowerband = LLV(L, 23)
            # dingdangline = MID(uperband, lowerband)
            # signalList = cross(C, dingdangline)
            # buysigdetail = CROSS(C, dingdangline)
            # sellsigdetail = CROSS(dingdangline, C)
            #
            # knum = len(H)
            #
            # signalall = buysigdetail.count(True)
            #
            # avsigp = knum / signalall if signalall > 0 else knum
            #
            # # print(buysigdetail.count(True))
            # # print(sellsigdetail.count(True))
            # print u'叮  当: ', dingdangline[(knum - avsigp):]
            # print u'收盘价: ', C[(knum - avsigp):]
            # # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):])
            # # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):])

        if not q_bar.empty():

            bar = q_bar.get()
            bars[barinterval].append(bar)

            # with open(bardatafile, 'a') as f:
            #     f.writelines(json.dumps(bar, ensure_ascii=False) + '\n')

            # print len(bars[barinterval])
            ed = time.time()
            lastk = get_last_k_line(bars, inst, granularity)
            print(lastk, len(bars[barinterval]), ed-st)

            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')
            dt = lastk['date_time']


            HH = H[-50:]
            LL = L[-50:]
            CC = C[-50:]
            
            uperband = HHV(HH, 23)
            lowerband = LLV(LL, 23)
            dingdangline = MID(uperband, lowerband)

            if cross2(C[-2:], dingdangline[-2:]):
                signalslist.append('bk')
            elif cross2(dingdangline[-2:], C[-2:], ):
                signalslist.append('sk')
            else:
                signalslist.append(None)

            signalList = cross(CC, dingdangline)
            buysigdetail = CROSS(CC, dingdangline)
            sellsigdetail = CROSS(dingdangline, CC)

            knum = len(H)

            signalall = signalslist.count('bk') + signalslist.count('sk') + signalslist.count('bp') + signalslist.count(
                'sp')

            # signalall1 = buysigdetail.count(True) + sellsigdetail.count(True)
            #
            # avsigp = knum / signalall if signalall > 0 else knum

            # print('buysig all:',buysigdetail.count(True))
            # print('sellsig all:', sellsigdetail.count(True))

            # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):])
            # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):])

            # print min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail))
            # print be_apart_from(sellsigdetail)
            # pp= getPositionRatio(buysigdetail)

            if buysigdetail[-1]:
                fundTemp += skprofit * pp * instMultifier - (pp * instMultifier * C[-1] * 1.11 / 10000) * 2
                fundratio = getPositionRatio(sellsigdetail)
                fundToUse = fundratio * fundTemp
                unitPrice = C[-1]*10*0.15

                pp = int(fundToUse/unitPrice)
                if skprofit >0:
                    profitlist.append(skprofit)
                else:
                    losslist.append(skprofit)
                bkprofits = []

                signal = {'date_time': dt, 'signaltype': 'BK', 'signalprice': C[-1], 'pos': pp}
                q_signals.put(signal)

                Signals.append(signal)


                # with open('allsignal.json', 'a') as f:
                #     f.writelines(json.dumps(signal, ensure_ascii=False) + '\n')

                order_price = C[-1]

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

                print('buy order issued.')
                lastsig = 'BK'
                buysigprice = C[-1]
                print('buysigprice', buysigprice)

            if sellsigdetail[-1]:
                fundTemp += bkprofit * pp * instMultifier - (pp * instMultifier * C[-1] * 1.11 / 10000) * 2
                fundratio = getPositionRatio(buysigdetail)
                fundToUse = fundTemp * fundratio
                unitPrice = C[-1] * 10 * 0.15

                pp = int(fundToUse / unitPrice)
                if bkprofit >0:
                    profitlist.append(bkprofit)
                else:
                    losslist.append(bkprofit)


                skprofits = []

                signal = {'date_time': dt, 'signaltype': 'SK', 'signalprice': C[-1], 'pos': pp}
                q_signals.put(signal)

                Signals.append(signal)

                # with open('allsignal.json', 'a') as f:
                #     f.writelines(json.dumps(signal, ensure_ascii=False) + '\n')

                # order_price = tick.LastPrice
                #
                # # TODO 暂时没有处理平昨仓和今仓,待处理... 应该有个完整的策略持仓管理模块
                #
                # td.PrepareOrder(tick.InstrumentID, s, p, pp, order_price)
                #
                # log.info(log.printfNow() + u'平多单:' + str(pp) + ',orderprice:'+str(order_price))
                # print('close order issued...')

                lastsig = 'SK'
                sellsigprice = C[-1]

                print('sellsigprice', sellsigprice)

            if lastsig == 'BK':
                # print tick.LastPrice, buysigprice

                bkprofit = C[-1] - buysigprice
                print('多单盈利价差', bkprofit)

                bkprofits.append(bkprofit)

                bkpmax = max(bkprofits) if bkprofits else 0
                bkpmin = min(bkprofits) if bkprofits else 0

                print('当前信号:', lastsig, '信号价:', buysigprice, '当前价: ', C[
                    -1], '仓位', pp, '盈利价差:', bkprofit, '最大:', bkpmax, '最小', bkpmin, '持续周期:', be_apart_from(
                    buysigdetail), '理论持仓', pp)
                sigprofit_info.append([lastsig, bkpmax, bkpmin])
                # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):], pp)

                if len(bkprofits) >= 2:
                    fundNow = fundTemp + (bkprofits[-1]-bkprofits[-2]) * pp * instMultifier

            elif lastsig == 'SK':
                skprofit = sellsigprice - C[-1]
                skprofits.append(skprofit)

                skpmax = max(skprofits) if skprofits else 0
                skpmin = min(skprofits) if skprofits else 0

                # print u'当前信号:', lastsig, u'信号价:', sellsigprice, u'当前价: ', C[
                #     -1], u'盈利价差:', skprofit, u'最大:', skpmax, u'最小', skpmin, u'持续周期:', be_apart_from(sellsigdetail)

                print('当前信号:', lastsig, '信号价:', sellsigprice, '当前价: ', C[
                    -1], '仓位', pp, '盈利价差:', skprofit, '最大:', skpmax, '最小', skpmin, '持续周期:', be_apart_from(
                    buysigdetail), '理论持仓', pp)

                sigprofit_info.append([lastsig, max(skprofits), min(skprofits)])
                # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):], pp)
                if len(skprofits) >= 2:
                    fundNow = fundTemp + (skprofits[-1]-skprofits[-2]) * pp * instMultifier

            fundList.append(fundNow)
            fundListMa = MA(fundList, 23)

            getinlist = CROSS(fundList, fundListMa)
            getoutlist = CROSS(fundListMa, fundList)
            # print getinlist.count(True)

            if getinlist[-1]:
                sigReal = {'date_time':dt, 'signaltype':signal['signaltype'], 'signalprice': C[-1], 'pos':signal['pos']}
                # if len(sigAllReal)>1 and sigAllReal[-1]['signaltype']==sigReal['signalprice']:
                #     continue
                # else:

                sigAllReal.append(sigReal)

            elif getoutlist[-1]:
                sigReal = {'date_time': dt, 'signaltype': signal['signaltype'], 'signalprice': C[-1],
                           'pos': signal['pos']}
                # if len(sigAllReal)>1 and sigAllReal[-1]['signaltype']==sigReal['signalprice']:
                #     continue
                # else:

                sigAllReal.append(sigReal)
                sigNow = sigAllReal[-1]
                sigNow1 = sigReal

                if sigNow['signaltype'] == 'BK':
                    profitReal = C[-1] - sigNow['signalprice']

                if sigNow['signaltype'] == 'SK':
                    profitReal = sigNow['signalprice'] - C[-1]


                fundTempReal += profitReal * sigNow['pos'] * instMultifier - (pp * instMultifier * C[-1] * 1.11 / 10000) * 2




            print(max(fundList), min(fundList))

            print('初始权益:', initFund, '策略当前权益: ', fundNow, '账号1权益', fundTempReal)
示例#3
0
                           granularities='780',
                           data_source_dir=data_path)
barinterval = inst + '_' + str(granularity)
bardatafile = data_path + barinterval + '.json'

# bars[barinterval] = barss
# O30 = get_k_line_column(bars, inst, 300, ohlc='open')
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')

lastk = get_last_k_line(bars, inst, granularity)
print(lastk)

uperband = HHV(H, 23)
lowerband = LLV(L, 23)
dingdangline = MID(uperband, lowerband)
signalList = cross(C, dingdangline)
buysigdetail = CROSS(C, dingdangline)
sellsigdetail = CROSS(dingdangline, C)

knum = len(H)
signalall = buysigdetail.count(True)

avsigp = knum / signalall
# print(buysigdetail.count(True))
# print(sellsigdetail.count(True))
# print len(O)
print(('buy signal:', avsigp, buysigdetail[(knum - avsigp):]))
print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):]))
示例#4
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)
示例#5
0
def initStrategy(q_initdata):
    bkprofits = []
    skprofits = []
    sigprofit_info = []
    posratio = []
    bkprofit = 0
    skprofit = 0

    initFund = 20000
    instMultifier = 10

    bars[barinterval] = list()

    while not q_initdata.empty():
        bar = q_initdata.get()
        bars[barinterval].append(bar)

        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')

        lastk = get_last_k_line(bars, inst, granularity)
        print(lastk)

        uperband = HHV(H, 23)
        lowerband = LLV(L, 23)
        dingdangline = MID(uperband, lowerband)
        signalList = cross(C, dingdangline)
        buysigdetail = CROSS(C, dingdangline)
        sellsigdetail = CROSS(dingdangline, C)

        pp = getPositionRatio(buysigdetail)

        if buysigdetail[-1]:

            initFund += skprofit * pp * instMultifier
            bkprofits = []
            # signal = {'date_time': time.time(), 'signaltype': 'BK', 'signalprice': tick.LastPrice}
            # 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() + u'下多单:' + 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

            # TODO 暂时没有处理平昨仓和今仓,待处理... 应该有个完整的策略持仓管理模块

            td.PrepareOrder(tick.InstrumentID, s, p, pp, order_price)

            log.info(log.printfNow() + '平多单:' + str(pp) + ',orderprice:' +
                     str(order_price))
            print('close order issued...')

            # spk
            sellcount = 0
            down_trading_flag = False

        knum = len(H)
        signalall = buysigdetail.count(True)

        if signalall > 0:
            avsigp = knum / signalall

            # print(buysigdetail.count(True))
            # print(sellsigdetail.count(True))
            # print len(O)
            print(('buy signal:', avsigp, buysigdetail[(knum - avsigp):]))
            print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):]))

            # print be_apart_from(buysigdetail)
            # print be_apart_from(sellsigdetail)

            # 计算发出信号时刻,最近平均信号距离内的信号数量
            sigsum2 = buysigdetail[(knum - avsigp):-2].count(
                True) + sellsigdetail[(knum - avsigp):-2].count(True)
            sigsum4 = sigsum2 * 2
            sigsum5 = sigsum4 if sellsigdetail[-1] or buysigdetail[-1] else 0
            # pp = min((sigsum5+1)*10, 80)
            # 计算下单仓位数量
            pp = min((sigsum5 + 1), 8)
def dingdangno6bksp(md, td, instid, instrumentid):
    while True:
        time.sleep(0.3)
        if not md.q_depth_market_data.empty():

            tick = q_depth_market_data.get()
            tickToBar(tick, granularity)

            dayopen = tick.OpenPrice
            dayhigh = tick.HighestPrice
            daylow = tick.LowestPrice
            dayavp = int(tick.AveragePrice / 10)
            BB = (tick.LastPrice -
                  daylow) / (dayhigh - daylow) if dayhigh != daylow else 0.5
            siglast = min(be_apart_from(buysigdetail),
                          be_apart_from(sellsigdetail))

            quote_info = "合约:{0},当前价格:{price},时间:{ttime},日内振幅:{1},价格位置:{2} 做多信号:{3},做空信号:{4}"
            print(
                quote_info.format(tick.InstrumentID,
                                  dayhigh - daylow,
                                  BB,
                                  buysigdetail.count(True),
                                  sellsigdetail.count(True),
                                  price=tick.LastPrice,
                                  ttime=tick.UpdateTime))
            quote_info1 = "合约:{instid},日内振幅:{zhenfu},价格位置:{BB:.3f} 做多信号:{buynum},做空信号:{sellnum},信号距离:{siglast}"

            info = {
                'instid': tick.InstrumentID,
                'zhenfu': dayhigh - daylow,
                'buynum': buysigdetail.count(True),
                'sellnum': sellsigdetail.count(True),
                'BB': BB,
                'siglast': siglast
            }
            print(quote_info1.format(**info))

            knum = len(H)
            signalall = buysigdetail.count(True)

            avsigp = knum / signalall

            # sigsum2 = buysigdetail[(knum - avsigp):-2].count(True) + sellsigdetail[(knum - avsigp):-2].count(True)
            # sigsum4 = sigsum2 * 2
            # sigsum5 = sigsum4 if sellsigdetail[-1] or buysigdetail[-1] else 0
            #
            # pp = min((sigsum5 + 1), 8)

            buysigprice = C[len(C) - be_apart_from(buysigdetail)]
            sellsigprice = C[len(C) - be_apart_from(sellsigdetail)]

            sellsigprice1 = C[-1] if sellsigdetail[-1] else 0  # 另外一种方法。

            lastsig = 'SK' if be_apart_from(buysigdetail) > be_apart_from(
                sellsigdetail) else 'BK'

            # if buysigdetail[-1] or sellsigdetail[-1]:
            #     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)
            #     posratio.append(pp)

            if lastsig == 'BK':

                bkprofit = tick.LastPrice - buysigprice
                bkprofits.append(bkprofit)

                bkpmax = max(bkprofits) if bkprofits else 0
                bkpmin = min(bkprofits) if bkprofits else 0

                print(INVESTOR_ID, '当前信号:', lastsig, '信号价:', buysigprice,
                      tick.LastPrice, '盈利价差:', bkprofit, '最大:', bkpmax, '最小',
                      bkpmin, '持续周期:', be_apart_from(buysigdetail), '理论持仓', pp)
                sigprofit_info.append([lastsig, bkpmax, bkpmin])
                print(('buy signal:', avsigp, buysigdetail[(knum - avsigp):],
                       pp))
            elif lastsig == 'SK':
                skprofit = sellsigprice - tick.LastPrice
                skprofits.append(skprofit)

                skpmax = max(skprofits) if skprofits else 0
                skpmin = min(skprofits) if skprofits else 0

                print('当前信号:', lastsig, '信号价:', sellsigprice, sellsigprice1,
                      tick.LastPrice, '盈利价差:', skprofit, '最大:', skpmax, '最小',
                      skpmin, '持续周期:', be_apart_from(sellsigdetail))
                sigprofit_info.append(
                    [lastsig, max(skprofits),
                     min(skprofits)])
                print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):],
                       pp))

            # print tick.InstrumentID, dayhigh - daylow, BB, buysigdetail.count(True), sellsigdetail.count(True), min(
            #     be_apart_from(buysigdetail), be_apart_from(sellsigdetail))

            if not q_signals.empty():
                lastsig = q_signals.get()
                print(lastsig)

            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')

            lastk = get_last_k_line(bars, 'rb1905', 780)
            print(lastk)

            uperband = HHV(H, 23)
            lowerband = LLV(L, 23)
            dingdangline = MID(uperband, lowerband)
            signalList = cross(C, dingdangline)
            buysigdetail = CROSS(C, dingdangline)
            sellsigdetail = CROSS(dingdangline, C)

            knum = len(H)
            signalall = buysigdetail.count(True)

            avsigp = knum / signalall

            # print(buysigdetail.count(True))
            # print(sellsigdetail.count(True))
            print('叮  当: ', dingdangline[(knum - avsigp):])
            print('收盘价: ', C[(knum - avsigp):])
            print(('buy signal:', avsigp, buysigdetail[(knum - avsigp):]))
            print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):]))

        if not q_bar.empty():

            bar = q_bar.get()
            bars[barinterval].append(bar)

            with open(bardatafile, 'a') as f:
                f.writelines(json.dumps(bar, ensure_ascii=False) + '\n')

            print(len(bars[barinterval]))

            # bar_s = dict()
            # barss = load_data_from_server(server_base=serverport, instruments_id=inst, granularity=granularity)
            # barinterval = inst + '_' + str(granularity)
            # bar_s[barinterval] = barss
            # print len(bar_s[barinterval])

            lastk = get_last_k_line(bars, 'rb1905', 780)
            print(lastk)

            # O30 = get_k_line_column(bars, inst, 300, ohlc='open')
            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')
            uperband = HHV(H, 23)
            lowerband = LLV(L, 23)
            dingdangline = MID(uperband, lowerband)
            signalList = cross(C, dingdangline)
            buysigdetail = CROSS(C, dingdangline)
            sellsigdetail = CROSS(dingdangline, C)

            knum = len(H)
            signalall = buysigdetail.count(True)

            avsigp = knum / signalall

            # print(buysigdetail.count(True))
            # print(sellsigdetail.count(True))

            print(('buy signal:', avsigp, buysigdetail[(knum - avsigp):]))
            print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):]))

            print(
                min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail)))
            # print be_apart_from(sellsigdetail)

            # if buysigdetail[-1] or sellsigdetail[-1]:  # 发出交易信号并确认,计算下单仓位
            #     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)
            #     posratio.append(pp)

            if buysigdetail[-1]:
                bkprofits = []
                signal = {
                    'date_time': time.time(),
                    'signaltype': 'BK',
                    'signalprice': tick.LastPrice
                }
                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)

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

                order_price = tick.LastPrice

                # TODO 暂时没有处理平昨仓和今仓,待处理... 应该有个完整的策略持仓管理模块
                if bkprofit > 0:
                    td.PrepareOrder(tick.InstrumentID, s, p, pp, order_price)

                # spk
                sellcount = 0
                down_trading_flag = False
示例#7
0
def dingdangNo6():
    lastsig = ''
    initFund = 20000
    fundNow = 0

    skprofit = 0
    bkprofit = 0

    initFund = 20000
    feeRatio = 0.0065
    instMultifier = 10
    signalslist = list()

    while True:

        if not q_depth_market_data.empty():

            tick = q_depth_market_data.get()

            tickToBar(tick, granularity)

            # dayopen = tick.OpenPrice
            # dayhigh = tick.HighestPrice
            # daylow = tick.LowestPrice
            # dayavp = int(tick.AveragePrice / 10)
            # BB = (tick.LastPrice - daylow) / (dayhigh - daylow) if dayhigh != daylow else 0.5
            # siglast = min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail))

            # quote_info = "合约:{0},当前价格:{price},时间:{ttime},日内振幅:{1},价格位置:{2} 做多信号:{3},做空信号:{4}"
            # # print quote_info.format(tick.InstrumentID,dayhigh - daylow,BB, buysigdetail.count(True),sellsigdetail.count(True), price=tick.LastPrice, ttime = tick.UpdateTime)
            # quote_info1 = "合约:{instid},日内振幅:{zhenfu},价格位置:{BB:.3f} 做多信号:{buynum},做空信号:{sellnum},信号距离:{siglast}"

            # info= {'instid': tick.InstrumentID,
            # 'zhenfu' : dayhigh - daylow,
            # 'buynum' : buysigdetail.count(True),
            # 'sellnum' : sellsigdetail.count(True),
            # 'BB':BB,
            # 'siglast': siglast}
            # # print quote_info1.format(**info)

            # knum = len(H)
            # signalall = buysigdetail.count(True)
            #
            # avsigp = knum / signalall
            #
            #
            # buysigprice = C[len(C) - be_apart_from(buysigdetail)]
            # sellsigprice = C[len(C) - be_apart_from(sellsigdetail)]
            #
            # sellsigprice1 = C[-1] if sellsigdetail[-1] else 0   # 另外一种方法。
            #
            # lastsig = 'SK' if be_apart_from(buysigdetail) > be_apart_from(sellsigdetail) else 'BK'
            #
            #

            if not q_signals.empty():
                lastsigdict = q_signals.get()
                print(lastsigdict)

            # 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')
            #
            # lastk = get_last_k_line(bars, 'rb1905', 780)
            # print lastk
            #
            # uperband = HHV(H, 23)
            # lowerband = LLV(L, 23)
            # dingdangline = MID(uperband, lowerband)
            # signalList = cross(C, dingdangline)
            # buysigdetail = CROSS(C, dingdangline)
            # sellsigdetail = CROSS(dingdangline, C)
            #
            # knum = len(H)
            #
            # signalall = buysigdetail.count(True)
            #
            # avsigp = knum / signalall if signalall > 0 else knum
            #
            # # print(buysigdetail.count(True))
            # # print(sellsigdetail.count(True))
            # print u'叮  当: ', dingdangline[(knum - avsigp):]
            # print u'收盘价: ', C[(knum - avsigp):]
            # # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):])
            # # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):])

        if not q_bar.empty():

            bar = q_bar.get()
            bars[barinterval].append(bar)

            # with open(bardatafile, 'a') as f:
            #     f.writelines(json.dumps(bar, ensure_ascii=False) + '\n')

            print(len(bars[barinterval]))

            lastk = get_last_k_line(bars, 'rb1905', 780)
            print(lastk)

            # O30 = get_k_line_column(bars, inst, 300, ohlc='open')
            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')
            uperband = HHV(H, 23)
            lowerband = LLV(L, 23)
            dingdangline = MID(uperband, lowerband)

            if cross2(C[-2:], dingdangline[-2:]):
                signalslist.append('bk')
            elif cross2(
                    dingdangline[-2:],
                    C[-2:],
            ):
                signalslist.append('sk')
            else:
                signalslist.append(None)

            signalList = cross(C, dingdangline)
            buysigdetail = CROSS(C, dingdangline)
            sellsigdetail = CROSS(dingdangline, C)

            knum = len(H)

            signalall = signalslist.count('bk') + signalslist.count(
                'sk') + signalslist.count('bp') + signalslist.count('sp')

            signalall1 = buysigdetail.count(True) + sellsigdetail.count(True)

            avsigp = knum / signalall if signalall > 0 else knum

            print(('buysig all:', buysigdetail.count(True)))
            print(('sellsig all:', sellsigdetail.count(True)))

            print(('buy signal:', avsigp, buysigdetail[(knum - avsigp):]))
            print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):]))

            # print min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail))
            # print be_apart_from(sellsigdetail)
            # pp= getPositionRatio(buysigdetail)

            if buysigdetail[-1]:

                pp = getPositionRatio(sellsigdetail)

                initFund += skprofit * pp * instMultifier - (
                    pp * instMultifier * tick.LastPrice / 10000) * 2

                bkprofits = []

                signal = {
                    'date_time': time.time(),
                    'signaltype': 'BK',
                    'signalprice': tick.LastPrice
                }
                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() + u'下多单:' + str(pp) + ',orderprice:'+str(order_price))

                print('buy order issued.')
                lastsig = 'BK'
                buysigprice = tick.LastPrice
                print('buysigprice', buysigprice)

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

                # order_price = tick.LastPrice
                #
                # # TODO 暂时没有处理平昨仓和今仓,待处理... 应该有个完整的策略持仓管理模块
                #
                # td.PrepareOrder(tick.InstrumentID, s, p, pp, order_price)
                #
                # log.info(log.printfNow() + u'平多单:' + str(pp) + ',orderprice:'+str(order_price))
                # print('close order issued...')
                lastsig = 'SK'
                sellsigprice = tick.LastPrice
                print('sellsigprice', sellsigprice)

            if lastsig == 'BK':
                print(tick.LastPrice, buysigprice)

                bkprofit = tick.LastPrice - buysigprice
                print(bkprofit)
                bkprofits.append(bkprofit)

                bkpmax = max(bkprofits) if bkprofits else 0
                bkpmin = min(bkprofits) if bkprofits else 0

                print('当前信号:', lastsig, '信号价:', buysigprice, tick.LastPrice,
                      '盈利价差:', bkprofit, '最大:', bkpmax, '最小', bkpmin, '持续周期:',
                      be_apart_from(buysigdetail), '理论持仓', pp)
                sigprofit_info.append([lastsig, bkpmax, bkpmin])
                # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):], pp)
                fundNow = initFund + bkprofit * pp * instMultifier

            elif lastsig == 'SK':
                skprofit = sellsigprice - tick.LastPrice
                skprofits.append(skprofit)

                skpmax = max(skprofits) if skprofits else 0
                skpmin = min(skprofits) if skprofits else 0

                print('当前信号:', lastsig, '信号价:', sellsigprice, sellsigprice,
                      tick.LastPrice, '盈利价差:', skprofit, '最大:', skpmax, '最小',
                      skpmin, '持续周期:', be_apart_from(sellsigdetail))
                sigprofit_info.append(
                    [lastsig, max(skprofits),
                     min(skprofits)])
                print(('sell signal:', avsigp, sellsigdetail[(knum - avsigp):],
                       pp))

                fundNow = initFund + skprofit * pp * instMultifier

            print('初始权益:', initFund, '策略当前权益: ', fundNow)
示例#8
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)
示例#9
0
def run():

    strategy_parameters = [['AP901', 180], ['rb1810', 780]]
    strategy_inst = ['rb1810']
    # strategy_parameters[1][0]
    strategy_period = strategy_parameters[1][1]

    import shelve
    acinfo = shelve.open(cfgfile)
    # BROKER_ID = acinfo['BROKER_ID']
    BROKER_ID = '7030'
    INVESTOR_ID = acinfo['INVESTOR_ID']
    PASSWORD = acinfo['PASSWORD']
    # ADDR_MD = acinfo['ADDR_MD']
    ADDR_MD = 'tcp://210.5.151.247:41213'  # 海通实盘
    ADDR_TD = acinfo['ADDR_TRADE']
    acinfo.close()

    s = S = ApiStruct.D_Sell
    b = B = ApiStruct.D_Buy
    k = K = ApiStruct.OF_Open
    p = P = ApiStruct.OF_Close
    # T['TE_RESUME'] = 'int'  # 流重传方式
    # TERT_RESTART = 0  # 从本交易日开始重传
    # TERT_RESUME = 1  # 从上次收到的续传
    # TERT_QUICK = 2  # 只传送登录后的流内容

    # 登录行情服务器
    user = MyMdApi(instruments=strategy_inst,
                   broker_id=BROKER_ID,
                   investor_id=INVESTOR_ID,
                   password=PASSWORD)
    user.Create("data")
    user.RegisterFront(ADDR_MD)
    user.Init()
    print u'行情服务器登录成功'

    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()
    print BROKER_ID, INVESTOR_ID, u'交易服务器登录成功。'

    last_time = None
    up_trader_flag = False
    down_trader_flag = False

    while True:
        if not q_depth_market_data.empty():
            payload = q_depth_market_data.get()

            tick = deepcopy(payload)
            sewing_data_to_file_and_depositary(depth_market_data=payload)

            last_k_line = get_last_k_line(instrument_id='rb1810',
                                          interval=strategy_period)

            # print last_k_line['low'], last_k_line['high'], payload.LastPrice

            if last_k_line is not None:

                # get the h,l c,serieses.
                stra_inst = 'rb1810'
                H = get_k_line_column(stra_inst, strategy_period, ohlc='high')
                L = get_k_line_column(stra_inst, strategy_period, ohlc='low')
                C = get_k_line_column(stra_inst, strategy_period, ohlc='close')

                # calculate the uppper and lower band
                HV = HHV(H, 23)
                LV = LLV(L, 23)

                # middle line
                Mid = list(map(lambda x: (x[0] + x[1]) / 2, zip(HV, LV)))

                num, detail = cross(C, Mid)
                # print 'High:', High[-20:]
                # print 'Low:', Low[-20:]
                #
                # print 'HHV: ', HV[-20:]
                # print 'LLV: ', LV[-20:]

                print 'MID: ', Mid[-20:]
                print 'Close: ', C[-20:]
                print 'cross num: ', num
                print 'cross detail: ', detail

                if last_time != last_k_line['date_time']:
                    last_time = last_k_line['date_time']
                    up_trader_flag = False
                    down_trader_flag = False

                if not up_trader_flag and payload.LastPrice > last_k_line[
                        'high'] and C[-1] > Mid[-1]:
                    # 下多单
                    up_trader_flag = True

                    td.PrepareOrder(tick.InstrumentID, b, k, single_volume,
                                    tick.LastPrice)

                    td.PrepareOrder(tick.InstrumentID, S, P, single_volume,
                                    tick.LastPrice + grid)

                    print
                    print u'下多单'

                    print last_k_line
                    print payload.LastPrice

                if not down_trader_flag and payload.LastPrice < last_k_line[
                        'low'] and C[-1] <= Mid[-1]:
                    # 下空单
                    down_trader_flag = True

                    td.PrepareOrder(tick.InstrumentID, s, k, single_volume,
                                    tick.LastPrice)

                    td.PrepareOrder(tick.InstrumentID, B, P, single_volume,
                                    tick.LastPrice - grid)

                    print
                    print u'下空单'
                    print last_k_line
                    print payload.LastPrice

            if not q_rtn_trade.empty():
                rtn_td = q_rtn_trade.get()
                print rtn_td.TradeTime
示例#10
0
def dingdangNo6():

    while True:

        if not q_depth_market_data.empty():

            tick = q_depth_market_data.get()
            q_depth_market_data.task_done()

            tickToBar(tick, granularity)

            # dayopen = tick.OpenPrice
            # dayhigh = tick.HighestPrice
            # daylow = tick.LowestPrice
            # dayavp = int(tick.AveragePrice / 10)
            # BB = (tick.LastPrice - daylow) / (dayhigh - daylow) if dayhigh != daylow else 0.5
            # siglast = min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail))

            # quote_info = "合约:{0},当前价格:{price},时间:{ttime},日内振幅:{1},价格位置:{2} 做多信号:{3},做空信号:{4}"
            # print quote_info.format(tick.InstrumentID,dayhigh - daylow,BB, buysigdetail.count(True),sellsigdetail.count(True), price=tick.LastPrice, ttime = tick.UpdateTime)
            # quote_info1 = "合约:{instid},日内振幅:{zhenfu},价格位置:{BB:.3f} 做多信号:{buynum},做空信号:{sellnum},信号距离:{siglast}"
            #
            # info= {'instid': tick.InstrumentID,
            # 'zhenfu' : dayhigh - daylow,
            # 'buynum' : buysigdetail.count(True),
            # 'sellnum' : sellsigdetail.count(True),
            # 'BB':BB,
            # 'siglast': siglast}
            # print quote_info1.format(**info)

            # knum = len(H)
            # signalall = buysigdetail.count(True)
            #
            # avsigp = knum / signalall
            #
            # sigsum2 = buysigdetail[(knum - avsigp):-2].count(True) + sellsigdetail[(knum - avsigp):-2].count(True)
            # sigsum4 = sigsum2 * 2
            # sigsum5 = sigsum4 if sellsigdetail[-1] or buysigdetail[-1] else 0
            #
            # pp = min((sigsum5 + 1), 8)

            # buysigprice = C[len(C) - be_apart_from(buysigdetail)]
            # sellsigprice = C[len(C) - be_apart_from(sellsigdetail)]
            #
            # sellsigprice1 = C[-1] if sellsigdetail[-1] else 0   # 另外一种方法。
            #
            # lastsig = 'SK' if be_apart_from(buysigdetail) > be_apart_from(sellsigdetail) else 'BK'
            #
            # if lastsig == 'BK':
            #
            #     bkprofit = tick.LastPrice - buysigprice
            #     bkprofits.append(bkprofit)
            #
            #     bkpmax = max(bkprofits) if bkprofits else 0
            #     bkpmin = min(bkprofits) if bkprofits else 0
            #
            #     print u'当前信号:', lastsig, u'信号价:', buysigprice, tick.LastPrice, u'盈利价差:', bkprofit, u'最大:', bkpmax, u'最小', bkpmin, u'持续周期:', be_apart_from(buysigdetail)
            #     sigprofit_info.append([lastsig, bkpmax, bkpmin])
            #     print('buy signal:', avsigp, buysigdetail[(knum - avsigp):], pp)
            # elif lastsig == 'SK':
            #     skprofit = sellsigprice - tick.LastPrice
            #     skprofits.append(skprofit)
            #
            #     skpmax = max(skprofits) if skprofits else 0
            #     skpmin = min(skprofits) if skprofits else 0

            # print u'当前信号:', lastsig, u'信号价:', sellsigprice, sellsigprice1, tick.LastPrice, u'盈利价差:', skprofit, u'最大:', skpmax, u'最小', skpmin, u'持续周期:',be_apart_from(sellsigdetail)
            # sigprofit_info.append([lastsig, max(skprofits), min(skprofits)])
            # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):], pp)

            # print tick.InstrumentID, dayhigh - daylow, BB, buysigdetail.count(True), sellsigdetail.count(True), min(
            #     be_apart_from(buysigdetail), be_apart_from(sellsigdetail))

            if not q_signals.empty():
                lastsig = q_signals.get()
                print(lastsig)

            # 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')
            #
            # lastk = get_last_k_line(bars, 'rb1905', 780)
            # print lastk
            #
            # uperband = HHV(H, 23)
            # lowerband = LLV(L, 23)
            # dingdangline = MID(uperband, lowerband)
            # signalList = cross(C, dingdangline)
            # buysigdetail = CROSS(C, dingdangline)
            # sellsigdetail = CROSS(dingdangline, C)
            #
            # knum = len(H)
            # signalall = buysigdetail.count(True)
            #
            # avsigp = knum / signalall
            #
            # # print(buysigdetail.count(True))
            # # print(sellsigdetail.count(True))
            # print dingdangline[(knum - avsigp):]
            # print C[(knum - avsigp):]
            # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):])
            # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):])

        if not q_bar.empty():

            bar = q_bar.get()
            bars[barinterval].append(bar)

            # with open(bardatafile, 'a') as f:
            #     f.writelines(json.dumps(bar, ensure_ascii=False) + '\n')

            # print len(bars[barinterval])

            # bar_s = dict()
            # barss = load_data_from_server(server_base=serverport, instruments_id=inst, granularity=granularity)
            # barinterval = inst + '_' + str(granularity)
            # bar_s[barinterval] = barss
            # print len(bar_s[barinterval])

            # lastk = get_last_k_line(bars, 'rb1905', 780)
            # print lastk

            # O30 = get_k_line_column(bars, inst, 300, ohlc='open')
            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')
            uperband = HHV(H, 23)
            lowerband = LLV(L, 23)
            dingdangline = MID(uperband, lowerband)
            signalList = cross(C, dingdangline)
            buysigdetail = CROSS(C, dingdangline)
            sellsigdetail = CROSS(dingdangline, C)

            # knum = len(H)
            # signalall = buysigdetail.count(True)

            # if signalall >0:
            #     avsigp = knum / signalall
            #
            # print(buysigdetail.count(True))
            # print(sellsigdetail.count(True))

            # print('buy signal:', avsigp, buysigdetail[(knum - avsigp):])
            # print('sell signal:', avsigp, sellsigdetail[(knum - avsigp):])

            # print min(be_apart_from(buysigdetail), be_apart_from(sellsigdetail))
            # print be_apart_from(sellsigdetail)

            # sigsum2 = buysigdetail[(knum - avsigp):-2].count(True) + sellsigdetail[(knum - avsigp):-2].count(True)
            # sigsum4 = sigsum2 * 2
            # sigsum5 = sigsum4 if sellsigdetail[-1] or buysigdetail[-1] else 0
            # pp = min((sigsum5 + 1), 8)
            # # print 'pp:', pp

            if sellsigdetail[-1]:
                skprofits = []

                pp = getPositionRatio(sellsigdetail)
                sigdt = ' '.join([str(tick.ActionDay), str(tick.UpdateTime)])
                signal = {
                    'date_time': sigdt,
                    'signaltype': 'SK',
                    'signalprice': tick.LastPrice,
                    'pos': pp
                }
                q_signals.put(signal)
                order_price = tick.LastPrice
                # td.PrepareOrder(tick.InstrumentID, s, k, pp, order_price)

                # spk
                sellcount = 0
                down_trading_flag = False
                # if not down_trading_flag and tick.LastPrice < get_last_k_line(bars,'rb1905',780)['low']:
                #     down_trading_flag = True
                #     sellcount +=1
                #     sk(pp) #
                #
                # pass
            elif buysigdetail[-1]:
                bkprofits = []

                pp = getPositionRatio(buysigdetail)
                sigdt = ' '.join([str(tick.ActionDay), str(tick.UpdateTime)])
                signal = {
                    'date_time': sigdt,
                    'signaltype': 'BK',
                    'signalprice': tick.LastPrice,
                    'pos': pp
                }
                q_signals.put(signal)
                order_price = tick.LastPrice

                # td.PrepareOrder(tick.InstrumentID, b, k, pp, order_price)

                # bpk
                pass
示例#11
0
文件: dingdang3.py 项目: pyctp/test3
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)