To retrieve historical data from Coinbase using PHP, you can utilize the Coinbase API. Below, I'll guide you through the steps to get historical price data using the Coinbase API.
### Step 1: Set Up Your Coinbase API
1. **Create a Coinbase Account**: If you don’t have an account, you’ll need to create one.
2. **Create an API Key**: Once you have an account, go to the API settings to create a new API key. Make sure to grant the appropriate permissions to the key.
### Step 2: Install a HTTP Client
In this example, we'll use Guzzle as the HTTP client to make requests to the Coinbase API:
```bash
composer require guzzlehttp/guzzle
```
### Step 3: Fetch Historical Data with PHP
Here is a sample PHP script that uses Guzzle to fetch historical price data:
```php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
function getHistoricalPrice($currencyPair, $start, $end, $granularity) {
$client = new Client();
// Coinbase API URL for historical prices
$url = "https://api.coinbase.com/v2/prices/{$currencyPair}/historic";
// Query parameters
$params = [
'start' => $start, // Start date in Y-m-d H:i:s format
'end' => $end, // End date in Y-m-d H:i:s format
'granularity' => $granularity // In seconds (3600 = 1 hour, 86400 = 1 day, etc.)
];
try {
$response = $client->get($url, [
'query' => $params,
'headers' => [
'CB-ACCESS-KEY' => 'YOUR_API_KEY',
// Include other headers as necessary
]
]);
// Decode JSON response
$data = json_decode($response->getBody(), true);
return $data;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
return null;
}
}
// Usage
$currencyPair = 'BTC-USD'; // An example currency pair
$start = '2023-10-01T00:00:00Z'; // Start date
$end = '2023-10-31T00:00:00Z'; // End date
$granularity = 86400; // 1 day in seconds
$historicalData = getHistoricalPrice($currencyPair, $start, $end, $granularity);
if ($historicalData) {
print_r($historicalData);
}
```
### Important Notes:
1. **API Key Security**: Avoid hardcoding your API key in the script. Use environment variables or secure storage to manage sensitive data.
2. **Error Handling**: Implement proper error handling for production code. The example here is for demonstration purposes and may require more robust solutions.
3. **Rate Limits**: Be aware of the Coinbase API rate limits. Exceeding these limits may result in your requests being blocked.
4. **API Documentation**: Check the [Coinbase API documentation](https://developers.coinbase.com/docs/wallet/api-reference) for the latest updates and changes.
This script provides a basic framework for fetching historical data. Adjust the parameters as needed based on your requirements.