How to save websockets data to DB

Viewed 826

I wanna read this stream: wss://stream.binance.com:9443/ws/btcusdt@trade and save the data to db so i can work with it later.

I dont know how or where to call the function because it is continuous stream of data and I dont know how to handle it.

Im using this php library:

https://github.com/jaggedsoft/php-binance-api

more specific this code:

$api->trades(["BNBBTC"], function($api, $symbol, $trades) {
    echo "{$symbol} trades update".PHP_EOL;
    print_r($trades);
});

I know how to save the data to db, but i dont know how to call the function.

public function x(){
$api = new API("api", "secret";
$api->trades(["BTCUSDT"], function($api, $symbol, $trades) {
            $data = new BinanceData();
            $data->symbol = $symbol;
            $data->price = $trades['price'];
            $data->binance_timestamps = $trades['timestamp'];
            $data->maker = $trades['maker'];
            $data->quantity = $trades['quantity'];
            $data->save();
        });
}

I call this function directly when i visit /x route:

Route::get('/x', [BinanceController::class, 'x']);

The question is how to call this function in background in Laravel so i dont have to access any routes or anything.

Thank you

1 Answers

Create a laravel artisan command, register it in the kernel. Then use supervisor on linux or any process manager to continually call it to create a daemon

https://laravel.com/docs/8.x/artisan

Related