Back to Ccxt

Fetch Ohlcv Many Exchanges Continuosly

wiki/examples/php/fetch-ohlcv-many-exchanges-continuosly.md

4.5.522.1 KB
Original Source
php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------

// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

// -----------------------------------------------------------------------------

error_reporting(E_ALL);
date_default_timezone_set('UTC');

use ccxt\Precise;
use React\Async;
use React\Promise;


// AUTO-TRANSPILE //
// fetch and handle constinuosly
function fetch_ohlcv_continuously($exchange, $symbol) {
   return Async\async(function () use ($exchange, $symbol) {
       while (true) {
           try {
               $ohlcv = Async\await($exchange->fetch_ohlcv($symbol));
               $ohlcv_length = count($ohlcv);
               var_dump('Fetched ', $exchange->id, ' - ', $symbol, ' candles. last candle: ', $ohlcv[$ohlcv_length - 1]);
           } catch(Exception $e) {
               var_dump($e);
               break;
           }
       }

   }) ();
}


// start exchanges and fetch OHLCV loop
function start_exchange($exchange_name, $symbols) {
   return Async\async(function () use ($exchange_name, $symbols) {
       $exchange_class = '\ccxt\async\\'.$exchange_name;
       $ex = new $exchange_class(array());
       $promises = [];
       for ($i = 0; $i < count($symbols); $i++) {
           $symbol = $symbols[$i];
           $promises[] = fetch_ohlcv_continuously($ex, $symbol);
       }
       Async\await(Promise\all($promises));
       Async\await($ex->close());
   }) ();
}


// main function
function example() {
   return Async\async(function () {
       $exchanges = ['binance', 'okx', 'kraken'];
       $symbols = ['BTC/USDT', 'ETH/USDT'];
       $promises = [];
       for ($i = 0; $i < count($exchanges); $i++) {
           $exchange_name = $exchanges[$i];
           $promises[] = start_exchange($exchange_name, $symbols);
       }
       Async\await(Promise\all($promises));
   }) ();
}


Async\await(example());