Пример #1
0
 def GetPositions(self, ClientCode, FirmId, LimitKind, Lots):
     """Все активные позиции по счету"""
     if FirmId == 'SPBFUT':  # Для фьючерсов свои расчеты
         futuresHoldings = self.qpProvider.GetFuturesHoldings()[
             'data']  # Все фьючерсные позиции
         activeFuturesHoldings = [
             futuresHolding for futuresHolding in futuresHoldings
             if futuresHolding['totalnet'] != 0
         ]  # Активные фьючерсные позиции
         for activeFuturesHolding in activeFuturesHoldings:  # Пробегаемся по всем активным фьючерсным позициям
             classCode = 'SPBFUT'  # Код площадки
             secCode = activeFuturesHolding['sec_code']  # Код тикера
             dataname = self.ClassSecCodeToDataName(
                 classCode, secCode
             )  # Получаем название тикера по коду площадки и коду тикера
             size = activeFuturesHolding['totalnet']  # Кол-во
             if Lots:  # Если входящий остаток в лотах
                 size = self.LotsToSize(
                     classCode, secCode,
                     size)  # то переводим кол-во из лотов в штуки
             price = float(
                 activeFuturesHolding['avrposnprice'])  # Цена приобретения
             price = self.QKToBTPrice(
                 classCode, secCode, price
             )  # Переводим цену приобретения за лот в цену приобретения за штуку
             self.positions[dataname] = Position(
                 size, price)  # Сохраняем в списке открытых позиций
     else:  # Для остальных фирм
         depoLimits = self.qpProvider.GetAllDepoLimits()[
             'data']  # Все лимиты по бумагам (позиции по инструментам)
         accountDepoLimits = [
             depoLimit for depoLimit in depoLimits  # Бумажный лимит
             if depoLimit['client_code'] == ClientCode
             and  # выбираем по коду клиента
             depoLimit['firmid'] == FirmId and  # фирме
             depoLimit['limit_kind'] == LimitKind and  # дню лимита
             depoLimit['currentbal'] != 0
         ]  # только открытые позиции
         for firmKindDepoLimit in accountDepoLimits:  # Пробегаемся по всем позициям
             dataname = firmKindDepoLimit[
                 'sec_code']  # В позициях код тикера указывается без кода площадки
             classCode, secCode = self.DataNameToClassSecCode(
                 dataname
             )  # По коду тикера без площадки получаем код площадки и код тикера
             size = int(firmKindDepoLimit['currentbal'])  # Кол-во
             if Lots:  # Если входящий остаток в лотах
                 size = self.LotsToSize(
                     classCode, secCode,
                     size)  # то переводим кол-во из лотов в штуки
             price = float(firmKindDepoLimit['wa_position_price']
                           )  # Цена приобретения
             price = self.QKToBTPrice(
                 classCode, secCode, price
             )  # Для рынка облигаций цену приобретения умножаем на 10
             dataname = self.ClassSecCodeToDataName(
                 classCode, secCode
             )  # Получаем название тикера по коду площадки и коду тикера
             self.positions[dataname] = Position(
                 size, price)  # Сохраняем в списке открытых позиций
Пример #2
0
    def update_positions(self):
        """
        this method syncs the Alpaca real broker positions and the Backtrader
        broker instance. the positions is defined in BrokerBase(in getposition)
        and used in bbroker (the backtrader broker instance) with Data as the
        key. so we do the same here. we create a defaultdict of Position() with
        data as the key.
        :return: collections.defaultdict ({data: Position})
        """
        positions = collections.defaultdict(Position)
        if self.p.use_positions:
            broker_positions = self.o.oapi.list_positions()
            broker_positions_symbols = [p.symbol for p in broker_positions]
            broker_positions_mapped_by_symbol = \
                {p.symbol: p for p in broker_positions}

            for name, data in iteritems(self.cerebro.datasbyname):
                if name in broker_positions_symbols:

                    is_sell = broker_positions_mapped_by_symbol[name].side ==\
                              'short'
                    size = broker_positions_mapped_by_symbol[name].qty
                    if is_sell:
                        size = -size
                    positions[data] = Position(
                        size, broker_positions_mapped_by_symbol[name].
                        avg_entry_price)
        return positions
Пример #3
0
 def updateposition(self, data):
     """Update position from streamer"""
     try:
         position = Position(data['Qty'],
                             abs(data['TotalAmt']/data['Qty']))
         self.positions[data['ProdCode']] = position
     except KeyError:
         print("key-error in updateposition", data, file=self.log)
