Untitled

mail@pastecode.io avatar
unknown
php_laravel_blade
a year ago
2.3 kB
4
Indexable
Never
<?php
namespace App\Services;

use Carbon\Carbon;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class IEXCloud {
    const API_URL = "https://cloud.iexapis.com/stable/";
    const SANDBOX_API_URL = "https://sandbox.iexapis.com/stable/";
    const STOCKS_PER_REQUEST = 20;

    /**
     * @var \GuzzleHttp\Client
     */
    protected $guzzle;

    /**
     * @var string
     */
    private $api_key;

    public function __construct($api_key)
    {
        $this->api_key = $api_key;
        $this->guzzle = new Client();
    }

    public function multi_single_day(array $symbols, Carbon $date) {
        $stocks = collect();
        $url = 'stock/market/batch';

        foreach(collect($symbols)->chunk(self::STOCKS_PER_REQUEST) as $symbols_chunk) {
            $stocks_chunk = $this->execute($url, [
                'types' => 'chart',
                'chartByDay' => 'true',
                'symbols' => $symbols_chunk->implode(','),
                'range' => 'date',
                'exactDate' => $date->format('Ymd')
            ]);

            foreach($symbols_chunk as $symbol) {
                if(isset($stocks_chunk->$symbol))
                    $stocks[$symbol] = $stocks_chunk->$symbol->chart;
            }
        }

        return $stocks;
    }

    public function price(string $symbol, Carbon $date) {
        if(now()->isBefore($date))
            return false;

        $result = $this->multi_single_day([$symbol], $date);
        if($result->isEmpty() || empty($result[$symbol]))
            return null;
        
        return $result[$symbol][0]->close;
    }

    protected function execute($method, array $arguments) {
        $arguments['token'] = $this->api_key;
        $link = self::API_URL . $method . '?' . http_build_query($arguments);

        try {
            $response = $this->guzzle->get($link);
        } catch (RequestException $e) {
            if($e->getResponse()->getBody()->getContents() == 'Unknown symbol') {
                return [];
            } else {
                throw $e;
            }
        }

        $json_response = (string) $response->getBody();
        return json_decode($json_response);
    }
}