Kucoin / kucoin-php-sdk

PHP SDK for KuCoin API.
https://docs.kucoin.com
MIT License
79 stars 41 forks source link

React Event loop #105

Open RCTORONTO opened 3 years ago

RCTORONTO commented 3 years ago

How would I go about using the websocketfeed to get

['topic' => '/market/ticker:XHV-USDT'] ['topic' => '/market/ticker:XHV-USDT'], ['topic' => '/spotMarket/tradeOrders'], ['topic' => '/account/balance']

into a single event loop, is there any example that covers having these 4 items push, having one call to the api->subscribePrivateChannels seems to block the next...

RCTORONTO commented 3 years ago

3 items, not 4

hhxsv5 commented 3 years ago
// Subscribe multiple channels
$channels = [
    ['topic' => '/market/ticker:XHV-USDT']
    ['topic' => '/market/ticker:XHV-USDT'],
    ['topic' => '/spotMarket/tradeOrders'],
    ['topic' => '/account/balance'],
];
RCTORONTO commented 3 years ago

`<?php

require DIR . '/vendor/autoload.php'; use KuCoin\SDK\Auth; use KuCoin\SDK\KuCoinApi; use KuCoin\SDK\PrivateApi\WebSocketFeed; use KuCoin\SDK\PrivateApi\Account; use KuCoin\SDK\Exceptions\HttpException; use KuCoin\SDK\Exceptions\BusinessException; use KuCoin\SDK\PrivateApi\Order; use KuCoin\SDK\PrivateApi\Fill; use KuCoin\SDK\PublicApi\Symbol;

use Ratchet\Client\WebSocket; use React\EventLoop\Factory; use React\EventLoop\LoopInterface;

//KuCoinApi::setBaseUri('https://openapi-sandbox.kucoin.com'); $BOT=array(); $BOT['settings']=parse_ini_file("/etc/rc/ku-xhv.ini", true); KuCoinApi::setDebugMode($BOT['settings']['debug']['enabled']);

// Logging in your code KuCoinApi::setLogPath('/tmp'); KuCoinApi::setLogLevel(Monolog\Logger::DEBUG);

if($BOT['settings']['debug']['enabled']){KuCoinApi::getLogger()->debug("ku-xhv-ws-bot logging started...");}

require ( 'vendor/phpclasses/circular-buffer/CircularBuffer.phpclass' ) ;

$auth = null; // Need to pass the Auth parameter when subscribing to a private channel($api->subscribePrivateChannel()). // $auth = new Auth('key', 'secret', 'passphrase'); $auth = new Auth('xxx', 'xxx','xxxx', Auth::API_KEY_VERSION_V2); $api = new WebSocketFeed($auth); //$api_private = new WebSocketFeed($auth); // store our bot details in 'BOT' $BOT['orders']=array(); $BOT['xhv']=array(); $BOT['usdt']=array(); $BOT['xhv']['prices']=new CircularBuffer(100); $BOT['settings']['firstrun']=true; $BOT['yins']=array(); $BOT['yins']['count']=0; $BOT['yangs']=array(); $BOT['yangs']['count']=0; $BOT['bot_completed_orders']=0; $BOT['xhv']['price']=null;

//$api_account = new Account($auth); //$api_orders = new Order($auth); //$api_symbol = new Symbol(); system("clear"); printf("BOT: ws xhv starting up...\n");sleep(1); sleep(3); // Use a custom event loop instance if you like $BOT['currentprice_ts']=null; $BOT['lastprice_ts']=null; $loop = Factory::create(); $loop->addPeriodicTimer(1, function () { // var_dump(date('Y-m-d H:i:s')); global $BOT; // xhv price is set by socketfeed

printf("%s %.3f\n",date("m/d H:i:s",time()),$BOT['xhv']['price']);
if($BOT['settings']['firstrun']){$BOT['settings']['firstrun']=false;}

}); $api->setLoop($loop); $query = ['connectId' => uniqid('', true)]; $channels = [ ['topic' => '/market/ticker:XHV-USDT'], ['topic' => '/spotMarket/tradeOrders'], ['topic' => '/account/balance'] ]; /* $api_private->subscribePrivateChannels($query, $channels, function (array $message, WebSocket $ws, LoopInterface $loop) use ($api_private) { global $BOT; printf(var_dump($message)); // Unsubscribe the channel // $ws->send(json_encode($api->createUnsubscribeMessage('/market/ticker:ETH-BTC')));

// Stop loop
// $loop->stop();

}, function ($code, $reason) { echo "OnClose: {$code} {$reason}\n"; }); */ $api->subscribePublicChannels($query, $channels, function (array $message, WebSocket $ws, LoopInterface $loop) use ($api) { global $BOT; $BOT['xhv']['price']=$message['data']['price']; printf(var_dump($message)); // Unsubscribe the channel // $ws->send(json_encode($api->createUnsubscribeMessage('/market/ticker:ETH-BTC')));

// Stop loop
//$loop->stop();

}, function ($code, $reason) { echo "OnClose: {$code} {$reason}\n"; });

?>`

