/**
  * @param CurrencyPair $currencyPair
  * @return Rate
  * @throws Exception
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $providers = [$this->mainProvider => CurrencyRateProvider::getByName($this->mainProvider), $this->secondProvider => CurrencyRateProvider::getByName($this->secondProvider)];
     if (count($providers) !== 2) {
         throw new Exception('One of providers not found');
     }
     $rates = [];
     /** @var CurrencyRateProvider $provider */
     foreach ($providers as $name => $provider) {
         if (null === $provider) {
             throw new Exception("Provider \"{$name}\" not found!");
         }
         try {
             $providerHandler = $provider->getImplementationInstance($this->httpAdapter);
             if ($providerHandler !== null) {
                 $swap = new Swap($providerHandler);
                 $rate = $swap->quote($currencyPair->getBaseCurrency() . '/' . $currencyPair->getQuoteCurrency())->getValue();
                 $rates[] = floatval($rate);
             } else {
                 throw new Exception('Provider "' . $provider->name . '" not found');
             }
         } catch (\Exception $e) {
             throw new Exception('One or more currency providers did not return result');
         }
     }
     $min = min($rates);
     $max = max($rates);
     return new Rate($max - $min >= $max * $this->criticalDifference / 100 ? $max : $rates[0], new \DateTime());
 }
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $providerIds = [(int) $this->mainProvider, (int) $this->secondProvider];
     /** @var CurrencyRateProvider[] $providers */
     $providers = CurrencyRateProvider::find()->where(['id' => $providerIds])->orderBy(['FIELD (`id`, ' . implode(',', $providerIds) . ')' => ''])->all();
     if (count($providers) !== 2) {
         throw new Exception('One of providers not found');
     }
     $rates = [];
     foreach ($providers as $provider) {
         try {
             $providerHandler = $provider->getImplementationInstance($this->httpAdapter);
             if ($providerHandler !== null) {
                 $swap = new Swap($providerHandler);
                 $rate = $swap->quote($currencyPair->getBaseCurrency() . '/' . $currencyPair->getQuoteCurrency())->getValue();
                 $rates[] = floatval($rate);
             } else {
                 throw new Exception('Provider "' . $provider->name . '" not found');
             }
         } catch (\Exception $e) {
             throw new Exception('One or more currency providers did not return result');
         }
     }
     $min = min($rates);
     $max = max($rates);
     return new Rate($max - $min >= $max * $this->criticalDifference / 100 ? $max : $rates[0], new \DateTime());
 }
示例#3
0
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $url = sprintf(self::URL, $currencyPair->getBaseCurrency() . $currencyPair->getQuoteCurrency(), $this->token);
     $content = $this->fetchContent($url);
     $json = StringUtil::jsonToArray($content);
     $data = $json[0];
     if ('Success' === $data['Outcome']) {
         $dateString = $data['Date'] . ' ' . $data['Time'];
         return new Rate((string) $data['Bid'], \DateTime::createFromFormat('m/d/Y H:i:s A', $dateString, new \DateTimeZone('UTC')));
     }
     throw new Exception($data['Message']);
 }
示例#4
0
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     if (!isset($this->rates[$currencyPair->toString()])) {
         throw new UnsupportedCurrencyPairException($currencyPair);
     }
     $rate = $this->rates[$currencyPair->toString()];
     if (is_scalar($rate)) {
         $rate = new Rate($rate);
     } elseif (!$rate instanceof Rate) {
         throw new InternalException(sprintf('Rates passed to the ArrayProvider must be Rate instances or scalars "%s" given.', gettype($rate)));
     }
     return $rate;
 }
示例#5
0
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $date = date("d/m/Y");
     $url = sprintf(self::URL, $date);
     $content = $this->httpAdapter->get($url)->getBody()->getContents();
     $cbr = new \SimpleXMLElement($content);
     $res = $cbr->xpath('/ValCurs/Valute[CharCode="' . $currencyPair->getBaseCurrency() . '"]');
     if (array_key_exists(0, $res)) {
         return new Rate(str_replace(',', '.', $res[0]->Value), new \DateTime());
     } else {
         throw new \Swap\Exception\Exception('The currency is not supported');
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair, $date = null)
 {
     $getAppend = function ($from, $to, $date = null) {
         $date = isset($date) ? $date : 'latest';
         return "{$date}?symbols={$to}&base={$from}";
     };
     $url = self::URL . $getAppend($currencyPair->getBaseCurrency(), $currencyPair->getQuoteCurrency(), $date);
     $content = $this->fetchContent($url);
     $return = StringUtil::jsonToArray($content);
     $return['date'] = isset($date) ? new \DateTime($date) : new \DateTime();
     return new Rate(current($return['rates']), $return['date']);
     throw new UnsupportedCurrencyPairException($currencyPair);
 }
