Exemple #1
0
    def getHotContractNextTDays(self, symbol, currTDays):
        # 获取下一个主力合约 代码

        if not self.__mainContractData is None:

            # 获取下一个交易日
            nextTradeDates = self.calendarObj.tradingDaysOffset(currTDays, 1)
            # 下一个交易日存在
            if not nextTradeDates is None:
                mainContract = commonHelpBylw.getMainContinContract(symbol)
                nextSymbol = self.__mainContractData.loc[nextTradeDates,
                                                         mainContract]
                return nextSymbol
    def __init__(self, symbol, **kwargs):
        i = 1
        self.symbol = symbol
        # context 来提供持仓的信息
        self.context = kwargs.get('context', None)
        self.exitTime = kwargs.get('exitTime', None)

        underLySym = commonHelpBylw.getMainContinContract(symbol)
        self.orderLog = loggerHelpbylw.getFileLogger(
            self.context.bTestID + '-' + underLySym + '-orderlog',
            'log\\' + self.context.bTestID + '\\' + underLySym +
            '-orderRecord.txt',
            mode_='a')
Exemple #3
0
def getVolofwangzong(aSymbol):
    sharesDict = {}
    sharesDict['SHFE.RB'] = 25
    sharesDict['SHFE.NI'] = 10
    sharesDict['SHFE.CU'] = 4
    sharesDict['DCE.J'] = 4
    sharesDict['SHFE.BU'] = 25
    sharesDict['CZCE.MA'] = 30
    sharesDict['DCE.PP'] = 20
    sharesDict['DCE.P'] = 20
    sharesDict['CZCE.SM'] = 25
    sharesDict['CFFEX.T'] = 1
    sharesDict['CZCE.SR'] = 20
    sharesDict['CZCE.CF'] = 15

    mainContract = commonHelpBylw.getMainContinContract(aSymbol)

    vol = sharesDict[mainContract]
    return vol
    def create_trailing_order(self, aOrderPosition, trailing_type,
                              trailingThresh, stop_type, stopThresh):

        # assert atradeOrder.status == ORDER_STATUS.FILLED
        # if atradeOrder.status == ORDER_STATUS.FILLED:

        underLySym = commonHelpBylw.getMainContinContract(
            aOrderPosition.symbol)
        orderLog = loggerHelpbylw.getFileLogger(
            self.bTestID + '-' + underLySym + '-orderlog',
            'log\\' + self.bTestID + '\\' + underLySym + '-orderRecord.txt',
            mode_='a')

        o = trailingOrder(aOrderPosition,
                          stop_type,
                          stopThresh,
                          trailing_type,
                          trailingThresh,
                          orderLog=orderLog)

        self.addStopOrder(o)
    def create_stop_order(self,
                          aOrderPosition,
                          stopThresh,
                          stopCommand='stoploss'):

        # if atradeOrder.status == ORDER_STATUS.FILLED:
        #     aOrderPosition = OrderHoldingPostion(atradeOrder)
        #     # o = stop_loss_by_order(aOrderPosition, 'percent', stopProfitThresh,)
        #     if stopCommand=='stoploss':
        #         o = StopLossOrder.__from_create__(aOrderPosition, 'percent', stopThresh)
        #     if stopCommand=='stopprofit':
        #         o = StopProfitOrder.__from_create__(aOrderPosition, 'percent', stopThresh)
        #     self.addStopOrder(o)
        #     self.addOrderPosition(aOrderPosition)
        #
        #     self.stoplossOrderCreatedEvent.emit(atradeOrder.symbol) #大概是订阅的tick函数要执行下

        underLySym = commonHelpBylw.getMainContinContract(
            aOrderPosition.symbol)
        orderLog = loggerHelpbylw.getFileLogger(
            self.bTestID + '-' + underLySym + '-orderlog',
            'log\\' + self.bTestID + '\\' + underLySym + '-orderRecord.txt',
            mode_='a')

        # o = stop_loss_by_order(aOrderPosition, 'percent', stopProfitThresh,)
        if stopCommand == 'stoploss':
            o = StopLossOrder.__from_create__(aOrderPosition,
                                              'percent',
                                              stopThresh,
                                              orderLog=orderLog)
        if stopCommand == 'stopprofit':
            o = StopProfitOrder.__from_create__(aOrderPosition,
                                                'percent',
                                                stopThresh,
                                                orderLog=orderLog)
        self.addStopOrder(o)
