Calls Xavier API to perform the exchange with a specific date.
 This method is called when using :at method, like this:

   30.eur.at(1.year.ago).to_usd
174307
def call_xavier_api(original, target)

      # Check if there is any cached XML for the specified date
      if defined?(Rails)
        parsed_response = Rails.cache.read("xaviermedia_#{stringified_exchange_date}")
      end

      unless parsed_response # Unless there is a cached XML response, ask for it
        retries = 10
        not_found_retries=10
        xml_response = nil
        begin
          # Returns the raw response or
          # raises OpenURI::HTTPError when no data available
          Timeout::timeout(1) { xml_response = make_call(@exchange_date) || nil }
        rescue Timeout::Error
          retries -= 1
          retries > 0 ? sleep(0.42) && retry : raise
        rescue OpenURI::HTTPError # Try to fetch one day and 2 days earlier
          not_found_retries -= 1
          if not_found_retries >= 0
            @exchange_date = (Time.parse(@exchange_date.to_s) - 86400).send(:to_date)
            retry
          else
            raise NotFoundError.new("404 Not Found")
          end
        rescue SocketError
          raise NotFoundError.new("Socket Error")
        end

        return nil unless xml_response && parsed_response = Crack::XML.parse(xml_response)["xavierresponse"]["exchange_rates"]["fx"]

        # Cache successful XML response for later reuse
        if defined?(Rails)
          Rails.cache.write("xaviermedia_#{stringified_exchange_date}", parsed_response)
        end
      end

      calculate_rate(parsed_response, original, target)
    end
342872
protected function getHistoricalExchangeRate(HistoricalExchangeRateQuery $exchangeQuery): ExchangeRateContract
    {
        $currencyPair = $exchangeQuery->getCurrencyPair();
        $baseCurrency = $currencyPair->getBaseCurrency();
        $date = $exchangeQuery->getDate();
        $formattedDate = $date->format('Ymd');

        $content = $this->request(self::URL.'?'.http_build_query(['date' => $formattedDate]));
        $element = StringUtil::xmlToElement($content);

        $elements = $element->xpath('./currency[cc="'.$baseCurrency.'"]');

        if (empty($elements)) {
            if ($element->xpath('./error')) {
                throw new UnsupportedDateException($date, $this);
            }

            throw new UnsupportedCurrencyPairException($currencyPair, $this);
        }

        $item = $elements[0];

        $rate = (float) str_replace(',', '.', (string) $item->rate);

        return $this->createRate($currencyPair, $rate, $date);
    }
367139
private function doCreateRate($url, CurrencyPair $currencyPair): ExchangeRate
    {
        $content = $this->request($url);
        $data = StringUtil::jsonToArray($content);

        if (empty($data['success'])) {
            throw new Exception($data['error']['info']);
        }

        $date = (new \DateTime())->setTimestamp($data['timestamp']);
        $hash = $currencyPair->getBaseCurrency().$currencyPair->getQuoteCurrency();

        if ($data['source'] === $currencyPair->getBaseCurrency() && isset($data['quotes'][$hash])) {
            return $this->createRate($currencyPair, (float) ($data['quotes'][$hash]), $date);
        }

        throw new UnsupportedCurrencyPairException($currencyPair, $this);
    }
32709
@Override
  public String requestDepositAddress(Currency currency, String... arguments) throws IOException {
    try {
      CoingiDepositWalletRequest request =
          new CoingiDepositWalletRequest().setCurrency(currency.getCurrencyCode().toUpperCase());
      return depositWallet(request).getAddress();
    } catch (CoingiException e) {
      throw CoingiErrorAdapter.adapt(e);
    }
  }
210960
def QA_util_id2date(idx, client):
    
    coll = client.quantaxis.trade_date
    temp_str = coll.find_one({'num': idx})
    return temp_str['date']
1015588
def call(self, _from=None, to=None, gas=None, gas_price=None, value=0,
             data=None, block="latest"):
        
        if _from is None:
            _from = self.default_from_address

        params = [
            get_transaction_params(_from, to, gas, gas_price, value, data),
            block,
        ]
        response = self.make_request("eth_call", params)
        return response['result']
826960
function() {
    var time = null;

    if (this.method === 'from now') {
      time = ago.fromNow(this.amount, this.unit);
    } else if (this.method === 'ago') {
      time = ago(this.amount, this.unit);
    } else {
      throw new Error('Invalid method: ' + this.method);
    }

    return new Date(time);
  }
36151
public static Trade adaptTrade(
      LakeBTCTradeResponse tx, CurrencyPair currencyPair, int timeScale) {

    final String tradeId = String.valueOf(tx.getId());
    Date date = DateUtils.fromMillisUtc(tx.getAt() * timeScale); // polled order
    // books provide
    // a timestamp
    // in seconds,
    // stream in ms
    return new Trade(null, tx.getAmount(), currencyPair, tx.getTotal(), date, tradeId);
  }
775635
def exchangebill(self):
        
        # TODO 目前仅在 华泰子类 中实现
        start_date, end_date = helpers.get_30_date()
        return self.get_exchangebill(start_date, end_date)