gets the price, I never see any order updates or account info messages

RCTORONTO commented 3 years ago

I can access the api in the full version of the script just fine for my account in the synchronous version

RCTORONTO commented 3 years ago

be great to have a barebones example that works with the private feed

EDIT: I cant seem to figure out how to connect to the Private Channels websocket feed altogether (I only ever get the public channel subscription symbol ticker updates)

"The recommended way is to just create a websocket connection and subscribe to multiple channels." .... yes I'd love to, how?

RCTORONTO commented 3 years ago

`<?php require DIR . '/vendor/autoload.php'; use KuCoin\SDK\Auth; use KuCoin\SDK\KuCoinApi; use KuCoin\SDK\PrivateApi\WebSocketFeed;

use KuCoin\SDK\Exceptions\HttpException; use KuCoin\SDK\Exceptions\BusinessException;

use Ratchet\Client\WebSocket; use React\EventLoop\Factory; use React\EventLoop\LoopInterface; use KuCoin\SDK\Http\SwooleHttp; use Swoole\Runtime; Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_SLEEP); //Swoole\Runtime::enableCoroutine(); require('vendor/phpclasses/circular-buffer/CircularBuffer.phpclass');

//KuCoinApi::setBaseUri('https://openapi-sandbox.kucoin.com');

$BOT=array(); $BOT['settings']=parse_ini_file("/etc/rc/ku-xhv-ws.ini", true);

KuCoinApi::setDebugMode($BOT['settings']['debug']['enabled']); KuCoinApi::setLogPath('/mnt/BACKUP'); KuCoinApi::setLogLevel(Monolog\Logger::DEBUG); if($BOT['settings']['debug']['enabled']){KuCoinApi::getLogger()->debug("ku-xhv-ws-bot logging started...");}

$auth = null; $auth = new Auth('xxx', 'xxx','xxx', Auth::API_KEY_VERSION_V2);

$api = new WebSocketFeed($auth); //$api_private = new WebSocketFeed($auth);

$BOT['orders']=array(); $BOT['xhv']=array(); $BOT['usdt']=array(); $BOT['settings']['firstrun']=true; $BOT['xhv']['price']=null; system("clear"); $loop = Factory::create(); $loop->addPeriodicTimer(1, function () { // var_dump(date('Y-m-d H:i:s')); global $BOT; // xhv price is set by socketfeed printf("%s %.3f\n",date("m/d H:i:s",time()),$BOT['xhv']['price']); if($BOT['settings']['firstrun']){$BOT['settings']['firstrun']=false;}

});

//$api->setLoop($loop);

//$query_private = ['connectId' => uniqid('', true)]; $query = ['connectId' => uniqid('', true)];

$channels = [ ['topic' => '/market/ticker:XHV-USDT'], ]; $pchannels = [ ['topic' => '/spotMarket/tradeOrders'], ['topic' => '/account/balance'], ];

$api->setLoop($loop); //$api_private->setLoop($loop); go(function() use ($api, $query, $pchannels) { $api->subscribePrivateChannels($query, $pchannels, function (array $message, WebSocket $ws, LoopInterface $loop) use ($api) { global $BOT; printf(var_dump($message)); if($BOT['settings']['debug']['enabled']){KuCoinApi::getLogger()->debug("got a private message?");} // never see that message }, function ($code, $reason) { echo "OnClose: {$code} {$reason}\n"; }); }); printf("\n\nPrivate running??\n\n"); // see that message go(function() use ($api, $query, $channels) { $api->subscribePublicChannels($query, $channels, function (array $message, WebSocket $ws, LoopInterface $loop) use ($api) { global $BOT; $BOT['xhv']['price']=$message['data']['price']; printf(var_dump($message)); if($BOT['settings']['debug']['enabled']){KuCoinApi::getLogger()->debug("got a public message?");} // only works when called before the subscribePrivateChannels }, function ($code, $reason) { echo "OnClose: {$code} {$reason}\n"; }); });

printf("\n\nPublic running??\n\n"); // never see that message

?> ` No dice... I see ticker messages, two sets of pings and pongs, but no account balance or orders messages from the private subscribe

RCTORONTO commented 3 years ago

commenting $loop->run(); in Private websocket subscribe channels solved my concurrency issue... still not getting any balance or orders messages, I do see welcome, ping and pong for both the connections (private - to get my details & public - to get the currency prices etc)

RCTORONTO commented 3 years ago

$query_pri = ['connectId' => uniqid('', true),'privateChannel'=>true,'response'=>true];

was needed, wasn't obvious because there's no example demonstrating privateChannel subscription

makopov commented 2 years ago

Can you paste where you put $loop->run();? I'm running into a similar issue I believe... I'm not even sure I understand what a loop is for.