Exemple #6
0
def getContractsByUnderlyingSymbols(symbolsCode, sDateTime, eDateTime):

    #sDateTime是字符串类型。只有日期
    #symbolsCode 是标的资产的代码。是个list

    #10g个

    exchangelist = []
    for asym in symbolsCode:
        exchangelist.append(getExchangeFromGmSymbol(asym))
    exchangelist = list(set(exchangelist))

    month159 = month159CZCE + month159DCE + month159SHFE
    month1to12 = month1to12SHFE + month1to12INE
    month1510 = month1510SHFE + month1510CZCE
    month612 = month612SHFE

    currAllFutureContract = get_instruments(
        symbols=None,
        exchanges=exchangelist,
        sec_types=[SEC_TYPE_FUTURE],
        names=None,
        skip_suspended=True,
        skip_st=True,
        fields='symbol,exchange,sec_id,listed_date,delisted_date',
        df=True)

    currAllFutureContract['listed_date'] = currAllFutureContract[
        'listed_date'].dt.strftime('%Y-%m-%d %H:%M:%S')
    currAllFutureContract['listed_date'] = currAllFutureContract[
        'listed_date'].str[0:10]
    currAllFutureContract['delisted_date'] = currAllFutureContract[
        'delisted_date'].dt.strftime('%Y-%m-%d %H:%M:%S')
    currAllFutureContract['delisted_date'] = currAllFutureContract[
        'delisted_date'].str[0:10]

    if sDateTime and eDateTime:

        currAllFutureContract=currAllFutureContract[(currAllFutureContract['listed_date']<=sDateTime) & \
        (currAllFutureContract['delisted_date']>=eDateTime)]

    tempContract = currAllFutureContract

    finalDf = pd.DataFrame(columns=currAllFutureContract.columns)

    for inx, row in tempContract.iterrows():
        underLyingSymbol = commonHelpBylw.getMainContinContract(row['symbol'])

        #确认当前品种是我们需要的品种
        if underLyingSymbol in symbolsCode:
            if underLyingSymbol in month159:
                if row['sec_id'][-2:] in ['01', '05', '09']:

                    finalDf.loc[finalDf.shape[0]] = row
            if underLyingSymbol in month1to12:
                if row['sec_id'][-2:] in ['01', '03', '05', '07', '09', '11']:

                    finalDf.loc[finalDf.shape[0]] = row
            if underLyingSymbol in month1510:
                if row['sec_id'][-2:] in ['01', '05', '10']:

                    finalDf.loc[finalDf.shape[0]] = row
            if underLyingSymbol in month612:
                if row['sec_id'][-2:] in ['06', '12']:

                    finalDf.loc[finalDf.shape[0]] = row
            if underLyingSymbol in allCon:

                finalDf.loc[finalDf.shape[0]] = row

    i = 1
    return finalDf
