Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

php-binance-api

> 编程语言
Open source

PHP Binance API is an asynchronous PHP library for the Binance API designed to be easy to use. https://github.com/binance-exchange/php-binance-api

644 stars0 likes0 views
WebsiteGitHub

About

PHP Binance API is an asynchronous PHP library for the Binance API designed to be easy to use. https://github.com/binance-exchange/php-binance-api

PHP Binance API

This project is designed to help you make your own projects that interact with Binance. You can stream candlestick chart data, market depth, or use other advanced features such as setting stop losses and iceberg orders. This project seeks to have complete API coverage (spot and futures) including WebSockets.

Installation

composer require "jaggedsoft/php-binance-api @dev"

Click for help with installation

Install Composer

If the above step didn't work, install composer and try again.

Debian / Ubuntu

bash
sudo apt-get install curl php-curl
curl -s http://getcomposer.org/installer | php
php composer.phar install

Composer not found? Use this command instead:

php composer.phar require "jaggedsoft/php-binance-api @dev"

Windows:

Download installer for Windows

Getting started

composer require jaggedsoft/php-binance-api

php
require 'vendor/autoload.php';
// 1. config in home directory
$api = new Binance\API();
// 2. config in specified file
$api = new Binance\API( "somefile.json" );
// 3. config by specifying api key and secret
$api = new Binance\API("","");
// 4. config by specifying api key, api secret and testnet flag. By default the testnet is disabled
$api = new Binance\API("","", true);
// 5. Rate Limiting Support
$api = new Binance\RateLimiter(new Binance\API());

See additional options for more options and help installing on Windows

Rate Limiting

This Feature is in beta, you can start using rate limiting as a wrapper to the main API class.

php
$api = new Binance\API( "somefile.json" );
$api = new Binance\RateLimiter($api);
while(true) {
   $api->openOrders("BNBBTC"); // rate limited
}

=======

Security - CA Bundles

If you don't know what a CA bundle is, no action is required. If you do know and you don't like our auto upate feature. You can disable the downloading of the CA Bundle

php
$api = new Binance\API( "somefile.json" );
$api->caOverride = true;

Get latest price of all symbols

php
$ticker = $api->prices();
print_r($ticker);

View Response

…

Get latest price of a symbol

php
$price = $api->price("BNBBTC");
echo "Price of BNB: {$price} BTC.".PHP_EOL;

Get miniTicker for all symbols

php
$api->miniTicker(function($api, $ticker) {
	print_r($ticker);
});

View Response

…

Get balances for all of your positions, including estimated BTC value

php
$ticker = $api->prices(); // Make sure you have an updated ticker object for this to work
$balances = $api->balances($ticker);
print_r($balances);
echo "BTC owned: ".$balances['BTC']['available'].PHP_EOL;
echo "ETH owned: ".$balances['ETH']['available'].PHP_EOL;
echo "Estimated Value: ".$api->btc_value." BTC".PHP_EOL;

View Response

    [WTC] => Array
        (
            [available] => 909.61000000
            [onOrder] => 0.00000000
            [btcValue] => 0.94015470
        )

    [BNB] => Array
        (
            [available] => 1045.94316876
            [onOrder] => 0.00000000
            [btcValue] => 0.21637426
        )
... (more)

Get all bid/ask prices

php
$bookPrices = $api->bookPrices();
print_r($bookPrices);
echo "Bid price of BNB: {$bookPrices['BNBBTC']['bid']}".PHP_EOL;

View Response

…

Place a LIMIT order

php
$quantity = 1;
$price = 0.0005;
$order = $api->buy("BNBBTC", $quantity, $price);
php
$quantity = 1;
$price = 0.0006;
$order = $api->sell("BNBBTC", $quantity, $price);

Place a MARKET order

php
$quantity = 1;
$order = $api->marketBuy("BNBBTC", $quantity);
php
$quantity = 0.01;
$order = $api->marketSell("ETHBTC", $quantity);

View Response

