Beispiel #1
0
    def GetDataAndBars(self):
        """"""
        stra = self.stra
        orders = stra.Orders
        # orders = [{"Direction": 0, "DateTime": "20161019 14:00:00", "Price": 2300},
        # #         {"Direction":1,"DateTime":"20161019 09:00:00","Price":2400}]
        orders_json = []
        for i in range(0, len(orders)):
            # 遇到diction=Diction.Buy转换后:diction:<Diction.Buy:1> 后面报错
            # orders_str.append(ord.__dict__)
            ord = orders[i]
            orders_json.append({"DateTime": ord.DateTime.replace('-', ''), "Direction": (0 if ord.Direction == DirectType.Buy else 1), "Offset": 0 if ord.Offset == OffsetType.Open else 1, "Price": ord.Price})

        it = 'year'
        for case in switch(stra.IntervalType):
            if case(IntervalType.Minute):
                it = 'min'
                break
            if case(IntervalType.Hour):
                it = 'hour'
                break
            if case(IntervalType.Day):
                it = 'day'
                break
            if case(IntervalType.Month):
                it = 'month'
                break

        data_req = {
            'instrument': stra.Instrument,
            'begin': stra.BeginDate,
            'end': stra.EndDate,
            'interval': stra.Interval,
            'intervalType': it,
        }

        indexes_json = []
        for key, values in stra.IndexDict.items():
            array = []
            for value in values:
                array.append(value)
            indexes_json.append({'name': key, 'array': array})

        bars_json = []
        for bar in stra.Bars:
            bars_json.append({"Open": bar.O, "High": bar.H, "Low": bar.L, "Close": bar.C, "Date": bar.D})

        report_json = self.Report

        # data_req = json.dumps(data_req)
        # orders_json = json.dumps(orders_json)
        # indexes_json = json.dumps(indexes_json)
        # report = json.dumps(report, ensure_ascii=False)

        data = {'data_req': data_req, 'orders': orders_json, 'indexes': indexes_json, 'report': report_json}
        return data, bars_json