1283081
private function fetchOnlineRate($url, ExchangeRateQuery $exchangeRateQuery): ExchangeRate
    {
        $currencyPair = $exchangeRateQuery->getCurrencyPair();

        $response = $this->getResponse($url);

        if (200 !== $response->getStatusCode()) {
            throw new Exception("Unexpected response status {$response->getReasonPhrase()}, $url");
        }

        $responsePayload = StringUtil::jsonToArray($response->getBody()->__toString());

        $keyAsCurrencyPair = $this->stringifyCurrencyPair($currencyPair);

        if (empty($responsePayload['results'][$keyAsCurrencyPair]['val'])) {
            throw new Exception("Unexpected response body {$response->getReasonPhrase()}");
        }

        if ($responsePayload['results'][$keyAsCurrencyPair]['fr'] !== $currencyPair->getBaseCurrency()) {
            throw new Exception("Unexpected base currency {$responsePayload['results'][$keyAsCurrencyPair]['fr']}");
        }

        if ($responsePayload['results'][$keyAsCurrencyPair]['to'] !== $currencyPair->getQuoteCurrency()) {
            throw new Exception("Unexpected quote currency {$responsePayload['results'][$keyAsCurrencyPair]['to']}");
        }

        if ($exchangeRateQuery instanceof HistoricalExchangeRateQuery) {
            $dateStringified = $responsePayload['date'];
            $date = new \DateTime($dateStringified);
            $rate = $responsePayload['results'][$keyAsCurrencyPair]['val'][$dateStringified];
        } else {
            $date = new \DateTime('now');
            $rate = $responsePayload['results'][$keyAsCurrencyPair]['val'];
        }

        return $this->createRate($currencyPair, (float) $rate, $date);
    }
1327386
public static Ticker adaptTicker(CryptonitTicker cryptonitTicker, CurrencyPair currencyPair) {

    BigDecimal open = cryptonitTicker.getOpen();
    BigDecimal last = cryptonitTicker.getLast();
    BigDecimal bid = cryptonitTicker.getBid();
    BigDecimal ask = cryptonitTicker.getAsk();
    BigDecimal high = cryptonitTicker.getHigh();
    BigDecimal low = cryptonitTicker.getLow();
    BigDecimal vwap = cryptonitTicker.getVwap();
    BigDecimal volume = cryptonitTicker.getVolume();
    Date timestamp = new Date(cryptonitTicker.getTimestamp() * 1000L);

    return new Ticker.Builder()
        .currencyPair(currencyPair)
        .open(open)
        .last(last)
        .bid(bid)
        .ask(ask)
        .high(high)
        .low(low)
        .vwap(vwap)
        .volume(volume)
        .timestamp(timestamp)
        .build();
  }
603103
def convert_currency(self, base_fiat, base_amount, target_fiat):
        
        url = "http://api.fixer.io/latest?base=%s" % base_fiat
        data = self.get_url(url).json()
        try:
            return data['rates'][target_fiat.upper()] * base_amount
        except KeyError:
            raise Exception("Can not convert %s to %s" % (base_fiat, target_fiat))
34462
def get_exchange_rate(self, base, target, raise_errors=True):
        """"""
        assert base and target

        base, target = base.lower(), target.lower()

        r = self.session.get(API_SIMPLE_TICKER.format(base, target))
        if r.status_code != requests.codes.ok:
            if not raise_errors:
                return None
            raise CryptonatorException(
                ("An error occurred while getting requested exchange rate "
                 "({} from Cryptonator).").format(r.status_code)
            )

        j = r.json()
        if not j['success'] or j['error']:
            if not raise_errors:
                return None
            raise CryptonatorException(
                ("An error occurred while getting requested exchange rate ({}, {})"
                 "('{}').").format(base, target, j['error'])
            )

        return float(j['ticker']['price'])
725438
public function getExchangeRate(ExchangeRateQuery $exchangeQuery): ExchangeRateContract
    {
        $currencyPair = $exchangeQuery->getCurrencyPair();

        $response = $this->request(
            sprintf(
                self::LATEST_URL,
                strtolower($currencyPair->getBaseCurrency()),
                strtolower($currencyPair->getQuoteCurrency())
            )
        );

        $data = StringUtil::jsonToArray($response);

        if (!$data['success']) {
            $message = !empty($data['error']) ? $data['error'] : 'Unknown error';

            throw new Exception($message);
        }

        $date = (new \DateTime())->setTimestamp($data['timestamp']);

        return $this->createRate($currencyPair, (float) ($data['ticker']['price']), $date);
    }
13584
private function getHistoricalExchangeRate(HistoricalExchangeRateQuery $exchangeQuery): ExchangeRate
    {
        $date = $exchangeQuery->getDate();
        $currencyPair = $exchangeQuery->getCurrencyPair();
        $rate = (float) $this->historicalRates[$date->format('Y-m-d')][(string) $currencyPair];

        return $this->createRate($currencyPair, $rate, $date);
    }
307343
@Override
  public Ticker getTicker(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.
    }

    DSXTickerWrapper dsxTickerWrapper = getDSXTicker(marketName, accountType);

    // Adapt to XChange DTOs
    return DSXAdapters.adaptTicker(dsxTickerWrapper.getTicker(marketName), currencyPair);
  }
977423
private function retrieveExchangeRateFor(Currency $currency): void
    {
        $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/latest', [
            'query' => [
                'access_key' => $this->apiKey,
                'base'       => $this->baseCurrency->getCode(),
            ],
        ]);

        $data = json_decode($response->getBody(), true);

        if ($data['success'] !== true) {
            throw FixerIoException::couldNotRetrieveRates($data['error']);
        }

        if (! array_key_exists($currency->getCode(), $data['rates'])) {
            throw FixerIoException::currencyNotFound($currency->getCode());
        }

        $this->exchangeRates[$currency->getCode()] = $data['rates'][$currency->getCode()];
    }