Skip to content

Commit

Permalink
Change data provider
Browse files Browse the repository at this point in the history
  • Loading branch information
pgrimaud committed Dec 31, 2023
1 parent e13e29a commit 19f3582
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 19 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ Show forex data on your LaMetric.

![lametric-forex](https://user-images.githubusercontent.com/1866496/71490521-daf2a680-2833-11ea-9278-9ab49b481476.gif)

Many thanks & Based on [Free Forex API](https://www.freeforexapi.com/) ❤️

## Feedback

If you need help, [create an issue](https://github.com/pgrimaud/lametric-forex/issues) or contact me on [Twitter](http://twitter.com/pgrimaud_)
2 changes: 2 additions & 0 deletions public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

Sentry\init(['dsn' => $config['sentry_key']]);

header('Content-Type: application/json');

$response = new Response();

try {
Expand Down
23 changes: 6 additions & 17 deletions src/Forex/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class Api
{
const DATA_ENDPOINT = 'https://www.freeforexapi.com/api/live';
const DATA_ENDPOINT = 'https://open.er-api.com/v6/latest/USD';

/**
* @var array
Expand Down Expand Up @@ -42,7 +42,7 @@ public function fetchData(Validator $validator): void

// save to redis
$this->predisClient->set($redisKey, json_encode($this->data));
$this->predisClient->expire($redisKey, 60 * 5);
$this->predisClient->expire($redisKey, 3600);
} else {
$this->data = json_decode($launchesFile, true);
}
Expand All @@ -64,25 +64,14 @@ private function callApi(string $pair, Validator $validator): array
$resource = $this->guzzleClient->request('GET', $endpoint);
$data = json_decode((string)$resource->getBody(), true);

if ((int)$data['code'] !== 200) {
$rates = $data['rates'];

// all pairs are USD, so let's try USD => CURRENCY1 => CURRENCY2
if ($validator->getCurrency1() !== 'USD') {
$newPairBase = $this->callApi('USD' . $validator->getCurrency2(), $validator);
$newPairCompare = $this->callApi('USD' . $validator->getCurrency1(), $validator);

$newPairBaseFixed = $newPairBase['price']['price'] ?? $newPairBase['price'];

return [
'price' => round($newPairBaseFixed / $newPairCompare['price'], 2),
];
}

throw new InvalidArgumentException('Invalid pair');
if(!isset($rates[$validator->getCurrency1()]) || !isset($rates[$validator->getCurrency2()])){
throw new InvalidArgumentException('Invalid pair');
}

return [
'price' => $data['rates'][$pair]['rate'] ?? ['price' => 0],
'price' => round($rates[$validator->getCurrency2()] / $rates[$validator->getCurrency1()], 2)
];
}

Expand Down

0 comments on commit 19f3582

Please sign in to comment.