PHP code example of marekskopal / twelvedata

1. Go to this page and download the library: Download marekskopal/twelvedata library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

marekskopal / twelvedata example snippets


use MarekSkopal\TwelveData\TwelveData;
use MarekSkopal\TwelveData\Enum\IntervalEnum;

// Create TwelveData instance
$twelveData = new TwelveData('<yourApiKey>');

// Get the one minute time series for the AAPL symbol. Response is in form of strict typed DTO (Data Transfer Object)
$response = $twelveData->coreData->timeSeries(
    symbol: 'AAPL',
    interval: IntervalEnum::OneMinute,
);

// Alternatively, you can use the low level interface
$response = $twelveData->get(
    '/time_series',
    [
        'symbol' => 'AAPL',
        'interval' => '1min',
    ],
);

use MarekSkopal\TwelveData\TwelveData;
use MarekSkopal\TwelveData\Enum\IntervalEnum;

$twelveData = new TwelveData('<yourApiKey>');

// Build requests without executing them
$requests = [
    'ts'   => $twelveData->coreData->timeSeriesRequest(symbol: 'AAPL', interval: IntervalEnum::OneMinute),
    'q'    => $twelveData->coreData->quoteRequest(symbol: 'TSLA'),
    'rate' => $twelveData->currencies->exchangeRateRequest(symbol: 'USD/EUR'),
];

// Execute all requests in a single batch call
$response = $twelveData->executeBatch($requests);

// Retrieve typed results
$timeSeries  = $response->get('ts');   // TimeSeries
$quote       = $response->get('q');    // Quote
$exchangeRate = $response->get('rate'); // ExchangeRate

// Check for per-request errors
if ($response->isError('ts')) {
    $error = $response->getError('ts'); // BatchItemError
}

use MarekSkopal\TwelveData\TwelveData;
use MarekSkopal\TwelveData\Config\Config;
use MarekSkopal\TwelveData\Dto\WebSocket\PriceEvent;
use MarekSkopal\TwelveData\WebSocket\PhrityWebSocketClient;

$twelveData = new TwelveData(new Config(apiKey: '<yourApiKey>'));
$realTimePrice = $twelveData->createRealTimePrice(new PhrityWebSocketClient());

$realTimePrice->connect();
$realTimePrice->subscribe(['AAPL', 'EUR/USD', 'BTC/USD']);

while ($realTimePrice->isConnected()) {
    $event = $realTimePrice->receive();

    if ($event instanceof PriceEvent) {
        echo "{$event->symbol}: {$event->price}\n";
    }
}

$realTimePrice->disconnect();