GithubHelp home page GithubHelp logo

binance-connector-php's Introduction

Binance Connector PHP

This is a thin library that working as a connector to the Binance public API.

Installation

composer require binance/binance-connector-php

How to use

require_once 'vendor/autoload.php';

$client = new \Binance\Spot();
$response = $client->time();
echo json_encode($response);


$client = new \Binance\Spot(['key' => $key, 'secret' => $secret]);
$response = $client->account();
echo json_encode($response);

Please find examples folder for more endpoints

RSA Signature

RSA signature is supported.

# RSA Key(Unencrypted) Authentication
$key = ''; # api key is also required
$privateKey = 'file:///path/to/rsa/private/key.pem';

$client = new \Binance\Spot([
    'key'  => $key,
    'privateKey'  => $privateKey, # pass the key file directly
    'baseURL' => 'https://testnet.binance.vision'
]);

# RSA key(Encrypted) Authentication
$key = '';
$encryptedPrivateKey = 'file:///path/to/rsa/private/key.pem';
$privateKey = openssl_pkey_get_private($encryptedPrivateKey, 'password');

$client = new \Binance\Spot([
    'key'  => $key,
    'privateKey'  => $privateKey,
    'baseURL' => 'https://testnet.binance.vision'
]);

Testnet

The spot testnet is available. In order to test on testnet:

$client = new \Binance\Spot([
    'baseURL' => 'https://testnet.binance.vision'
]);

RecvWindow

From Binance API, recvWindow is available for all endpoints require signature. By default, it's 5000ms. You are allowed to set this parameter to any value less than 60000, number beyond this limit will receive error from Binance server.

$client = new \Binance\Spot(['key' => $key, 'secret' => $secret]);
$response = $client->getOrder('BNBUSDT', [
        'orderId'    => '11',
        'recvWindow' => 10000
    ]
);

Optional parameters

For the optional parameters in the endpoint, pass exactly the field name from API document into the optional parameter array. e.g

$response = $client->cancelOCOOrder('BNBUSDT',
    [
        'orderListId' => '12'
    ]
);

The mandartory parameter is validated in the library level, missing required parameter will throw Binance\Exception\MissingArgumentException.

Timeout

Time out in seconds.

$client = new \Binance\Spot(['timeout' => 0.5]);

$response = $client->time();

echo json_encode($response);

Display meta info

Binance API server returns weight usage in the header of each response. This is very useful to indentify the current usage. To reveal this value, simpily intial the client with show_weight_usage=True as:

$client = new \Binance\Spot(['showWeightUsage' => true]);
$response = $client->time();
echo json_encode($response);

this will returns:

{"data":{"serverTime":1590579807751},"weight_usage":{"x-mbx-used-weight":["2"],"x-mbx-used-weight-1m":["2"]}}

It's also able to print out all headers, which may be very helpful for debug:

$client = new \Binance\Spot(['showHeader' => true]);
$response = $client->time();
echo json_encode($response);

the returns will be like:

{"data":{"serverTime":1590579942001},"header":{"Content-Type":["application/json;charset=utf-8"],"Transfer-Encoding":["chunked"],...}}

Websocket

$client = new \Binance\Websocket\Spot();

$callbacks = [
    'message' => function($conn, $msg){
        echo $msg.PHP_EOL;
    },
    'ping' => function($conn, $msg) {
        echo "received ping from server".PHP_EOL;
    }
];

$client->aggTrade('btcusdt', $callbacks);

It's able to provide a customlized websocket connector.

$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$client = new \Binance\Websocket\Spot(['wsConnector' => $connector]);

$callbacks = [
    'message' => function($conn, $msg){
        echo "received message".PHP_EOL;
    },
    'pong' => function($conn) {
        echo "received pong from server".PHP_EOL;
    },
    'ping' => function($conn) {
        echo "received ping from server".PHP_EOL;
    },
    'close' => function($conn) {
        echo "receive closed.".PHP_EOL;
    }
];

$client->miniTicker('btcusdt', $callbacks);

# send ping to server intervally
$loop->addPeriodicTimer(2, function () use ($client) {
    $client->ping();
    echo "ping sent ".PHP_EOL;
});

$loop->run();

Listen to combined stream:

$client->combined([
    'btcusdt@miniTicker',
    'ethusdt@miniTicker'
], $callbacks);

Test

# install the packages
composer install

vendor/bin/phpunit

Limitation