(
    [symbol] => BNBBTC
    [orderId] => 7652393
    [clientOrderId] => aAE7BNUhITQj3eg04iG1sY
    [transactTime] => 1508564815865
    [price] => 0.00000000
    [origQty] => 1.00000000
    [executedQty] => 1.00000000
    [status] => FILLED
    [timeInForce] => GTC
    [type] => MARKET
    [side] => BUY
)

Place a STOP LOSS order

php
// When the stop is reached, a stop order becomes a market order
$type = "STOP_LOSS"; // Set the type STOP_LOSS (market) or STOP_LOSS_LIMIT, and TAKE_PROFIT (market) or TAKE_PROFIT_LIMIT
$quantity = 1;
$price = 0.5; // Try to sell it for 0.5 btc
$stopPrice = 0.4; // Sell immediately if price goes below 0.4 btc
$order = $api->sell("BNBBTC", $quantity, $price, $type, ["stopPrice"=>$stopPrice]);
print_r($order);

Place an ICEBERG order

php
// Iceberg orders are intended to conceal the true order quantity.
$type = "LIMIT"; // LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT
$quantity = 1;
$price = 0.5;
$icebergQty = 10;
$order = $api->sell("BNBBTC", $quantity, $price, $type, ["icebergQty"=>$icebergQty]);
print_r($order);

Getting 24hr ticker price change statistics for a symbol

php
$prevDay = $api->prevDay("BNBBTC");
print_r($prevDay);
echo "BNB price change since yesterday: ".$prevDay['priceChangePercent']."%".PHP_EOL;

Complete Account Trade History

php
$history = $api->history("BNBBTC");
print_r($history);

View Response

…

Get Market Depth

php
$depth = $api->depth("ETHBTC");
print_r($depth);

Get Open Orders

php
$openorders = $api->openOrders("BNBBTC");
print_r($openorders);

Get Order Status

php
$orderid = "7610385";
$orderstatus = $api->orderStatus("ETHBTC", $orderid);
print_r($orderstatus);

Cancel an Order

php
$response = $api->cancel("ETHBTC", $orderid);
print_r($response);

Market History / Aggregate Trades

php
$trades = $api->aggTrades("BNBBTC");
print_r($trades);

Get all account orders; active, canceled, or filled.

php
$orders = $api->orders("BNBBTC");
print_r($orders);

Get Kline/candlestick data for a symbol

php
//Periods: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
$ticks = $api->candlesticks("BNBBTC", "5m");
print_r($ticks);

View Response

…

WebSocket API

miniTicker return the latest candlestick information for every symbol

php
$api->miniTicker(function($api, $ticker) {
	print_r($ticker);
});

View Response

…

Realtime Complete Chart Updates via WebSockets

php
$api->chart(["BNBBTC"], "15m", function($api, $symbol, $chart) {
	echo "{$symbol} chart update\n";
	print_r($chart);
});

View Response

…

Get latest candlestick data only

php
$api->kline(["BTCUSDT", "EOSBTC"], "5m", function($api, $symbol, $chart) {
  //echo "{$symbol} ({$interval}) candlestick update\n";
	$interval = $chart->i;
	$tick = $chart->t;
	$open = $chart->o;
	$high = $chart->h;
	$low = $chart->l;
	$close = $chart->c;
	$volume = $chart->q; // +trades buyVolume assetVolume makerVolume
	echo "{$symbol} price: {$close}\t volume: {$volume}\n";
});

Trade Updates via WebSocket

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

Get ticker updates for all symbols via WebSocket

php
$api->ticker(false, function($api, $symbol, $ticker) {
	print_r($ticker);
});

Get ticker updates for a specific symbol via WebSocket

php
$api->ticker("BNBBTC", function($api, $symbol, $ticker) {
	print_r($ticker);
});

Realtime updated depth cache via WebSockets

php
$api->depthCache(["BNBBTC"], function($api, $symbol, $depth) {
	echo "{$symbol} depth cache update".PHP_EOL;
	//print_r($depth); // Print all depth data
	$limit = 11; // Show only the closest asks/bids
	$sorted = $api->sortDepth($symbol, $limit);
	$bid = $api->first($sorted['bids']);
	$ask = $api->first($sorted['asks']);
	echo $api->displayDepth($sorted);
	echo "ask: {$ask}".PHP_EOL;
	echo "bid: {$bid}".PHP_EOL;
});

