Ejemplo n.º 1
0
    def close_position(self, instrument, longUnits='ALL', shortUnits='ALL'):
        instrument = get_symbol(instrument)

        response = self.api.position.close(self.account_id,
                                           instrument,
                                           longUnits=longUnits,
                                           shortUnits=shortUnits)

        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'CLOSE_POSITION')
            raise Exception(response.body['errorMessage'])

        longOrderCreateTransaction = response.get('longOrderCreateTransaction',
                                                  None)
        longOrderFillTransaction = response.get('longOrderFillTransaction',
                                                None)
        longOrderCancelTransaction = response.get('longOrderCancelTransaction',
                                                  None)
        shortOrderCreateTransaction = response.get(
            'shortOrderCreateTransaction', None)
        shortOrderFillTransaction = response.get('shortOrderFillTransaction',
                                                 None)
        shortOrderCancelTransaction = response.get(
            'shortOrderCancelTransaction', None)
        relatedTransactionIDs = response.get('relatedTransactionIDs', None)
        lastTransactionID = response.get('lastTransactionID', None)
        print(longOrderCreateTransaction.__dict__)
        print(longOrderFillTransaction.__dict__)
        print(longOrderCancelTransaction.__dict__)
        print(shortOrderCreateTransaction.__dict__)
        print(shortOrderFillTransaction.__dict__)
        print(shortOrderCancelTransaction.__dict__)
        print(relatedTransactionIDs.__dict__)
        print(lastTransactionID)
        return True
Ejemplo n.º 2
0
    def _process_order_response(self,
                                response,
                                func_name,
                                response_status="200"):
        if response.status < 200 or response.status > 299:
            log_error(logger, response, func_name)
            raise Exception(response.body.get('errorMessage'))

        transactions = []
        trade_ids = []
        order_ids = []
        for name in TransactionName.all():
            try:
                transaction = response.get(name, response_status)
                transactions.append(transaction)

                to = getattr(transaction, 'tradeOpened', None)
                if to:
                    trade_ids.append(to.tradeID)

                if isinstance(transaction,
                              LimitOrderTransaction) or isinstance(
                                  transaction, StopOrderTransaction):
                    order_ids.append(transaction.id)
            except:
                pass

        if trade_ids or order_ids:
            self.pull()

        if settings.DEBUG:
            for t in transactions:
                print_entity(t, title=t.__class__.__name__)
                print('')
        return transactions
Ejemplo n.º 3
0
    def get_trade(self, trade_id):
        response = api.trade.get(self.account_id, str(trade_id))
        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'GET_TRADE')
            return None

        trade = response.get("trade", "200")
        self.trades[trade.id] = trade

        if settings.DEBUG:
            print_trades([trade])
        return trade
Ejemplo n.º 4
0
    def list_open_positions(self):
        response = self.api.position.list_open(self.account_id, )

        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'LIST_OPEN_POSITION')
            raise Exception(response.body['errorMessage'])

        last_transaction_id = response.get('lastTransactionID', 200)
        positions = response.get('positions', 200)
        for position in positions:
            self.positions[position.instrument] = position
        return positions
Ejemplo n.º 5
0
    def get_order(self, order_id):
        response = api.order.get(self.account_id, str(order_id))
        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'GET_ORDER')
            return None

        order = response.get("order", "200")
        self.orders[order.id] = order

        if settings.DEBUG:
            print_orders([order])
        return order
Ejemplo n.º 6
0
    def _process_trades(self, response):

        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'LIST_TRADE')
            raise Exception(response.body.get('errorMessage'))

        trades = response.get("trades", "200")
        for trade in trades:
            self.trades[trade.id] = trade

        if settings.DEBUG:
            print_trades(trades)
        return trades
Ejemplo n.º 7
0
    def pull_position(self, instrument):
        """pull position by instrument"""
        instrument = get_symbol(instrument)
        response = self.api.position.get(self.account_id, instrument)

        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'QEURY_POSITION')
            raise Exception(response.body['errorMessage'])

        last_transaction_id = response.get('lastTransactionID', 200)
        position = response.get('position', 200)
        if position:
            self.positions[position.instrument] = position

        return position
Ejemplo n.º 8
0
    def _process_orders(self, response):
        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'LIST_ORDER')
            return []

        orders = response.get("orders", "200")
        if len(orders) == 0:
            logger.debug("Account {} has no pending Orders to cancel".format(
                self.account_id))
        for order in orders:
            self.orders[order.id] = order

        if settings.DEBUG:
            print_orders(orders)
        return orders
Ejemplo n.º 9
0
    def close_trade(self, trade_id, lots=None, percent=None):
        # units : (string, default=ALL)
        # Indication of how much of the Trade to close. Either the string “ALL”
        # (indicating that all of the Trade should be closed), or a DecimalNumber
        # representing the number of units of the open Trade to Close using a
        # TradeClose MarketOrder. The units specified must always be positive, and
        # the magnitude of the value cannot exceed the magnitude of the Trade’s
        # open units.

        if percent:
            trade = self.get_trade(trade_id)
            units = trade.currentUnits
            units = units * percent
        elif lots:
            units = str(lots_to_units(lots, OrderSide.BUY))
        else:
            units = 'ALL'

        response = api.trade.close(self.account_id, trade_id, units=str(units))
        if response.status < 200 or response.status > 299:
            log_error(logger, response, 'CLOSE_TRADE')
            raise Exception(response.body.get('errorMessage'))

        transactions = []
        trade_ids = []

        for name in TransactionName.all():
            try:
                transaction = response.get(name, "200")
                transactions.append(transaction)

                tcs = getattr(transaction, 'tradesClosed', [])
                for tc in tcs:
                    trade_ids.append(tc.tradeID)
            except:
                pass

        if trade_ids:
            self.pull()

        if settings.DEBUG:
            for t in transactions:
                print_entity(t, title=t.__class__.__name__)
                print('')
        # orderCreateTransaction, orderFillTransaction, orderCancelTransaction
        return transactions