示例#7
0
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $queryPairs = sprintf('"%s%s"', $currencyPair->getBaseCurrency(), $currencyPair->getQuoteCurrency());
     $query = sprintf('select * from yahoo.finance.xchange where pair in (%s)', $queryPairs);
     $url = sprintf(self::URL, urlencode($query));
     $content = $this->fetchContent($url);
     $json = StringUtil::jsonToArray($content);
     $data = $json['query']['results']['rate'];
     if ('0.00' === $data['Rate'] || 'N/A' === $data['Date']) {
         throw new UnsupportedCurrencyPairException($currencyPair);
     }
     $dateString = $data['Date'] . ' ' . $data['Time'];
     $date = \DateTime::createFromFormat('m/d/Y H:ia', $dateString);
     return new Rate($data['Rate'], $date);
 }
示例#8
0
 /**
  * {@inheritdoc}
  */
 public function quote($currencyPair, $date = null)
 {
     if (is_string($currencyPair)) {
         $currencyPair = CurrencyPair::createFromString($currencyPair);
     } elseif (!$currencyPair instanceof CurrencyPair) {
         throw new \InvalidArgumentException('The currency pair must be either a string or an instance of CurrencyPair');
     }
     //todo: abstract???
     if (isset($date)) {
         // date cache check, first cache check
         if (null !== $this->dateCache && null !== ($rate = $this->dateCache->fetchRate($currencyPair, $date))) {
             return $rate;
         }
         $rate = $this->provider->fetchRate($currencyPair, $date);
         //store date and rate
         if (null !== $this->dateCache && isset($date)) {
             $this->dateCache->storeRate($currencyPair, $rate, $date);
         }
         return $rate;
     }
     // original cache check
     if (null !== $this->cache && null !== ($rate = $this->cache->fetchRate($currencyPair))) {
         return $rate;
     }
     $rate = $this->provider->fetchRate($currencyPair);
     // original cache set
     if (null !== $this->cache) {
         $this->cache->storeRate($currencyPair, $rate);
     }
     return $rate;
 }
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $url = sprintf(self::URL, $currencyPair->getBaseCurrency(), $currencyPair->getQuoteCurrency());
     $content = $this->fetchContent($url);
     $document = new \DOMDocument();
     @$document->loadHTML($content);
     $xpath = new \DOMXPath($document);
     $nodes = $xpath->query('//span[@class="bld"]');
     if (0 === $nodes->length) {
         throw new Exception('The currency is not supported or Google changed the response format');
     }
     $nodeContent = $nodes->item(0)->textContent;
     $bid = strstr($nodeContent, ' ', true);
     if (!is_numeric($bid)) {
         throw new Exception('The currency is not supported or Google changed the response format');
     }
     return new Rate($bid, new \DateTime());
 }
示例#10
0
 /**
  * @test
  */
 public function it_fetches_a_rate_from_scalars()
 {
     $arrayProvider = new ArrayProvider(['EUR/USD' => 1.5, 'USD/GBP' => '1.25', 'JPY/GBP' => 1]);
     $eurUsd = $arrayProvider->fetchRate(CurrencyPair::createFromString('EUR/USD'));
     $usdGbp = $arrayProvider->fetchRate(CurrencyPair::createFromString('USD/GBP'));
     $jpyGbp = $arrayProvider->fetchRate(CurrencyPair::createFromString('JPY/GBP'));
     $this->assertEquals('1.50', $eurUsd->getValue());
     $this->assertEquals('1.25', $usdGbp->getValue());
     $this->assertEquals('1', $jpyGbp->getValue());
 }
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     if ('EUR' !== $currencyPair->getBaseCurrency()) {
         throw new UnsupportedCurrencyPairException($currencyPair);
     }
     $content = $this->fetchContent(self::URL);
     $xmlElement = StringUtil::xmlToElement($content);
     $cube = $xmlElement->Cube->Cube;
     $cubeAttributes = $cube->attributes();
     $date = new \DateTime((string) $cubeAttributes['time']);
     foreach ($cube->Cube as $cube) {
         $cubeAttributes = $cube->attributes();
         $cubeQuoteCurrency = (string) $cubeAttributes['currency'];
         if ($cubeQuoteCurrency === $currencyPair->getQuoteCurrency()) {
             return new Rate((string) $cubeAttributes['rate'], $date);
         }
     }
     throw new UnsupportedCurrencyPairException($currencyPair);
 }
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $content = $this->fetchContent(self::URL);
     $xmlElement = StringUtil::xmlToElement($content);
     $baseCurrency = (string) $xmlElement->Body->OrigCurrency;
     if ($baseCurrency !== $currencyPair->getBaseCurrency()) {
         throw new UnsupportedCurrencyPairException($currencyPair);
     }
     $cube = $xmlElement->Body->Cube;
     $cubeAttributes = $cube->attributes();
     $date = new \DateTime((string) $cubeAttributes['date']);
     foreach ($cube->Rate as $rate) {
         $rateAttributes = $rate->attributes();
         $rateQuoteCurrency = (string) $rateAttributes['currency'];
         if ($rateQuoteCurrency === $currencyPair->getQuoteCurrency()) {
             $rateValue = !empty($rateAttributes['multiplier']) ? (double) $rate / (int) $rateAttributes['multiplier'] : (double) $rate;
             return new Rate((string) $rateValue, $date);
         }
     }
     throw new UnsupportedCurrencyPairException($currencyPair);
 }