View Response

…

User Data: Account Balance Updates, Trade Updates, New Orders, Filled Orders, Cancelled Orders via WebSocket

…

View Response

…

Withdraw

php
$asset = "BTC";
$address = "1C5gqLRs96Xq4V2ZZAR1347yUCpHie7sa";
$amount = 0.2;
$response = $api->withdraw($asset, $address, $amount);
print_r($response);

Withdraw with addressTag

php
//Required for coins like XMR, XRP, etc.
$address = "44tLjmXrQNrWJ5NBsEj2R77ZBEgDa3fEe9GLpSf2FRmhexPvfYDUAB7EXX1Hdb3aMQ9FLqdJ56yaAhiXoRsceGJCRS3Jxkn";
$addressTag = "0e5e38a01058dbf64e53a4333a5acf98e0d5feb8e523d32e3186c664a9c762c1
";
$amount = 0.1;
$response = $api->withdraw($asset, $address, $amount, $addressTag);
print_r($response);

Get All Withdraw History

php
$withdrawHistory = $api->withdrawHistory();
print_r($withdrawHistory);

Get Withdraw History for a specific asset

php
$withdrawHistory = $api->withdrawHistory("BTC");
print_r($withdrawHistory);

Get Deposit Address

php
$depositAddress = $api->depositAddress("VEN");
print_r($depositAddress);

Get All Deposit History

php
$depositHistory = $api->depositHistory();
print_r($depositHistory);

Troubleshooting

If you get the following errors, please synchronize your system time.

signedRequest error: {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
signedRequest error: {"code":-1021,"msg":"Timestamp for this request is outside of the recvWindow."}
balanceData error: Please make sure your system time is synchronized, or pass the useServerTime option.

useServerTime

php
//Call this before running any functions
$api->useServerTime();

Installing on Windows

Download and install composer:

  1. https://getcomposer.org/download/
  2. Create a folder on your drive like C:\Binance
  3. Run command prompt and type cd C:\Binance
  4. composer require jaggedsoft/php-binance-api
  5. Once complete copy the vendor folder into your project.

Config file in home directory

If you dont wish to store your API key and secret in your scripts, load it from your home directory

bash
mkdir -vp ~/.config/jaggedsoft/
cat >  ~/.config/jaggedsoft/php-binance-api.json "
}
EOF

Config file in home directory to operate on testnet

Testnet have its own credentials, see the testnet documentation page for more details.

bash
mkdir -vp ~/.config/jaggedsoft/
cat >  ~/.config/jaggedsoft/php-binance-api.json ",
    "api-secret": "",
    "use-testnet": true
}
EOF

Config file in home directory with curl options

bash
mkdir -vp ~/.config/jaggedsoft/
cat >  ~/.config/jaggedsoft/php-binance-api.json ",
    "curlOpts": {
	    "CURLOPT_SSL_VERIFYPEER": 0,
	    "INVALID_CONSTANT_NAME": 42
    }

}
EOF

Optionally add proxy configuration

bash
mkdir -vp ~/.config/jaggedsoft/
cat >  ~/.config/jaggedsoft/php-binance-api.json ",
    "proto": "https",
    "address": "proxy.domain.com",
    "port": "1080"
}
EOF

custom location

php
$api = new Binance\API( "myfile.json" );

Basic stats: Get api call counter

php
$api->getRequestCount();

Basic stats: Get total data transferred

php
$api->getTransfered();

Security - Disable downloading of CA Bundles

You can disable the downloading of the CA Bundle:

php
$api = new Binance\API( "somefile.json" );
$api->caOverride = true;

Documentation

There are also numerous other formats available here: https://github.com/jaggedsoft/php-binance-api/tree/gh-pages

Star History

Contribution

  • Give us a star :star:
  • Fork and Clone! Awesome
  • Select existing issues or create a new issue and give us a PR with your bugfix or improvement after. We love it ❤️

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPbinancecryptocurrencycryptocurrency-exchangesphp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言