Adapts a Ripple Account Orders object to an XChange OpenOrders object Counterparties set in
additional data since there is no other way of the application receiving this information.
428107
public static OpenOrders adaptOpenOrders(
      final RippleAccountOrders rippleOrders, final int scale) {
    final List<LimitOrder> list = new ArrayList<>(rippleOrders.getOrders().size());
    for (final RippleAccountOrdersBody order : rippleOrders.getOrders()) {

      final OrderType orderType;

      final RippleAmount baseAmount;
      final RippleAmount counterAmount;
      if (order.getType().equals("buy")) {
        // buying: we receive base and pay with counter, taker receives counter and pays with base
        counterAmount = order.getTakerGets();
        baseAmount = order.getTakerPays();
        orderType = OrderType.BID;
      } else {
        // selling: we receive counter and pay with base, taker receives base and pays with counter
        baseAmount = order.getTakerGets();
        counterAmount = order.getTakerPays();
        orderType = OrderType.ASK;
      }

      final String baseSymbol = baseAmount.getCurrency();
      final String counterSymbol = counterAmount.getCurrency();

      // need to provide rounding scale to prevent ArithmeticException
      final BigDecimal price =
          counterAmount
              .getValue()
              .divide(baseAmount.getValue(), scale, RoundingMode.HALF_UP)
              .stripTrailingZeros();
      final CurrencyPair pair = new CurrencyPair(baseSymbol, counterSymbol);

      final RippleLimitOrder xchangeOrder =
          (RippleLimitOrder)
              new RippleLimitOrder.Builder(orderType, pair)
                  .baseCounterparty(baseAmount.getCounterparty())
                  .counterCounterparty(counterAmount.getCounterparty())
                  .id(Long.toString(order.getSequence()))
                  .limitPrice(price)
                  .timestamp(null)
                  .originalAmount(baseAmount.getValue())
                  .build();
      list.add(xchangeOrder);
    }

    return new OpenOrders(list);
  }
1146035
public static UserTrades adaptTradeHistory(GatecoinTradeHistoryResult gatecoinUserTrades) {

    List<UserTrade> trades = new ArrayList<>();
    long lastTradeId = 0;
    if (gatecoinUserTrades != null) {
      GatecoinTradeHistory[] tradeHistory = gatecoinUserTrades.getTransactions();
      for (GatecoinTradeHistory gatecoinUserTrade : tradeHistory) {
        final boolean isAsk = Objects.equals(gatecoinUserTrade.getWay().toLowerCase(), "ask");
        OrderType orderType = isAsk ? OrderType.ASK : OrderType.BID;
        BigDecimal originalAmount = gatecoinUserTrade.getQuantity();
        BigDecimal price = gatecoinUserTrade.getPrice();
        Date timestamp =
            GatecoinUtils.parseUnixTSToDateTime(gatecoinUserTrade.getTransactionTime());
        long transactionId = gatecoinUserTrade.getTransactionId();
        if (transactionId > lastTradeId) {
          lastTradeId = transactionId;
        }
        final String tradeId = String.valueOf(transactionId);
        final String orderId =
            isAsk ? gatecoinUserTrade.getAskOrderID() : gatecoinUserTrade.getBidOrderID();
        final BigDecimal feeRate = gatecoinUserTrade.getFeeRate();
        final BigDecimal feeAmount =
            feeRate.multiply(originalAmount).multiply(price).setScale(8, BigDecimal.ROUND_CEILING);

        final CurrencyPair currencyPair =
            new CurrencyPair(
                gatecoinUserTrade.getCurrencyPair().substring(0, 3),
                gatecoinUserTrade.getCurrencyPair().substring(3, 6));
        UserTrade trade =
            new UserTrade(
                orderType,
                originalAmount,
                currencyPair,
                price,
                timestamp,
                tradeId,
                orderId,
                feeAmount,
                Currency.getInstance(currencyPair.counter.getCurrencyCode()));
        trades.add(trade);
      }
    }
    return new UserTrades(trades, lastTradeId, TradeSortType.SortByID);
  }