Futures and Vanilla Options APIs are not supported:

  • /fapi/*
  • /dapi/*
  • /vapi/*
  • Associated Websocket Market and User Data Streams

Contributing

Contributions are welcome. If you've found a bug within this project, please open an issue to discuss what you would like to change. If it's an issue with the API, please open a topic at Binance Developer Community

License

MIT

binance-connector-php's People

Contributors

2pd avatar alplabin avatar slvler avatar tantialex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

binance-connector-php's Issues

How to use the php api?

Good afternoon. I program in php. I would like to access the exchange through your api. Before that, I traded on another exchange in the same way, the api was simple and clear there, but it's hard to figure it out, you need help. I understand that some kind of file is needed, it connects everywhere - vendor/autoload.php . What is it and how to download it? I don't understand. Help please.

subAccountUniversalTransferHistory (Master account) is not functioning

GET https://api.binance.com/sapi/v1/sub-account/universalTransfer?page=1&recvWindow=5000&timestamp=1663519465973&signature=XXX results in in a 400 Bad Request response: {"code":100001002,"msg":"Unsupported operation"} in MYPATH/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113 Stack trace: #0 MYPATH/vendor/guzzlehttp/guzzle/src/Middleware.php(69): GuzzleHttp\Exception\RequestException::create() #1 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(204): GuzzleHttp\Middleware::GuzzleHttp{closure}() #2 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(153): GuzzleHttp\Promise\Promise::callHandler() #3 MYPATH/vendor/guzzlehttp/promises/src/TaskQueue.php(48): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}() #4 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(248): GuzzleHttp\Promise\TaskQueue->run() #5 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(224): GuzzleHttp\Promise\Promise->invokeWaitFn() #6 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(269): GuzzleHttp\Promise\Promise->waitIfPending() #7 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(226): GuzzleHttp\Promise\Promise->invokeWaitList() #8 MYPATH/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending() #9 MYPATH/vendor/guzzlehttp/guzzle/src/Client.php(187): GuzzleHttp\Promise\Promise->wait() #10 MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php(104): GuzzleHttp\Client->request() #11 MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php(98): Binance\APIClient->processRequest() #12 MYPATH/vendor/binance/binance-connector-php/src/Binance/Spot/SubAccount.php(553): Binance\APIClient->signRequest() #13 MYPATH/test4.php(14): Binance\Spot->subAccountUniversalTransferHistory() #14 {main} in MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php:106 Stack trace: #0 MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php(98): Binance\APIClient->processRequest() #1 MYPATH/vendor/binance/binance-connector-php/src/Binance/Spot/SubAccount.php(553): Binance\APIClient->signRequest() #2 MYPATH/test4.php(14): Binance\Spot->subAccountUniversalTransferHistory() #3 {main} thrown in MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php on line 106

XXX - the real signature is substituted, as well as MYPATH - is for the original URL/URI/path masquerading.

Spot WebSocket API

Any ETA when the "Spot WebSocket API" will be implemented in binance-connector-php
like in binance-connector-java and binance-connector-python

Thanks

Fix bug with showHeader => true and weightUsage => true

I detect bug with enabled both showHeader and weightUsage, returns only weightUsage in array without header.
I fixed this in method processRequest in file /src/Binance/APIClient.php
Fixed code:

    private function processRequest($method, $path, $params = array())
    {
        try {
            $response = $this->httpRequest->request($method, $this->buildQuery($path, $params));
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            throw new ClientException($e);
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            throw new ServerException($e);
        }

        $body = json_decode($response->getBody(), true);
        
        // fixed show header bug with weight usage
        $returnData = null;
        if ($this->showWeightUsage || $this->showHeader) {
            $returnData['data'] = $body;
        }
        
        if ($this->showWeightUsage) {
            $weights = [];
            foreach ($response->getHeaders() as $name => $value) {
                $name = strtolower($name);
                if (strpos($name, 'x-mbx-used-weight') === 0 ||
                    strpos($name, 'x-mbx-order-count') === 0 ||
                    strpos($name, 'x-sapi-used') === 0) {
                    $weights[$name] = $value;
                }
            }
            
            $returnData['weight_usage'] = $weights;
        }
            
        if ($this->showHeader) {
            $returnData['header'] = $response->getHeaders();
        }

        return is_null($returnData) ? $body : $returnData;
    }

openssl_sign(): Supplied key param cannot be coerced into a private key

I implemented this package in my Laravel project and initialized it like this

            $client = new Spot([
                'key'  => config('binance.testnet.api_key'),
                'privateKey'  => config('binance.testnet.api_secret'),
                'baseURL' => 'https://testnet.binance.vision'
            ]);

a simple $client->time() returns the timecode. But if I want to send an order or want to get some account info, I will get this error:
openssl_sign(): Supplied key param cannot be coerced into a private key

What do I wrong?

composer require binance/binance-connector-php issue

composer require binance/binance-connector-php
Could not find a version of package binance/binance-connector-php matching
your minimum-stability (stable). Require it with an explicit version constr
aint allowing its desired stability.

can you tell me the dependence i should install. (php 7.4.30 installed)

Uncaught Error: Class "Binance\Spot" not found

i get below error
Fatal error: Uncaught Error: Class "Binance\Spot" not found in C:\xampp\htdocs\binance\test.php:4 Stack trace: #0 {main} thrown in C:\xampp\htdocs\binance\test.php on line 4

SimpleEarn Endpoint Outdated

I want to use the new endpoints for simpleearn enabled in the Binance API since August 26, 2023, I have already tried to update the php library on my server but it still does not appear available, do you have any plans to update the library soon term? or you can help me update my library locally with the new simpleearn endpoints. I would appreciate your help.

imagen

contribution guide

Is there any contribution guides? I want to implement connector for USDM-Futures, has some one already start working on that?

Fatal error after PHP update

Fatal error: Uncaught Error: Class "Psr\Log\NullLogger" not found in XXX/vendor/binance/binance-connector-php/src/Binance/APIClient.php:73 Stack trace: #0 XXX/vendor/binance/binance-connector-php/src/Binance/Spot.php(35): Binance\APIClient->__construct() #1 MYscript: Binance\Spot->__construct() #2 {main} thrown in XXX/vendor/binance/binance-connector-php/src/Binance/APIClient.php on line 73

Any idea, what is the cause for the error? Just updated PHP 7.4 to PHP v8.1, updated and re-installed all the packages, and the previously working script still causes such an error....

subAccount list query stopped working since 2022-09-20 20:00:00 UTC

I am constantly monitoring new sub-users on hourly base via
GET https://api.binance.com/sapi/v1/sub-account/list?page=1&limit=500&recvWindow=5000&timestamp=CURRENT_TIMESTAMP&signature=VALID_SIGNATURE.
Since 2022-09-20 20:00:00 UTC it stopped working, resulting in the following output:

Fatal error: Uncaught Binance\Exception\ClientException: GuzzleHttp\Exception\ClientException: Client error: GET https://api.binance.com/sapi/v1/sub-account/list?page=1&limit=500&recvWindow=5000&timestamp=CURRENT_TIMESTAMP&signature=VALID_SIGNATURE resulted in a 400 Bad Request response: {"code":-10038,"msg":"Broker account is not supported."} in /MYPATH/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113 Stack trace: #0 /MYPATH/vendor/guzzlehttp/guzzle/src/Middleware.php(69): GuzzleHttp\Exception\RequestException::create() #1 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(204): GuzzleHttp\Middleware::GuzzleHttp{closure}() #2 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(153): GuzzleHttp\Promise\Promise::callHandler() #3 /MYPATH/vendor/guzzlehttp/promises/src/TaskQueue.php(48): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}() #4 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(248): GuzzleHttp\Promise\TaskQueue->run() #5 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(224): GuzzleHttp\Promise\Promise->invokeWaitFn() #6 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(269): GuzzleHttp\Promise\Promise->waitIfPending() #7 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(226): GuzzleHttp\Promise\Promise->invokeWaitList() #8 /MYPATH/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending() #9 /MYPATH/vendor/guzzlehttp/guzzle/src/Client.php(187): GuzzleHttp\Promise\Promise->wait() #10 /MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php(104): GuzzleHttp\Client->request() #11 /MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php(98): Binance\APIClient->processRequest() #12 /MYPATH/vendor/binance/binance-connector-php/src/Binance/Spot/SubAccount.php(48): Binance\APIClient->signRequest() #13 /MYPATH/subuserminitor.php(28): Binance\Spot->subAccountList() #14 {main} in /MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php:106 Stack trace: #0 /MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php(98): Binance\APIClient->processRequest() #1 /MYPATH/vendor/binance/binance-connector-php/src/Binance/Spot/SubAccount.php(48): Binance\APIClient->signRequest() #2 /MYPATH/subuserminitor.php(28): Binance\Spot->subAccountList() #3 {main} thrown in /MYPATH/vendor/binance/binance-connector-php/src/Binance/APIClient.php on line 106

Please help with the issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.