Beispiel #2
0
    def __order__(self, direction, offset, price, volume, remark):
        """策略执行信号"""

        if self.SingleOrderOneBar and (self.LastEntryDateLong == self.D[-1]
                                       or self.LastEntryDateShort == self.D[-1]
                                       or self.ExitDateLong == self.D[-1]
                                       or self.ExitDateShort == self.D[-1]):
            return
        order = OrderItem()
        order.Instrument = self.Instrument
        order.DateTime = self.D[-1]
        order.Direction = direction
        order.Offset = offset
        order.Price = price
        order.Volume = volume
        order.Remark = remark

        self.Orders.append(order)

        # 处理策略相关属性
        order.IndexEntryLong = self._lastOrder.IndexEntryLong
        order.IndexExitLong = self._lastOrder.IndexExitLong
        order.IndexEntryShort = self._lastOrder.IndexEntryShort
        order.IndexExitShort = self._lastOrder.IndexExitShort
        order.IndexLastEntryLong = self._lastOrder.IndexLastEntryLong
        order.IndexLastEntryShort = self._lastOrder.IndexLastEntryShort
        order.AvgEntryPriceLong = self._lastOrder.AvgEntryPriceLong
        order.AvgEntryPriceShort = self._lastOrder.AvgEntryPriceShort
        order.PositionLong = self._lastOrder.PositionLong
        order.PositionShort = self._lastOrder.PositionShort
        order.EntryDateLong = self._lastOrder.EntryDateLong
        order.EntryDateShort = self._lastOrder.EntryDateShort
        order.EntryPriceLong = self._lastOrder.EntryPriceLong
        order.EntryPriceShort = self._lastOrder.EntryPriceShort
        order.ExitDateLong = self._lastOrder.ExitDateLong
        order.ExitDateShort = self._lastOrder.ExitDateShort
        order.ExitPriceLong = self._lastOrder.ExitPriceLong
        order.ExitPriceShort = self._lastOrder.ExitPriceShort
        order.LastEntryDateLong = self._lastOrder.LastEntryDateLong
        order.LastEntryDateShort = self._lastOrder.LastEntryDateShort
        order.LastEntryPriceLong = self._lastOrder.LastEntryPriceLong
        order.LastEntryPriceShort = self._lastOrder.LastEntryPriceShort

        diroff = '{0}-{1}'.format(order.Direction.name, order.Offset.name)
        for case in switch(diroff):
            if case('Buy-Open'):
                order.PositionLong += order.Volume
                order.AvgEntryPriceLong = (
                    self._lastOrder.PositionLong *
                    self._lastOrder.AvgEntryPriceLong + order.Volume *
                    order.Price) / (self._lastOrder.Volume + order.Volume)
                if self._lastOrder.PositionLong == 0:
                    order.IndexEntryLong = len(self.Bars) - 1
                    order.EntryDateLong = self.D[-1]  # str '20160630 21:25:00'
                    order.EntryPriceLong = order.Price
                order.IndexLastEntryLong = len(self.Bars) - 1
                order.LastEntryPriceLong = order.Price
                order.LastEntryDateLong = self.D[-1]
                break

            if case('Buy-Close'):
                c_lots = min(self._lastOrder.PositionShort,
                             order.Volume)  # 能够平掉的数量
                if c_lots <= 0:  # 无仓可平
                    print('平仓量>持仓量')
                    break
                order.PositionShort -= c_lots

                order.IndexExitShort = len(self.Bars) - 1
                order.ExitDateShort = self.D[-1]
                order.ExitPriceShort = order.Price
                break

            if case('Sell-Open'):
                order.PositionShort += order.Volume
                order.AvgEntryPriceShort = (
                    self._lastOrder.PositionShort *
                    self._lastOrder.AvgEntryPriceShort + order.Volume *
                    order.Price) / (self._lastOrder.Volume + order.Volume)
                if self._lastOrder.PositionShort == 0:
                    order.IndexEntryShort = len(self.Bars) - 1
                    order.EntryDateShort = self.D[
                        -1]  # time or double or str ???
                    order.EntryPriceShort = order.Price
                order.IndexLastEntryShort = len(self.Bars) - 1
                order.LastEntryPriceShort = order.Price
                order.LastEntryDateShort = self.D[-1]
                break

            if case('Sell-Close'):
                c_lots = min(self._lastOrder.PositionLong,
                             order.Volume)  # 能够平掉的数量
                if c_lots <= 0:  # 无仓可平
                    print('平仓量>持仓量')
                    break
                order.PositionLong -= c_lots

                order.IndexExitLong = len(self.Bars) - 1
                order.ExitDateLong = self.D[-1]
                order.ExitPriceLong = order.Price
                break

        self._lastOrder = order
        self.stra_onorder(self, order)