429692
def save(self, *args, **kwargs):
        """"""
        objects = self.get_filtered_manager()
        old_pos = getattr(self, '_original_sort_order', None)
        new_pos = self.sort_order

        if old_pos is None and self._unique_togethers_changed():
            self.sort_order = None
            new_pos = None

        try:
            with transaction.atomic():
                self._save(objects, old_pos, new_pos)
        except IntegrityError:
            with transaction.atomic():
                old_pos = objects.filter(pk=self.pk).values_list(
                    'sort_order', flat=True)[0]
                self._save(objects, old_pos, new_pos)

        # Call the "real" save() method.
        super(Orderable, self).save(*args, **kwargs)
70605
public static List<LimitOrder> adaptOpenOrders(
      List<CurrencyPair> currencyPairList, List<LykkeOrder> lykkeOrders) throws IOException {
    List<LimitOrder> limitOrders = new ArrayList<>();

    for (LykkeOrder lykkeOrder : lykkeOrders) {
      limitOrders.add(adaptLimitOrder(currencyPairList, lykkeOrder));
    }
    return limitOrders;
  }
1025338
public static AccountInfo adaptAccountInfo(ANXAccountInfo anxAccountInfo) {

    // Adapt to XChange DTOs
    AccountInfo accountInfo =
        new AccountInfo(
            anxAccountInfo.getLogin(),
            percentToFactor(anxAccountInfo.getTradeFee()),
            ANXAdapters.adaptWallet(anxAccountInfo.getWallets()));
    return accountInfo;
  }
123255
public static Trades adaptTrades(EXXTransaction[] transactions, CurrencyPair currencyPair) {
    List<Trade> trades = new ArrayList<>();
    long lastTradeId = 0;
    for (EXXTransaction transaction : transactions) {
      final long tradeId = transaction.getTid();
      if (tradeId > lastTradeId) {
        lastTradeId = tradeId;
      }
      OrderType orderType = OrderType.BID;
      if (transaction.getType().equals("sell")) orderType = OrderType.ASK;
      trades.add(
          new Trade.Builder()
              .id(String.valueOf(transaction.getTid()))
              .originalAmount((transaction.getAmount()))
              .price(transaction.getPrice())
              .timestamp(new Date(transaction.getDate()))
              .currencyPair(currencyPair)
              .type(orderType)
              .build());
    }

    return new Trades(trades, lastTradeId, TradeSortType.SortByID);
  }
445223
def place_order(self, amount, price, side, ord_type, symbol='btcusd', exchange='bitfinex'):
        
        payload = {

            "request": "/v1/order/new",
            "nonce": self._nonce,
            "symbol": symbol,
            "amount": amount,
            "price": price,
            "exchange": exchange,
            "side": side,
            "type": ord_type

        }

        signed_payload = self._sign_payload(payload)
        r = requests.post(self.URL + "/order/new", headers=signed_payload, verify=True)
        json_resp = r.json()

        try:
            json_resp['order_id']
        except:
            return json_resp['message']

        return json_resp
236802
public static Trades adaptTrades(CexIOTrade[] cexioTrades, CurrencyPair currencyPair) {

    List<Trade> tradesList = new ArrayList<>();
    long lastTradeId = 0;
    for (CexIOTrade trade : cexioTrades) {
      long tradeId = trade.getTid();
      if (tradeId > lastTradeId) {
        lastTradeId = tradeId;
      }
      // Date is reversed order. Insert at index 0 instead of appending
      tradesList.add(0, adaptTrade(trade, currencyPair));
    }
    return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
  }
1263902
public static Trade adaptTrade(ANXTrade anxTrade) {

    OrderType orderType = adaptSide(anxTrade.getTradeType());
    BigDecimal amount = anxTrade.getAmount();
    BigDecimal price = anxTrade.getPrice();
    CurrencyPair currencyPair = adaptCurrencyPair(anxTrade.getItem(), anxTrade.getPriceCurrency());
    Date dateTime = DateUtils.fromMillisUtc(anxTrade.getTid());
    final String tradeId = String.valueOf(anxTrade.getTid());

    return new Trade(orderType, amount, currencyPair, price, dateTime, tradeId);
  }