Пример #4
0
    def start(self):
        super(CtpBroker, self).start()
        self.o.start(broker=self)
        self.startingcash = self.cash = cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()

        if self.p.use_positions:
            for instrument, p in self.o.get_positions().items():
                self.positions[instrument] = Position(p.size, p.price)
Пример #5
0
    def _fill(self, oref, size, price, **kwargs):
        order = self.o.order_by_ref(oref)
        if order is None:
            return
        if 'pqty' in kwargs and \
           'avgprice' in kwargs:
            pos = Position(kwargs['pqty'], kwargs['avgprice'])
        else:
            data = order.data
            pos = self.getposition(data)
        psize, pprice, opened, closed = pos.update(size, price)

        closedvalue = closedcomm = 0.0
        openedvalue = openedcomm = 0.0
        margin = pnl = 0.0

        order.execute(data.datetime[0], size, price, closed, closedvalue,
                      closedcomm, opened, openedvalue, openedcomm, margin, pnl,
                      psize, pprice)
Пример #6
0
 def on_position(self, position: PositionData, last=False):
     is_sell = position.direction == Direction.SHORT
     size = position.volume
     if is_sell:
         size = -size
     price = position.price
     self._positions[position.symbol] = Position(size, price)
     if last:
         self._pos_inited = True
         for k, v in self._positions.items():
             print(f"intrument: {k}, size: {v.size}, price: {v.price}")
Пример #7
0
    def _fill(self, oref, size, price, **kwargs):
        order = self.o.order_by_ref(oref)
        if order is None:
            return
        if 'pqty' in kwargs and \
           'avgprice' in kwargs:
            pos = Position(kwargs['pqty'],
                           kwargs['avgprice'])
        else:
            data = order.data
            pos = self.getposition(data)
        psize, pprice, opened, closed = pos.update(size, price)

        closedvalue = closedcomm = 0.0
        openedvalue = openedcomm = 0.0
        margin = pnl = 0.0

        order.execute(data.datetime[0], size, price,
                      closed, closedvalue, closedcomm,
                      opened, openedvalue, openedcomm,
                      margin, pnl,
                      psize, pprice)
Пример #8
0
    def start(self):
        super().start()
        self.k.start(broker=self)
        self.startingcash = self.cash = self.k.get_cash()
        self.startingvalue = self.value = self.k.get_value()

        if self.p.use_positions:  # pylint: disable=no-member
            for p in self.k.get_positions():
                is_sell = p['side'] == 'sell'
                size = p['units']
                if is_sell:
                    size = -size
                price = p['avgPrice']
                self.positions[p['instrument']] = Position(size, price)
Пример #9
0
    def start(self):
        super().start()
        self.k.start(broker=self)
        self.startingcash = self.cash = self.k.get_cash()
        self.startingvalue = self.value = self.k.get_value()

        if self.p.use_positions:  # pylint: disable=no-member
            for p in self.k.get_positions():
                is_sell = p["side"] == "sell"
                size = p["units"]
                if is_sell:
                    size = -size
                price = p["avgPrice"]
                self.positions[p["instrument"]] = Position(size, price)
    def start(self):
        super(OandaV20Broker, self).start()
        self.addcommissioninfo(self, OandaV20CommInfo(mult=1.0,
                                                      stocklike=False))
        self.o.start(broker=self)
        self.startingcash = self.cash = cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()

        if self.p.use_positions:
            for p in self.o.get_positions():
                print('position for instrument:', p['instrument'])
                size = float(p['long']['units']) + float(p['short']['units'])
                price = (float(p['long']['averagePrice'])
                         if size > 0 else float(p['short']['averagePrice']))
                self.positions[p['instrument']] = Position(size, price)
Пример #11
0
    def start(self):
        super(OandaBroker, self).start()
        self.o.start(broker=self)
        self.startingcash = self.cash = cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()

        if self.p.use_positions:
            for p in self.o.get_positions():
                print('position for instrument:', p['instrument'])
                is_sell = p['side'] == 'sell'
                size = p['units']
                if is_sell:
                    size = -size
                price = p['avgPrice']
                self.positions[p['instrument']] = Position(size, price)
Пример #12
0
    def start(self):
        super(IGBroker, self).start()
        self.addcommissioninfo(self, IGCommInfo(mult=1.0, stocklike=False))
        self.o.start(broker=self)
        self.startingcash = self.cash = cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()

        if self.p.use_positions:
            for p in self.o.get_positions():
                print('position for instrument:', p['market']['epic'])
                is_sell = p['position']['direction'] == 'SELL'
                size = p['position']['dealSize']
                if is_sell:
                    size = -size
                price = p['position']['openLevel']
                self.positions[p['market']['epic']] = Position(size, price)