Beispiel #3
0
    def __new_min_bar__(self, bar):
        """有新min_bar添加"""

        bar_time = time.strptime(bar.D, "%Y%m%d %H:%M:%S")
        year = bar_time.tm_year
        mon = bar_time.tm_mon
        day = bar_time.tm_mday
        hour = bar_time.tm_hour
        mins = bar_time.tm_min
        for case in switch(self.IntervalType):
            if case(IntervalType.Minute):
                mins = bar_time.tm_min // self.Interval * self.Interval
                break
            if case(IntervalType.Hour):
                hour = hour // self.Interval
                mins = 0
                break
            if case(IntervalType.Day):
                hour = 0
                mins = 0
                break
            if case(IntervalType.Month):
                hour = 0
                mins = 0
                day = 1
                break
            if case(IntervalType.Year):
                hour = 0
                mins = 0
                day = 1
                mon = 1
                break
            if case(IntervalType.Week):
                hour = 0
                mins = 0
                # 用周号替换日期
                day = time.strftime('%W', bar_time)
                break

        bar_time = time.strptime(
            '{0}{1}{2} {3}:{4}'.format(year, mon, day, hour, mins),
            '%Y%m%d %H:%M')
        # time -> str
        bar_time = time.strftime('%Y%m%d %H:%M:%S', bar_time)
        if len(self.Bars) == 0 or self.Bars[-1].D != bar_time:
            bar.D = bar_time
            self.Bars.append(bar)

            self.D = np.append(self.D, bar.D)
            self.H = np.append(self.H, bar.H)
            self.L = np.append(self.L, bar.L)
            self.O = np.append(self.O, bar.O)
            self.C = np.append(self.C, bar.C)
            self.V = np.append(self.V, bar.V)
            self.I = np.append(self.I, bar.I)
        else:
            old_bar = self.Bars[-1]
            self.H[-1] = old_bar.H = max(bar.H, old_bar.H)
            self.L[-1] = old_bar.L = min(bar.L, old_bar.L)
            self.C[-1] = old_bar.C = bar.C
            old_bar.V += bar.V
            self.V[-1] = old_bar.V
            self.I[-1] = old_bar.I = bar.I
            # bar.A = tick.AveragePrice

        self.stra_uppdate(self, bar)
Beispiel #4
0
    def ReqOrderInsert(self,
                       pInstrument='',
                       pDirection=DirectType,
                       pOffset=OffsetType,
                       pPrice=0.0,
                       pVolume=1,
                       pType=OrderType.Limit,
                       pCustom=0):
        """"""
        OrderPriceType = OrderPriceTypeType.AnyPrice
        TimeCondition = TimeConditionType.IOC
        LimitPrice = 0.0
        VolumeCondition = VolumeConditionType.AV

        for case in switch(pType):
            if case(OrderType.Market):  # 市价
                OrderPriceType = OrderPriceTypeType.AnyPrice
                TimeCondition = TimeConditionType.IOC
                LimitPrice = 0.0
                VolumeCondition = VolumeConditionType.AV
                break
            if case(OrderType.Limit):  # 限价
                OrderPriceType = OrderPriceTypeType.LimitPrice
                TimeCondition = TimeConditionType.GFD
                LimitPrice = pPrice
                VolumeCondition = VolumeConditionType.AV
                break
            if case(OrderType.FAK):  # FAK
                OrderPriceType = OrderPriceTypeType.LimitPrice
                TimeCondition = TimeConditionType.IOC
                LimitPrice = pPrice
                VolumeCondition = VolumeConditionType.AV
                break
            if case(OrderType.FOK):  # FOK
                OrderPriceType = OrderPriceTypeType.LimitPrice
                TimeCondition = TimeConditionType.IOC
                LimitPrice = pPrice
                VolumeCondition = VolumeConditionType.CV  # 全部数量
                break

        self._req += 1
        self.t.ReqOrderInsert(
            BrokerID=self.BrokerID,
            InvestorID=self.Investor,
            InstrumentID=pInstrument,
            OrderRef="%06d%06d" % (self._req, pCustom % 1000000),
            UserID=self.Investor,
            # 此处ctp_enum与at_struct名称冲突
            Direction=DirectionType.Buy
            if pDirection == DirectType.Buy else DirectionType.Sell,
            CombOffsetFlag=chr(
                OffsetFlagType.Open if pOffset == OffsetType.Open else (
                    OffsetFlagType.CloseToday if pOffset ==
                    OffsetType.CloseToday else OffsetFlagType.Close)),
            CombHedgeFlag=HedgeFlagType.Speculation.__char__(),
            IsAutoSuspend=0,
            ForceCloseReason=ForceCloseReasonType.NotForceClose,
            IsSwapOrder=0,
            ContingentCondition=ContingentConditionType.Immediately,
            VolumeCondition=VolumeCondition,
            MinVolume=1,
            VolumeTotalOriginal=pVolume,
            OrderPriceType=OrderPriceType,
            TimeCondition=TimeCondition,
            LimitPrice=LimitPrice,
        )