Exemple #7
0
def plotResultMulContract(logDataPathDir,plotSDateTime,plotEDateTime,bTestParams,
                            firstYVarsname=[],secondYVarsname=[]):



        import os
        import re
        def getOrder(filePath):
            fileNameList = os.listdir(filePath)
            absPath = os.path.abspath(filePath)

            dfOrderSingal = pd.DataFrame(columns=["createdAt", "symbol", 'signalname'])
            for afName in fileNameList:
                fDirAndName = os.path.join(absPath, afName)

                try:
                    with open(fDirAndName, encoding='gbk')as f:
                        # with open(r'log\tradeRecord.txt',encoding='gbk')as f:
                        tmpd = pd.read_csv(f, header=None, sep=",")
                        tmpd.columns = ["createdAt", "symbol", 'signalname']
                        dfOrderSingal = dfOrderSingal.append(tmpd, ignore_index=True)


                except Exception as e:
                    print(e)
            return dfOrderSingal

        dfOrderSingal=getOrder(logDataPathDir+'orderRecord')

        lastPath=os.path.abspath(os.path.join(logDataPathDir, "../.."))
        stopFilePath=lastPath+'\\stopLossProfitLog\\livemode\\'
        stopOrder=getOrder(stopFilePath+''+'orderRecord')

        dfOrderSingal=dfOrderSingal.append(stopOrder)
        # #取委托记录
        # fileNameList=os.listdir(logDataPathDir+'orderRecord')
        # absPath=os.path.abspath(logDataPathDir+'orderRecord')
        #
        # dfOrderSingal=pd.DataFrame(columns = ["createdAt", "symbol", 'signalname'])
        # for afName in fileNameList:
        #     fDirAndName = os.path.join(absPath, afName)
        #
        #
        #
        #     try:
        #         with open(fDirAndName, encoding='gbk')as f:
        #             # with open(r'log\tradeRecord.txt',encoding='gbk')as f:
        #             tmpd=pd.read_csv(f, header=None, sep=",")
        #             tmpd.columns = ["createdAt", "symbol", 'signalname']
        #             dfOrderSingal = dfOrderSingal.append(tmpd,ignore_index=True)
        #
        #
        #     except Exception as e:
        #         print(e)

        dfOrderSingal = dfOrderSingal.loc[
            (dfOrderSingal['createdAt'] >= plotSDateTime) & (dfOrderSingal['createdAt'] <= plotEDateTime)]
        dfOrderSingal['date'] = pd.to_datetime(dfOrderSingal['createdAt'], format='%Y-%m-%d %H:%M:%S')
        dfOrderSingal['date'] = dfOrderSingal['date'].dt.tz_localize(tz=timezone(timedelta(hours=8)))






        def addASeries(varsname, yaxisindex):
            interResultAbsPath = os.path.abspath(logDataPathDir + 'interResult')
            for aname in varsname:

                filenameAndPath= os.path.join(interResultAbsPath, asymbol+'-'+aname+'.txt')
                with open(filenameAndPath, encoding='gbk')as f:
                    # with open('log\\%s.txt'%(aname),encoding='gbk')as f:

                    aVar = pd.read_csv(f, header=None, sep=",")
                    aVar.columns = ["createdAt", aname]
                    aVar = aVar.loc[(aVar['createdAt'] >= plotSDateTime) & (aVar['createdAt'] <= plotEDateTime)]
                    aVar['date'] = pd.to_datetime(aVar['createdAt'], format='%Y-%m-%d %H:%M:%S')
                    aVar['date'] = aVar['date'].dt.tz_localize(tz=timezone(timedelta(hours=8)))
                if aname == 'macd':
                    plotHelpbylw.addASeries(H, aVar[['date', aname]], aname, yaxisIndex=yaxisindex,
                                            seriesType='column')
                else:
                    plotHelpbylw.addASeries(H, aVar[['date', aname]], aname, yaxisIndex=yaxisindex)





        symlist=list(dfOrderSingal['symbol'].drop_duplicates().values)
        for asymbol in symlist:


            #先画合约的k线,然后委托标记 打上去。
            aUnderLyAsset = commonHelpBylw.getMainContinContract(asymbol)
            # print(asymbol)
            # if aUnderLyAsset!='CZCE.MA':
            #     continue

            if asymbol=='DCE.j2001':
                i=1


            sfrestr = bTestParams[aUnderLyAsset]['fre']
            gmFreStr = parseToGmFre(sfrestr)
            H = plotHelpbylw.plotAContractCandle(asymbol, plotSDateTime, plotEDateTime, fre=gmFreStr)

            currDf = dfOrderSingal.loc[dfOrderSingal['symbol'] == asymbol]
            plotHelpbylw.plotSingal(H, currDf, asymbol)





           #画该品种的中间结果

            # interResultFileNameList = os.listdir(logDataPathDir + 'interResult')
            # interResultAbsPath = os.path.abspath(logDataPathDir + 'interResult')
            #
            # for afile in interResultFileNameList:
            #
            #     splits=re.split('-|.',afile)
            #
            #     sym=splits[0]
            #     varName=splits[1]
            #
            #
            #     interResultFilePath = os.path.join(interResultFileNameList, interResultAbsPath)

            addASeries(firstYVarsname, 0)

            # 如果外界参数显示,需要画图的中间变量至少有1个
            # 设置y
            if len(secondYVarsname) >= 1:
                yAxis = [{'height': '70%', 'resize': {'enabled': True}},
                         {'top': '70%', 'height': '30%'}]

                H.set_options('yAxis', yAxis)
                addASeries(secondYVarsname, 1)

            filename = logDataPathDir + asymbol
            H.save_file(filename)
    def onTrade(self, tradedict, context):

        #如果是开仓指令的trade来了,那么就考虑tradeorder是否已经全部成交了,成交了则考虑 建立止盈止损指令了
        #如果是平仓指令,那么就是考察orderposition是不是有影响

        #如果是开仓动作的交易回报,那么去处理 tradeorder,这个tradeorder就是记录开仓的委托的
        if tradedict['position_effect'] == PositionEffect_Open:
            # 在这里给委托补充持仓均价字段。
            atradeOrder = self.trade_orders.get(tradedict['orderID'])
            if atradeOrder is not None:
                atradeOrder.fill(tradedict)

                #order 完全成交了,那么创建orderposition ,创建止盈止损指令。
                if atradeOrder.status == ORDER_STATUS.FILLED:
                    aOrderPosition = OrderHoldingPostion(atradeOrder)
                    self.addOrderPosition(aOrderPosition)

                    #给aOrderPosition 中的 startStopEvent 引用订阅行情的动作,这样当aOrderPosition第一次建立了
                    #止盈止损的时候,需要取订阅行情
                    subgmFun = partial(context.subscribe, frequency='tick')
                    aOrderPosition.startStopEvent.subscribe(subgmFun)

                    lwSubscribeFun = partial(context.subcribeObj.add,
                                             fre='tick')
                    aOrderPosition.startStopEvent.subscribe(lwSubscribeFun)

                    aSymbol = aOrderPosition.symbol
                    underLyingSymbol = commonHelpBylw.getMainContinContract(
                        aSymbol)
                    stopLossThresh = context.bTestParams[underLyingSymbol][
                        'stopLossRatio']
                    stopProfitThresh = context.bTestParams[underLyingSymbol][
                        'stopProfitRatio']

                    trailing_type = context.bTestParams[underLyingSymbol][
                        'trailing_type']
                    trailingThresh = context.bTestParams[underLyingSymbol][
                        'trailingThresh']
                    trailing_stop_type = context.bTestParams[underLyingSymbol][
                        'trailing_stop_type']
                    trailing_stopThresh = context.bTestParams[
                        underLyingSymbol]['trailing_stopThresh']

                    self.create_stop_order(aOrderPosition,
                                           stopThresh=stopLossThresh,
                                           stopCommand='stoploss')

                    # 再创建一个止盈指令
                    # stopProfit = partial(context.simuBroker4StopLossProfit.create_stop_order,
                    #                      stopThresh=stopProfitThresh, stopCommand='stopprofit')
                    # tradeo.orderTotalFIlledEvent.subscribe(stopProfit)

                    self.create_stop_order(aOrderPosition,
                                           stopThresh=stopProfitThresh,
                                           stopCommand='stopprofit')

                    self.create_trailing_order(aOrderPosition, trailing_type,
                                               trailingThresh,
                                               trailing_stop_type,
                                               trailing_stopThresh)

            self._deleteTradeOrders(
            )  #因为tradeorder已经完成了,stoporder会建立起来,所以应该清除掉了。

        if tradedict['position_effect'] in [
                PositionEffect_Close, PositionEffect_CloseToday,
                PositionEffect_CloseYesterday
        ]:

            # for aSLOrder in self._stoploss_orders:
            #     aSLOrder.onTrade(tradedict)

            for aOP in self.orderPostions:
                aOP.onTrade(tradedict)

            # self.deleteSLOrdersByClearPosition()
            self.deleteOrderPositions()  #因为持仓可能为0,所以清除掉
            self.deleteSLOrders()  #因为持仓可能为0,所以清除掉可能导致order的状态变为失效
Exemple #9
0
 def getHotContractCurrDays(self, symbol, currTDays):
     # 获取下一个主力合约 代码
     mainContract = commonHelpBylw.getMainContinContract(symbol)
     currMainSymbol = self.__mainContractData.loc[currTDays, mainContract]
     return currMainSymbol