Пример #13
0
    def start(self):
        super(AlpacaBroker, self).start()
        self.addcommissioninfo(self, AlpacaCommInfo(mult=1.0, stocklike=False))
        self.o.start(broker=self)
        self.startingcash = self.cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()

        if self.p.use_positions:
            for p in self.o.get_positions():
                # print('position for instrument:', p['symbol'])
                # print('position for instrument:', p.symbol)
                is_sell = p.side == 'short'
                size = float(p.qty)
                if is_sell:
                    size = -size
                price = float(p.avg_entry_price)
                self.positions[p.symbol] = Position(size, price)
Пример #14
0
    def start(self):
        super(fxcmBroker, self).start()
        self.o.start(broker=self)
        self.startingcash = self.cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()
        comminfo = fxcmCommInfo(leverage=self.o.get_leverage(),
                                stocklike=False,
                                commtype=CommInfoBase.COMM_FIXED)
        # set as default comminfo
        self.addcommissioninfo(comminfo, name=None)

        if self.p.use_positions:
            positions = self.o.get_positions()
            if positions is None:
                return
            for p in positions:
                size = float(p['long']['units']) + float(p['short']['units'])
                price = (float(p['long']['averagePrice'])
                         if size > 0 else float(p['short']['averagePrice']))
                self.positions[p['instrument']] = Position(size, price)
Пример #15
0
    def start(self):
        super(MTraderBroker, self).start()
        self.addcommissioninfo(self, MTraderCommInfo(mult=1.0, stocklike=False))
        self.o.start(broker=self)
        # Check MetaTrader account
        self.o.check_account()
        # Get balance on start
        self.o.get_balance()
        self.startingcash = self.cash = self.o.get_cash()
        self.startingvalue = self.value = self.o.get_value()

        if self.p.use_positions:
            for p in self.o.get_positions():
                # print('position for instrument:', p.symbol)
                is_sell = p.type.endswith("_SELL")
                size = float(p.volume)
                if is_sell:
                    size = -size
                price = float(p.open)
                self.positions[p.symbol] = Position(size, price)
    def rebuild_positions(self):
        datas = dict((d._name, d) for d in self.o.datas)

        for p in self.o.get_positions():
            print('position for instrument:', p)
            size = float(p.volume)
            is_buy = p.type.endswith("_BUY")
            if not is_buy:
                size = -size
            price = float(p.open)
            if not self.positions[p.symbol]:
                self.positions[p.symbol] = Position(size, price)
            else:
                self.positions[p.symbol].update(size, price)

            data = datas.get(p.symbol, None)
            if data is None:
                logger.warn("data %s not found", p.symbol)
                continue

            # Info
            info = p.comment
            if "ref" in info:
                Order.refbasis = itertools.count(info["ref"])

            # Parent order
            PRClass = BuyOrder if is_buy else SellOrder
            order = PRClass(
                data=data,
                size=float(p.volume),
                price=float(p.open),
                exectype=Order.Market,
                transmit=p.stoploss <= 0 and p.takeprofit <= 0,
                simulated=True,
            )
            pref = order.ref
            self.orders[order.ref] = order
            self.brackets[pref] = [order]
            self.o.rebuild_order(order, p.id)

            # Stoploss
            if p.stoploss > 0:
                if "sl" in info:
                    Order.refbasis = itertools.count(info["sl"])

                # opposite with position size
                SLClass = SellOrder if is_buy else BuyOrder

                slorder = SLClass(
                    data=data,
                    size=float(p.volume),
                    price=float(p.stoploss),
                    exectype=Order.Stop,
                    parent=order,
                    transmit=p.takeprofit <= 0,
                    simulated=True,
                )
                self.orders[slorder.ref] = slorder
                self.brackets[pref].append(slorder)

            # Takeprofit
            if p.takeprofit > 0:
                if "tp" in info:
                    Order.refbasis = itertools.count(info["tp"])

                # opposite with position size
                TPClass = SellOrder if is_buy else BuyOrder

                tporder = TPClass(
                    data=data,
                    size=float(p.volume),
                    price=float(p.takeprofit),
                    exectype=Order.Limit,
                    parent=order,
                    transmit=True,
                    simulated=True,
                )
                self.orders[tporder.ref] = tporder
                self.brackets[pref].append(tporder)

            # Submit order will auto submit bracket orders
            self._submit(pref)

            # complete parent order
            order.addcomminfo(self.getcommissioninfo(data))
            order.execute(0, order.size, order.price, 0, 0.0, 0.0, order.size,
                          0.0, 0.0, 0.0, 0.0, order.size, order.price)
            order.completed()
            self.notify(order)
            self._bracketize(order)
            self._ococheck(order)