示例#13
0
 public function fetchRate(CurrencyPair $currencyPair)
 {
     /** @var CurrencyRateProvider $provider */
     $provider = CurrencyRateProvider::findOne($this->provider);
     if ($provider === null) {
         throw new Exception('Provider not found');
     }
     try {
         $providerHandler = $provider->getImplementationInstance($this->httpAdapter);
         $swap = new Swap($providerHandler);
         $rate = $swap->quote($currencyPair->getBaseCurrency() . '/' . $currencyPair->getQuoteCurrency())->getValue();
         if ($this->marginMultiplier !== null && $this->marginMultiplier > 1) {
             $rate *= $this->marginMultiplier;
         }
         if ($this->fixedMargin !== null && $this->fixedMargin > 0) {
             $rate += $this->fixedMargin;
         }
     } catch (\Exception $e) {
         throw new Exception('Calculating error');
     }
     return new Rate($rate, new \DateTime());
 }
示例#14
0
文件: Swap.php 项目: henrytrager/swap
 /**
  * {@inheritdoc}
  */
 public function quote($currencyPair)
 {
     if (is_string($currencyPair)) {
         $currencyPair = CurrencyPair::createFromString($currencyPair);
     } elseif (!$currencyPair instanceof CurrencyPair) {
         throw new \InvalidArgumentException('The currency pair must be either a string or an instance of CurrencyPair');
     }
     if (null !== $this->cache && null !== ($rate = $this->cache->fetchRate($currencyPair))) {
         return $rate;
     }
     $rate = $this->provider->fetchRate($currencyPair);
     if (null !== $this->cache) {
         $this->cache->storeRate($currencyPair, $rate);
     }
     return $rate;
 }
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     if (!$this->enterprise && 'USD' !== $currencyPair->getBaseCurrency()) {
         throw new UnsupportedCurrencyPairException($currencyPair);
     }
     if ($this->enterprise) {
         $url = sprintf(self::ENTERPRISE_URL, $this->appId, $currencyPair->getBaseCurrency(), $currencyPair->getQuoteCurrency());
     } else {
         $url = sprintf(self::FREE_URL, $this->appId);
     }
     $content = $this->fetchContent($url);
     $data = StringUtil::jsonToArray($content);
     if (isset($data['error'])) {
         throw new Exception($data['description']);
     }
     $date = new \DateTime();
     $date->setTimestamp($data['timestamp']);
     if ($data['base'] === $currencyPair->getBaseCurrency() && isset($data['rates'][$currencyPair->getQuoteCurrency()])) {
         return new Rate((string) $data['rates'][$currencyPair->getQuoteCurrency()], $date);
     }
     throw new UnsupportedCurrencyPairException($currencyPair);
 }
示例#16
0
 /**
  * @test
  */
 public function it_can_be_converted_to_a_string()
 {
     $pair = new CurrencyPair('EUR', 'USD');
     $this->assertEquals('EUR/USD', (string) $pair);
     $this->assertEquals('EUR/USD', $pair->toString());
 }
 public function __construct(CurrencyPair $currencyPair)
 {
     parent::__construct(sprintf('The currency pair "%s" is not supported.', $currencyPair->toString()));
     $this->currencyPair = $currencyPair;
 }
 protected function getKey(CurrencyPair $currencyPair, $date)
 {
     return $currencyPair->toString() . '_' . $date;
 }
示例#19
0
 /**
  * {@inheritdoc}
  */
 public function storeRate(CurrencyPair $currencyPair, Rate $rate)
 {
     $this->store->put($currencyPair->toString(), $rate, $this->ttl);
 }
示例#20
0
 /**
  * {@inheritdoc}
  */
 public function fetchRate(CurrencyPair $currencyPair)
 {
     $url = sprintf(self::URL, $currencyPair->getBaseCurrency(), $currencyPair->getQuoteCurrency());
     $content = $this->fetchContent($url);
     return new Rate((string) StringUtil::xmlToElement($content), new \DateTime());
 }