Exemplo n.º 1
0
    def loads_trade(self, trade_id, trade_type, data, operations):
        """
        Load a strategy trader trade and its operations.
        @todo Need to check the validity of the trade :
            - existings orders, create, sell, limit, stop, position
            - and eventually the free margin, asset quantity
        There is many scenarii where the trade state changed, trade executed, order modified or canceled...
        """
        trade = None

        if trade_type == StrategyTrade.TRADE_BUY_SELL:
            trade = StrategyAssetTrade(0)
        elif trade_type == StrategyTrade.TRADE_MARGIN:
            trade = StrategyMarginTrade(0)
        elif trade_type == StrategyTrade.TRADE_POSITION:
            trade = StrategyPositionTrade(0)
        elif trade_type == StrategyTrade.TRADE_IND_MARGIN:
            trade = StrategyIndMarginTrade(0)
        else:
            error_logger.error("During loads, usupported trade type %i" %
                               (trade_type, ))
            return

        trade.loads(data, self.strategy.service)

        # operations
        for op in operations:
            if op['name'] in self.strategy.service.tradeops:
                try:
                    operation = self.strategy.service.tradeops[op['name']]()
                    operation.loads(op)

                    if operation.check(trade):
                        # append the operation to the trade
                        trade.add_operation(operation)
                    else:
                        error_logger.error(
                            "During loads, operation checking error %s" %
                            (op_name, ))
                except Exception as e:
                    error_logger.error(repr(e))
            else:
                error_logger.error("During loads, region checking error %s" %
                                   (r['name'], ))

        # check orders/position/quantity before adding
        trader = self.strategy.trader()

        if trade.check(trader, self.instrument):
            self.add_trade(trade)
Exemplo n.º 2
0
    def process_entry(self, timestamp, direction, price, take_profit,
                      stop_loss, timeframe):
        trader = self.strategy.trader()
        market = trader.market(self.instrument.market_id)

        quantity = 0.0
        price = market.ofr  # signal is at ofr price (for now limit entry at current ofr price)

        date_time = datetime.fromtimestamp(timestamp)
        date_str = date_time.strftime('%Y-%m-%d %H:%M:%S')

        # ajust max quantity according to free asset of quote, and convert in asset base quantity
        if 0:  # not trader.has_margin(self.market.margin_cost(self.instrument.trade_quantity)):
            Terminal.inst().notice(
                "Not enought free margin %s, has %s but need %s" %
                (market.quote,
                 market.format_quantity(trader.account.margin_balance),
                 market.format_quantity(self.instrument.trade_quantity)),
                view='status')
        else:
            quantity = market.adjust_quantity(self.instrument.trade_quantity)

        #
        # create an order
        #

        do_order = self.activity

        order_hedging = False
        order_quantity = 0.0
        order_price = None
        order_type = None
        order_leverage = 1.0

        # @todo check self.hedging (supported by IG using compensate position)
        if self.hedging:
            order_hedging = True

        # simply set the computed quantity
        order_quantity = quantity
        order_type = Order.ORDER_MARKET  #  Order.ORDER_LIMIT @todo limit later

        # @todo or trade at order book, compute the limit price from what the order book offer
        # limit best price at tiniest ofr price

        # adjust price to min / tick size / max
        order_price = market.adjust_price(market.ofr)

        if take_profit > 0:
            take_profit = market.adjust_price(take_profit)

        if stop_loss > 0:
            stop_loss = market.adjust_price(stop_loss)

        #
        # cancelation of the signal
        #

        if order_quantity <= 0 or order_quantity * price < market.min_notional:
            # min notional not reached
            do_order = False

        if self.trades:
            self.lock()

            if len(self.trades) >= self.max_trades:
                # no more than max simultaneous trades
                do_order = False

            for trade in self.trades:
                if trade.timeframe == timeframe:
                    do_order = False

            # if self.trades and (self.trades[-1].dir == direction) and ((timestamp - self.trades[-1].entry_open_time) < self.trade_delay):
            if self.trades and (self.trades[-1].dir == direction) and (
                (timestamp - self.trades[-1].entry_open_time) < timeframe):
                # the same order occurs just after, ignore it
                do_order = False

            self.unlock()

        #
        # execution of the order
        #

        if do_order:
            trade = StrategyMarginTrade(timeframe)

            logger.info("Order %s %s qty=%s p=%s sl=%s tp=%s ts=%s" %
                        ("long" if direction > 0 else "short",
                         self.instrument.market_id,
                         market.format_quantity(order_quantity),
                         market.format_price(order_price),
                         market.format_price(stop_loss),
                         market.format_price(take_profit), date_str))

            # the new trade must be in the trades list if the event comes before, and removed after only it failed
            self.add_trade(trade)

            if trade.open(trader,
                          self.instrument.market_id,
                          direction,
                          order_type,
                          order_price,
                          order_quantity,
                          take_profit,
                          stop_loss,
                          order_leverage,
                          hedging=order_hedging):
                # initiate the take-profit limit order
                if take_profit > 0:
                    trade.modify_take_profit(trader, self.instrument.market_id,
                                             take_profit)

                # # initiate the stop-loss order
                # if stop_loss > 0:
                #     trade.modify_stop_loss(trader, self.instrument.market_id, stop_loss)

                # notify
                self.strategy.notify_order(trade.id, trade.dir,
                                           self.instrument.market_id,
                                           market.format_price(price),
                                           timestamp, trade.timeframe, 'entry',
                                           None, market.format_price(trade.sl),
                                           market.format_price(trade.tp))

                # want it on the streaming (take care its only the order signal, no the real complete execution)
                if trade.direction > 0:
                    self._global_streamer.member('buy-entry').update(
                        price, timestamp)
                elif trade.direction < 0:
                    self._global_streamer.member('sell-entry').update(
                        price, timestamp)
            else:
                self.remove_trade(trade)