コード例 #1
0
    def market_order(self,
                     instrument,
                     side,
                     lots,
                     take_profit=None,
                     stop_loss=None,
                     trailing_pip=None,
                     **kwargs):
        timeInForce = kwargs.get('timeInForce', TimeInForce.FOK)
        symbol = get_fxcm_symbol(instrument)
        is_buy = side == OrderSide.BUY
        amount = lots_to_units(lots) / 1000
        is_in_pips = kwargs.get('is_in_pips', True)

        if is_in_pips and stop_loss and stop_loss > 0:
            stop_loss = -1 * stop_loss  # change to negtive if using pips

        return self.fxcmpy.open_trade(symbol,
                                      is_buy,
                                      amount,
                                      timeInForce,
                                      order_type='AtMarket',
                                      rate=0,
                                      is_in_pips=is_in_pips,
                                      limit=take_profit,
                                      at_market=0,
                                      stop=stop_loss,
                                      trailing_step=trailing_pip,
                                      account_id=self.account_id)
コード例 #2
0
    def close_trade(self, trade_id, lots=None, percent=None):
        amount = self.get_trade(trade_id).get_amount()
        if percent:
            amount = amount * percent
        elif lots:
            amount = lots_to_units(lots) / 1000

        try:
            self.fxcmpy.close_trade(trade_id, amount, order_type='AtMarket',
                                    time_in_force='IOC', rate=None, at_market=None)
        except Exception as ex:
            logger.error('[Closet Trade] %s' % ex)
コード例 #3
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
コード例 #4
0
    def _make_limit_or_stop_order(self,
                                  instrument,
                                  side,
                                  price,
                                  lots,
                                  take_profit=None,
                                  stop_loss=None,
                                  trailing_pip=None,
                                  **kwargs):
        symbol = get_fxcm_symbol(instrument)
        is_buy = side == OrderSide.BUY
        amount = lots_to_units(lots) / 1000
        is_in_pips = kwargs.get('is_in_pips', True)

        order_id = kwargs.get('order_id', None)
        if order_id:
            order = self.get_order(order_id)
            if trailing_pip:
                order.set_trailing_step(trailing_pip)

            kw = {}
            if stop_loss:
                kw['stop'] = stop_loss
                kw['is_stop_in_pips'] = is_in_pips
            if take_profit:
                kw['limit'] = take_profit
                kw['is_limit_in_pips'] = is_in_pips
            if kw:
                self.fxcmpy.change_order_stop_limit(order_id, **kw)
        else:
            return self.create_entry_order(symbol,
                                           is_buy,
                                           amount,
                                           time_in_force=TimeInForce.GTC,
                                           price=price,
                                           take_profit=take_profit,
                                           stop_loss=stop_loss,
                                           trailing_pip=trailing_pip,
                                           **kwargs)
コード例 #5
0
    def _process_order_paramters(self, **kwargs):
        data = {}
        instrument = None
        pip_unit = None

        if kwargs.get('instrument'):
            instrument = get_symbol(kwargs['instrument'])

            data['instrument'] = instrument

        if kwargs.get('trade_id'):
            data['tradeID'] = str(kwargs['trade_id'])
            trade = self.trades.get(data['tradeID']) or self.get_trade(
                data['tradeID'])
            instrument = trade.instrument

        if instrument:
            pip_unit = pip(instrument)

        if kwargs.get('lots'):
            units = lots_to_units(kwargs['lots'],
                                  kwargs.get('side') or OrderSide.BUY)
            data['units'] = str(units)

        if kwargs.get('type'):
            data['type'] = kwargs['type']

        if kwargs.get('timeInForce'):
            data['timeInForce'] = kwargs['timeInForce'] or TimeInForce.FOK

        if kwargs.get('priceBound'):
            data['priceBound'] = str(kwargs['priceBound'])

        if kwargs.get('price'):
            data['price'] = str(kwargs['price'])

        if kwargs.get('positionFill'):
            data['positionFill'] = kwargs[
                'positionFill'] or OrderPositionFill.DEFAULT

        # The Client Extensions to update for the Order. Do not set, modify, or
        # delete clientExtensions if your account is associated with MT4.
        if kwargs.get('client_id') or kwargs.get('client_tag') or kwargs.get(
                'client_comment'):
            data['clientExtensions'] = ClientExtensions(
                id=kwargs['client_id'],
                tag=kwargs['client_tag'],
                comment=kwargs['client_comment'])

        if kwargs.get('trade_client_id') or kwargs.get(
                'trade_client_tag') or kwargs.get('trade_client_comment'):
            data['tradeClientExtensions'] = ClientExtensions(
                id=kwargs['trade_client_id'],
                tag=kwargs['trade_client_tag'],
                comment=kwargs['trade_client_comment'])

        if kwargs.get('take_profit_price'):
            data['takeProfitOnFill'] = TakeProfitDetails(
                price=str(kwargs['take_profit_price']),
                clientExtensions=data.get('clientExtensions'))

        if kwargs.get('stop_loss_pip') and pip_unit:
            stop_loss_price = pip_unit * Decimal(str(kwargs['stop_loss_pip']))
            data['stopLossOnFill'] = StopLossDetails(
                distance=str(stop_loss_price),
                clientExtensions=data.get('clientExtensions'))

        if kwargs.get('stop_loss_distance'):
            data['stopLossOnFill'] = StopLossDetails(
                distance=str(kwargs['stop_loss_distance']),
                clientExtensions=data.get('clientExtensions'))

        if kwargs.get('trailing_pip'):
            trailing_distance_price = pip_unit * Decimal(
                str(kwargs['trailing_pip']))
            data['trailingStopLossOnFill'] = TrailingStopLossDetails(
                distance=str(trailing_distance_price),
                clientExtensions=data.get('clientExtensions'))

        if kwargs.get('trigger_condition'):
            data['triggerCondition'] = kwargs[
                'trigger_condition'] or OrderTriggerCondition.DEFAULT

        if kwargs.get('gtd_time'):
            # todo confirm gtdTime format
            data['gtdTime'] = str(kwargs['gtd_time'])

        if kwargs.get('client_trade_id'):
            data['clientTradeID'] = kwargs['client_trade_id']

        if kwargs.get('guaranteed'):
            data['guaranteed'] = kwargs['guaranteed']

        if kwargs.get('distance'):
            data['distance'] = kwargs['distance']

        return data