def _force_close(self): """ 在回测的最后一根k线以close价格强平持仓位。 """ force_trans = [] if self._all_transactions: price_type = self._all_transactions[-1].price_type else: price_type = PriceType.LMT for pos in self.positions.values(): order = Order( self._datetime, pos.contract, price_type, TradeSide.PING, pos.direction, self._bars[pos.contract].close, pos.quantity ) force_trans.append(Transaction(order)) for trans in force_trans: self._update_holding(trans) self._update_positions(trans) if force_trans: self.update_status(trans.datetime, False, False) self.positions = {} return
def sell(self, direction, price, quantity, price_type, contract): self._orders.append(Order( None, contract, price_type, TradeSide.PING, direction, float(price), quantity ))
def buy(self, direction, price, quantity, price_type='LMT', contract=None): """ 开仓。 :param str/int direction: 下单方向。多头 - 'long' / 1 ;空头 - 'short' / 2 :param float price: 价格。 :param int quantity: 数量。 :param str/int price_type: 下单价格类型。限价单 - 'lmt' / 1;市价单 - 'mkt' / 2 """ contract = None con = Contract(contract) if contract else self._main_contract self._orders.append( Order(self.datetime, con, PriceType.arg_to_type(price_type), TradeSide.KAI, Direction.arg_to_type(direction), float(price), quantity))
def sell(self, price, quantity, symbol=None): """ 平多仓。 Args: price (float): 价格, 0表市价。 quantity (int): 数量。 symbol (str): 合约 """ if not self.on_bar: raise Exception('只有on_bar函数内能下单!') if symbol: contract = Contract(symbol) if isinstance(symbol, str) else symbol else: contract = self.contract price_type = PriceType.MKT if price == 0 else PriceType.LMT self._orders.append( Order(None, contract, price_type, TradeSide.CLOSE, Direction.LONG, float(price), quantity))
def cover(self, price, quantity, price_type, contract): self._exit_orders.append( Order(None, contract, price_type, TradeSide.PING, Direction.SHORT, float(price), quantity))
def short(self, price, quantity, price_type, contract): self._entry_orders.append( Order(None, contract, price_type, TradeSide.KAI, Direction.SHORT, float(price), quantity))
def buy(self, price, quantity, price_type, contract): self._orders.append( Order(None, contract, price_type, TradeSide.KAI, Direction.LONG, float(price), quantity))