275166
def put(self, accountId):
        """"""
        self.reqparse.add_argument('accountName', type=str, required=True)
        self.reqparse.add_argument('accountType', type=str, required=True)
        self.reqparse.add_argument('contacts', type=dict, required=True, action='append')
        self.reqparse.add_argument('enabled', type=int, required=True, choices=(0, 1))
        self.reqparse.add_argument('requiredRoles', type=str, action='append', default=())
        self.reqparse.add_argument('properties', type=dict, required=True)
        args = self.reqparse.parse_args()

        account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], args['accountType'])
        if not account_class:
            raise InquisitorError('Invalid account type: {}'.format(args['accountType']))

        validate_contacts(args['contacts'])

        if not args['accountName'].strip():
            raise Exception('You must provide an account name')

        if not args['contacts']:
            raise Exception('You must provide at least one contact')

        class_properties = {from_camelcase(key): value for key, value in args['properties'].items()}
        for prop in account_class.class_properties:
            if prop['key'] not in class_properties:
                raise InquisitorError('Missing required property {}'.format(prop))

        account = account_class.get(accountId)
        if account.account_type != args['accountType']:
            raise InquisitorError('You cannot change the type of an account')

        account.account_name = args['accountName']
        account.contacts = args['contacts']
        account.enabled = args['enabled']
        account.required_roles = args['requiredRoles']
        account.update(**args['properties'])
        account.save()

        auditlog(event='account.update', actor=session['user'].username, data=args)

        return self.make_response({'message': 'Object updated', 'account': account.to_json(is_admin=True)})
189318
@Override
  public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {

    String marketName = DSXAdapters.currencyPairToMarketName(currencyPair);

    String accountType = null;
    try {
      if (args != null) {
        accountType = (String) args[0];
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      // ignore, can happen if no argument given.
    }

    DSXOrderbookWrapper dsxOrderbookWrapper = getDSXOrderbook(marketName, accountType);
    DSXOrderbook orderbook = dsxOrderbookWrapper.getOrderbook(marketName);

    // Adapt to XChange DTOs
    List<LimitOrder> asks = DSXAdapters.adaptOrders(orderbook.getAsks(), currencyPair, "ask", "");
    List<LimitOrder> bids = DSXAdapters.adaptOrders(orderbook.getBids(), currencyPair, "bid", "");

    return new OrderBook(null, asks, bids);
  }
66989
def shift_ordering_up(self, parent_id, position, db_session=None, *args, **kwargs):
        
        return self.service.shift_ordering_up(
            parent_id=parent_id,
            position=position,
            db_session=db_session,
            *args,
            **kwargs
        )
472932
def get_openOrders(self, acc_id=None, symbol=None, side=None, size=None, _async=False):
        
        params = {}
        path = '/v1/order/openOrders'
        if all([acc_id, symbol]):
            params['account-id'] = acc_id
            params['symbol'] = symbol
        if side:
            assert side in ['buy', 'sell']
            params['side'] = side
        if size:
            params['size'] = size

        return api_key_get(params, path, _async=_async)
828665
def from_xdr_object(cls, op_xdr_object):
        
        if not op_xdr_object.sourceAccount:
            source = None
        else:
            source = encode_check(
                'account', op_xdr_object.sourceAccount[0].ed25519).decode()

        line = Asset.from_xdr_object(op_xdr_object.body.changeTrustOp.line)
        limit = Operation.from_xdr_amount(
            op_xdr_object.body.changeTrustOp.limit)

        return cls(source=source, asset=line, limit=limit)
1062229
def to_xdr_object(self):
        
        asset = self.asset.to_xdr_object()
        destination = account_xdr_object(self.destination)

        amount = Operation.to_xdr_amount(self.amount)

        payment_op = Xdr.types.PaymentOp(destination, asset, amount)
        self.body.type = Xdr.const.PAYMENT
        self.body.paymentOp = payment_op
        return super(Payment, self).to_xdr_object()
1340507
private static LimitOrder withAmount(LimitOrder limitOrder, BigDecimal tradeableAmount) {

    OrderType type = limitOrder.getType();
    CurrencyPair currencyPair = limitOrder.getCurrencyPair();
    String id = limitOrder.getId();
    Date date = limitOrder.getTimestamp();
    BigDecimal limit = limitOrder.getLimitPrice();
    return new LimitOrder(type, tradeableAmount, currencyPair, id, date, limit);
  }
43192
def save
      raise ArgumentError.new("Account is missing.") unless account
      
      account.require_secret
      
      hash = {}
      hash["settings"] = to_hash
      hash["secret"] = account.secret
      
      RippleRest.post "v1/accounts/#{account.address}/settings", hash
    end