Example #1
0
    def update_signal(self, event):
        """ 处理策略函数产生的下单事件。

        可能产生一系列order事件,在bar的开盘时间交易。
        """
        assert event.type == Event.SIGNAL
        new_orders = []
        for order in event.orders:
            errmsg = self._valid_order(order)
            if errmsg == '':
                order.datetime = self._datetime
                new_orders.append(order)
                if order.side == TradeSide.KAI:
                    self.holding['cash'] -= \
                        order.order_margin(self._bars[order.contract].open)
            else:
                logger.warn(errmsg)
                # print len(event.orders), len(new_orders)
                continue
        self.open_orders.update(new_orders)  # 改变对象的值,不改变对象地址。
        self._all_orders.extend(new_orders)
        for order in new_orders:
            self.api.order(copy.deepcopy(order))
        for order in new_orders:
            if order.side == TradeSide.PING:
                pos = self.positions[
                    PositionKey(order.contract, order.direction)]
                pos.closable -= order.quantity
Example #2
0
 def _valid_order(self, order):
     """ 判断订单是否合法。 """ 
     if order.side == TradeSide.PING:
         try:
             pos = self.current_positions[order.contract]
             if pos.quantity >= order.quantity:
                 return True 
         except KeyError:
             # 没有持有该合约
             logger.warn("不存在合约[%s]" % order.contract)
             #assert False
             return False
         logger.warn("下单仓位问题")
         return False
     elif order.side == TradeSide.KAI:
         if self.current_holdings['cash'] < order.price * order.quantity:
             raise Exception('没有足够的资金开仓') 
     return True
Example #3
0
 def _valid_order(self, order):
     if order.quantity <= 0:
         logger.warn("下单数量错误!")
         return False
     """ 判断订单是否合法。 """
     if order.side == TradeSide.PING:
         try:
             poskey = PositionKey(order.contract, order.direction)
             pos = self.positions[poskey]
             if pos.quantity >= order.quantity:
                 return True
         except KeyError:
             # 没有持有该合约
             logger.warn("不存在合约[%s]" % order.contract)
             #assert False
             return False
         logger.warn("下单仓位问题")
         return False
     elif order.side == TradeSide.KAI:
         if self.holding['cash'] < order.price * order.quantity:
             raise TradingError(err='没有足够的资金开仓')
         else:
             new_price = self._ticks[order.contract]
             self.holding['cash'] -= order.order_margin(new_price)
     return True
Example #4
0
 def _valid_order(self, order):
     """ 判断订单是否合法。 """ 
     if order.quantity<=0:
         logger.warn("下单数量错误!")
         return False 
     # 撤单
     if order.side == TradeSide.CANCEL:
         if order in self.open_orders:
             return True  
         else:
             raise TradingError(err='撤销失败: 不存在该订单!') 
     if order.side == TradeSide.PING:
         try:
             poskey = PositionKey(order.contract, order.direction)
             pos = self.positions[poskey]
             if pos.quantity >= order.quantity:
                 return True 
         except KeyError:
             # 没有持有该合约
             logger.warn("不存在合约[%s]" % order.contract)
             #assert False
             return False
         logger.warn("下单仓位问题")
         return False
     elif order.side == TradeSide.KAI:
         if self.holding['cash'] < order.price * order.quantity:
             raise TradingError(err='没有足够的资金开仓') 
         else:
             new_price = self._ticks[order.contract]
             self.holding['cash'] -= order.order_margin(new_price)
     return True
Example #5
0
 def process_trading_events(self, append):
     """ 提交订单,撮合,更新持仓 """
     if self._orders:
         self.events_pool.put(SignalEvent(self._orders))
     self._orders = []
     new_signal = False # 保证至少一次价格撮合。
     event = None
     while True:
        # 事件处理。 
         try:
             event = self.events_pool.get()
         except Queue.Empty:
             assert(False)
         except IndexError:
             if new_signal:
                 break
         else:
             #if event.type == 'MARKET':
                 #strategy.calculate_signals(event)
                 #port.update_timeindex(event)
             if event.type == Event.SIGNAL:
                 try:
                     self.blotter.update_signal(event)
                 except TradingError as e:
                     new_signal = True
                     logger.warn(e)
                     return
             elif event.type == Event.ORDER:
                 self.exchange.insert_order(event)
             elif event.type == Event.FILL:
                 # 模拟交易接口收到报单成交
                 self.blotter.api.on_transaction(event)
         # 价格撮合。note: bar价格撮合要求撮合置于运算后面。
         if event == None or event.type == Event.ORDER:
             self.exchange.make_market(self.blotter._bars)
             new_signal = True
     self.blotter.update_status(self._datetime, append)
Example #6
0
 def process_trading_events(self, append):
     """ 提交订单,撮合,更新持仓 """
     if self._orders:
         self.events_pool.put(SignalEvent(self._orders))
     self._orders = []
     new_signal = False # 保证至少一次价格撮合。
     event = None
     while True:
        # 事件处理。 
         try:
             event = self.events_pool.get()
         except Queue.Empty:
             assert(False)
         except IndexError:
             if new_signal:
                 break
         else:
             #if event.type == 'MARKET':
                 #strategy.calculate_signals(event)
                 #port.update_timeindex(event)
             if event.type == Event.SIGNAL:
                 try:
                     self.blotter.update_signal(event)
                 except TradingError as e:
                     new_signal = True
                     logger.warn(e)
                     return
             elif event.type == Event.ORDER:
                 self.exchange.insert_order(event)
             elif event.type == Event.FILL:
                 # 模拟交易接口收到报单成交
                 self.blotter.api.on_transaction(event)
         # 价格撮合。note: bar价格撮合要求撮合置于运算后面。
         if event == None or event.type == Event.ORDER:
             self.exchange.make_market(self.blotter._bars)
             new_signal = True
     self.blotter.update_status(self._datetime, append)