Binance api ticker price

Binance API Series Pt. I – Spot Trading with Postman

Introduction

The purpose of this series is to introduce you to Binance’s REST API and to teach you how to interact with it. By the end, you should be confident in your ability to query information about the markets and your position and to place a range of different order types.

Prerequisites

Testnet keys

We’re going to use the testnet for our purposes. This will give us some funds with no real-world value to play around with. They function in exactly the same way as real coins and tokens, so once you’re comfortable with the API, you can start to use it to trade real funds.

  1. Start by heading over to the Spot Test Network.
  2. To get access, you’ll need to log in with a GitHub account. Create one if you haven’t already.
  3. Click Authenticate and sign in via GitHub.
  4. Under API Keys, you’ll be informed that you don’t have keys registered. Click on Generate HMAC_SHA256 Key to create a pair.
  5. On the next screen, give the keys a label. Call them whatever you want and hit Generate.
  6. You’re presented with two keys: the API Key and the Secret Key. It’s important that you record these now. You’ll need to start the key creation process again if you don’t. We recommend storing them on your machine’s notes app for easy copy-pasting later.

Downloading and installing Postman

Postman is an API Collaboration platform. It’s a perfect starting point for us – we’ll have access to collections of Binance requests that we’ll test without needing to write a single line of code.

Once that’s completed, locate it in your file explorer and install it. Fire up the application, and we’re good to go! Note that you can create an account to log in, but it isn’t necessary. If you want to skip that step, just select the option to do so at the bottom of the window.

Creating the environment

At this stage, you should have an interface that resembles the following.

The download shouldn’t take very long. Find it in your file explorer and unzip it. Then, we can head back into Postman.

  1. Select Import, and navigate to the folder you’ve just extracted (binance-postman-api).
  2. Enter it, then enter the environments folder.
  3. You’ll now see two files (one for mainnet and one for testnet). The one we’re after is binance_com_spot_testnet_api.postman_environment.json. Make sure you’ve got the correct one because our keys won’t work with the other.

On this screen, leave the timestamp and signature fields blank. These two values will be automatically created upon each request.

Importing the collection

Now we’re going to import the collection – this is an extensive assortment of requests that do the heavy lifting for us when we’re making calls. To load it into our environment:

  1. Click Import in the top left corner.
  2. In the popup, under the File tab, select Upload Files.
  3. We’re looking for the binance-postman-api folder again. Locate and open it.
  4. This time, enter collections in the subdirectory.
  5. There are two files here again. One is for working with the futures API. But we’re working with the spot one, so you’ll need to select the binance_spot_api_v1.postman_collection.json file.
  6. You should now see a confirmation screen that identifies the import as being in the Postman Collection format. Select Import.

Under the Collections tab to the left of the window, you’ll now notice that we have a folder with over 100 requests. Congratulations! We’re good to go. In the next section, we’ll take a look at the kinds of requests we can make.

Making Requests

If you expand the folders under the Collections tab, you’ll see that we have a bunch of different requests we can make. From the color-coding, you might note that there are three types of methods we can use:

  • GET : The GET method is used to retrieve stuff from a server. We’ll use this to find out information about your account balance, asset prices, etc.
  • POST : We’ll generally use the POST method to create information on a server. This is needed for things like placing orders, requesting withdrawals, etc.
  • DELETE : The DELETE method is a request for the server to delete information. It’ll come in handy for canceling orders.

Find the list of symbols and the trading rules

Time for our first request! We’re going to get the symbols we can trade on the exchange and the trading rules:

GET /exchangeInfo

This one doesn’t take any additional parameters – you could copy and paste that into your address bar, and you’d get a response. But for requests where we include several parameters, Postman makes it easy to see and modify them.

In the uppermost highlighted section, you’ll see some important information:

the time taken to receive the response (less than a second)

the size of the response (

In the second box is the bulk of the response. It’s been pretty-printed it so that it’s a bit easier on the eyes. This contains information on the exchange itself, as well as the pairs you can trade and their minimum/maximum amounts.

It looks like a lot of information, but the format makes it very easy to work with programmatically. When writing scripts to interact with it, you’ll easily be able to pick out specific properties of specific elements from the response.

Check the account balances

Let’s check what assets we have, and how much of each:

Congratulations on your newfound (non-existent) wealth!

How to get the current price for a symbol

We can go about getting the current price of an asset in different ways. Perhaps the simplest is with the following request:

As with the previous, you can change the symbol variable or remove it completely and get the latest price for all symbols.

Check the current order book depth

Order book depth (also referred to as depth of market, or DOM) can tell us a lot about the market. We’re going to make a call that will return some useful information:

Читайте также:  Airdrop криптовалюты как заработать

When we send this with the default values (Market > Order Book), we’re sent back a response that tells us about the bids and asks for BTCUSDT. The testnet server won’t yield as much data as the actual one, so below is a screenshot of what you would expect to see in a real environment:

In the highlighted section above, we can see the first bid. Since we’re looking at the book for BTCUSDT, the upper number is the price that someone is willing to pay for your BTC. Below is the amount they’re willing to buy. What this says, therefore, is that this order is asking for 0.999 BTC at a rate of 9704.65 USDT per BTC. If we continued to scroll down, we would see the offer price decrease – representing buyers that would pay less.

The top offer will naturally be the most attractive one if you’re looking for bang for your buck. That said, if you’re trying to market sell, say, 3 BTC, you’ll only be able to sell 0.999 BTC for the best price. You’ll need to take the subsequent (cheaper) offers until the entirety of your order is filled.

Place a test order

Now we’re going to post a test order.

You can see we have many more parameters involved. Let’s walk through the checked ones:

  • symbol – we’ve come across this one previously. This is the pair you want to trade.
  • side – here, you’ll stipulate whether you want to BUY or SELL. With the BTCUSDT pair, BUY indicates that you want to buy BTC for USDT, whereas sell will sell BTC for USDT.
  • type – the type of order you want to submit. Possible values (detailed here):
    • LIMIT
    • MARKET
    • STOP_LOSS
    • STOP_LOSS_LIMIT
    • TAKE_PROFIT
    • TAKE_PROFIT_LIMIT
    • LIMIT_MAKER
  • timeInForce– this parameter expresses how you want the order to execute:
    • GTC (good till canceled) – perhaps the most popular setup, GTC will ensure that your order is valid until it’s filled, or until you cancel it.
    • FOK (fill or kill) – FOK instructs the exchange to execute an order all at once. If the exchange can’t do so, the order is immediately canceled.
    • IOC (immediate or cancel) – either all or part of the order must be executed immediately, or it’s canceled. Unlike FOK, the orders are not canceled if they can be partially filled.
  • quantity – simply, the quantity of the asset that you want to buy or sell.
  • price – the price at which you want to sell. For the BTCUSDT pair, this is expressed in USDT.
  • newClientOrderId – an identifier for the order. This isn’t a mandatory field, but you can set it to an identifier that will make it easy to query later. Otherwise, it is randomly generated by the exchange.

Place a real order

Time to place a real fake order.

Your response returns a bunch of details about the order if successful.

Check an open order’s status

We got confirmation that the order was placed in the previous section, but what if we want to check it again later? We have a few requests at our disposal.

Lastly, we can query specific orders with:

Cancel an order

After some time, we might decide that the $40,000 target is a little too optimistic, so we want to cancel it. In that case, we’d use:

Place an order that fills instantly

Below, you can see that we’re about to submit a market order to sell BNB for BUSD at the current market price.

Note that the response gives us minimal information:

Источник

Binance api ticker price

Table of Contents generated with DocToc

Public Rest API for Binance (2021-05-12)

General API Information

  • The base endpoint is: https://api.binance.com
  • If there are performance issues with the endpoint above, these API clusters are also available:
    • https://api1.binance.com
    • https://api2.binance.com
    • https://api3.binance.com
  • All endpoints return either a JSON object or array.
  • Data is returned in ascending order. Oldest first, newest last.
  • All time and timestamp related fields are in milliseconds.

HTTP Return Codes

  • HTTP 4XX return codes are used for malformed requests; the issue is on the sender’s side.
  • HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.
  • HTTP 429 return code is used when breaking a request rate limit.
  • HTTP 418 return code is used when an IP has been auto-banned for continuing to send requests after receiving 429 codes.
  • HTTP 5XX return codes are used for internal errors; the issue is on Binance’s side. It is important to NOT treat this as a failure operation; the execution status is UNKNOWN and could have been a success.
  • Any endpoint can return an ERROR

Sample Payload below:

  • Specific error codes and messages are defined in Errors Codes.

General Information on Endpoints

  • For GET endpoints, parameters must be sent as a query string .
  • For POST , PUT , and DELETE endpoints, the parameters may be sent as a query string or in the request body with content type application/x-www-form-urlencoded . You may mix parameters between both the query string and request body if you wish to do so.
  • Parameters may be sent in any order.
  • If a parameter sent in both the query string and request body , the query string parameter will be used.

General Info on Limits

  • The following intervalLetter values for headers:
    • SECOND => S
    • MINUTE => M
    • HOUR => H
    • DAY => D
  • intervalNum describes the amount of the interval. For example, intervalNum 5 with intervalLetter M means «Every 5 minutes».
  • The /api/v3/exchangeInfo rateLimits array contains objects related to the exchange’s RAW_REQUEST , REQUEST_WEIGHT , and ORDER rate limits. These are further defined in the ENUM definitions section under Rate limiters (rateLimitType) .
  • A 429 will be returned when either rate limit is violated.
  • Every request will contain X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) in the response headers which has the current used weight for the IP for all request rate limiters defined.
  • Each route has a weight which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier weight .
  • When a 429 is received, it’s your obligation as an API to back off and not spam the API.
  • Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).
  • IP bans are tracked and scale in duration for repeat offenders, from 2 minutes to 3 days.
  • A Retry-After header is sent with a 418 or 429 responses and will give the number of seconds required to wait, in the case of a 429, to prevent a ban, or, in the case of a 418, until the ban is over.
  • The limits on the API are based on the IPs, not the API keys.
Читайте также:  История создания криптовалюты биткоин

Order Rate Limits

  • Every successful order response will contain a X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter) header which has the current order count for the account for all order rate limiters defined.
  • Rejected/unsuccessful orders are not guaranteed to have X-MBX-ORDER-COUNT-** headers in the response.
  • The order rate limit is counted against each account.
  • The API system is asynchronous, so some delay in the response is normal and expected.
  • Each endpoint has a data source indicating where the data is being retrieved, and thus which endpoints have the most up-to-date response.

These are the three sources, ordered by which is has the most up-to-date response to the one with potential delays in updates.

  • Matching Engine — the data is from the matching Engine
  • Memory — the data is from a server’s local or external memory
  • Database — the data is taken directly from a database

Some endpoints can have more than 1 data source. (e.g. Memory => Database) This means that the endpoint will check the first Data Source, and if it cannot find the value it’s looking for it will check the next one.

Endpoint security type

  • Each endpoint has a security type that determines how you will interact with it. This is stated next to the NAME of the endpoint.
    • If no security type is stated, assume the security type is NONE.
  • API-keys are passed into the Rest API via the X-MBX-APIKEY header.
  • API-keys and secret-keys are case sensitive.
  • API-keys can be configured to only access certain types of secure endpoints. For example, one API-key could be used for TRADE only, while another API-key can access everything except for TRADE routes.
  • By default, API-keys can access all secure routes.
Security Type Description
NONE Endpoint can be accessed freely.
TRADE Endpoint requires sending a valid API-Key and signature.
USER_DATA Endpoint requires sending a valid API-Key and signature.
USER_STREAM Endpoint requires sending a valid API-Key.
MARKET_DATA Endpoint requires sending a valid API-Key.
  • TRADE and USER_DATA endpoints are SIGNED endpoints.

SIGNED (TRADE and USER_DATA) Endpoint security

  • SIGNED endpoints require an additional parameter, signature , to be sent in the query string or request body .
  • Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation.
  • The signature is not case sensitive.
  • totalParams is defined as the query string concatenated with the request body .
  • A SIGNED endpoint also requires a parameter, timestamp , to be sent which should be the millisecond timestamp of when the request was created and sent.
  • An additional parameter, recvWindow , may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000.
  • The logic is as follows:

Serious trading is about timing. Networks can be unstable and unreliable, which can lead to requests taking varying amounts of time to reach the servers. With recvWindow , you can specify that the request must be processed within a certain number of milliseconds or be rejected by the server.

It is recommended to use a small recvWindow of 5000 or less! The max cannot go beyond 60,000!

SIGNED Endpoint Examples for POST /api/v3/order

Here is a step-by-step example of how to send a valid signed payload from the Linux command line using echo , openssl , and curl .

Key Value
apiKey vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A
secretKey NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j
Parameter Value
symbol LTCBTC
side BUY
type LIMIT
timeInForce GTC
quantity 1
price 0.1
recvWindow 5000
timestamp 1499827319559

Example 1: As a request body

requestBody: symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

HMAC SHA256 signature:

curl command:

Example 2: As a query string

queryString: symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

HMAC SHA256 signature:

curl command:

Example 3: Mixed query string and request body

queryString: symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC

requestBody: quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559

HMAC SHA256 signature:

curl command:

Note that the signature is different in example 3. There is no & between «GTC» and «quantity=1».

Public API Endpoints

These terms will be used throughout the documentation, so it is recommended especially for new users to read to help their understanding of the API.

  • base asset refers to the asset that is the quantity of a symbol. For the symbol BTCUSDT, BTC would be the base asset .
  • quote asset refers to the asset that is the price of a symbol. For the symbol BTCUSDT, USDT would be the quote asset .

Symbol status (status):

  • PRE_TRADING
  • TRADING
  • POST_TRADING
  • END_OF_DAY
  • HALT
  • AUCTION_MATCH
  • BREAK

Symbol type:

Order status (status):

Status Description
NEW The order has been accepted by the engine.
PARTIALLY_FILLED A part of the order has been filled.
FILLED The order has been completed.
CANCELED The order has been canceled by the user.
PENDING_CANCEL Currently unused
REJECTED The order was not accepted by the engine and not processed.
EXPIRED The order was canceled according to the order type’s rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill)
or by the exchange, (e.g. orders canceled during liquidation, orders canceled during maintenance)

OCO Status (listStatusType):

Status Description
RESPONSE This is used when the ListStatus is responding to a failed action. (E.g. Orderlist placement or cancellation)
EXEC_STARTED The order list has been placed or there is an update to the order list status.
ALL_DONE The order list has finished executing and thus no longer active.

OCO Order Status (listOrderStatus):

Status Description
EXECUTING Either an order list has been placed or there is an update to the status of the list.
ALL_DONE An order list has completed execution and thus no longer active.
REJECT The List Status is responding to a failed action either during order placement or order canceled

ContingencyType

Order types (orderTypes, type):

More information on how the order types definitions can be found here: Types of Orders

  • LIMIT
  • MARKET
  • STOP_LOSS
  • STOP_LOSS_LIMIT
  • TAKE_PROFIT
  • TAKE_PROFIT_LIMIT
  • LIMIT_MAKER

Order Response Type (newOrderRespType):

Order side (side):

Time in force (timeInForce):

This sets how long an order will be active before expiration.

Status Description
GTC Good Til Canceled
An order will be on the book unless the order is canceled.
IOC Immediate Or Cancel
An order will try to fill the order as much as it can before the order expires.
FOK Fill or Kill
An order will expire if the full order cannot be filled upon execution.

Kline/Candlestick chart intervals:

m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

Rate limiters (rateLimitType)

Rate limit intervals (interval)

Test connectivity to the Rest API.

Weight: 1

Parameters: NONE

Data Source: Memory

Response:

Check server time

Test connectivity to the Rest API and get the current server time.

Weight: 1

Parameters: NONE

Data Source: Memory

Response:

Current exchange trading rules and symbol information

Weight: 10

Parameters:

There are 3 possible options:

Options Example
No parameter curl -X GET «https://api.binance.com/api/v3/exchangeInfo»
symbol curl -X GET «https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC»
symbols curl -X GET «https://api.binance.com/api/v3/exchangeInfo?symbols=%5B%22BNBBTC%22,%22BTCUSDT%22%5D» or curl -g GET ‘https://api.binance.com/api/v3/exchangeInfo?symbols=[«BTCUSDT»,»BNBBTC»]’

If any symbol provided in either symbol or symbols do not exist, the endpoint will throw an error.

Data Source: Memory

Response:

Market Data endpoints

Weight: Adjusted based on the limit:

Limit Weight
5, 10, 20, 50, 100 1
500 5
1000 10
5000 50

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 100; max 5000. Valid limits:[5, 10, 20, 50, 100, 500, 1000, 5000]

Data Source: Memory

Response:

Recent trades list

Get recent trades.

Weight: 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 500; max 1000.

Data Source: Memory

Response:

Old trade lookup (MARKET_DATA)

Get older trades.

Weight: 5

Parameters:

Name Type Mandatory Description
symbol STRING YES
limit INT NO Default 500; max 1000.
fromId LONG NO TradeId to fetch from. Default gets most recent trades.

Data Source: Database

Response:

Compressed/Aggregate trades list

Get compressed, aggregate trades. Trades that fill at the time, from the same taker order, with the same price will have the quantity aggregated.

Weight: 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
fromId LONG NO ID to get aggregate trades from INCLUSIVE.
startTime LONG NO Timestamp in ms to get aggregate trades from INCLUSIVE.
endTime LONG NO Timestamp in ms to get aggregate trades until INCLUSIVE.
limit INT NO Default 500; max 1000.
  • If both startTime and endTime are sent, time between startTime and endTime must be less than 1 hour.
  • If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.

Data Source: Database

Response:

Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.

Weight: 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
interval ENUM YES
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
  • If startTime and endTime are not sent, the most recent klines are returned.

Data Source: Database

Response:

Current average price

Current average price for a symbol.

Weight: 1

Parameters:

Name Type Mandatory Description
symbol STRING YES

Data Source: Memory

Response:

24hr ticker price change statistics

24 hour rolling window price change statistics. Careful when accessing this with no symbol.

Weight: 1 for a single symbol; 40 when the symbol parameter is omitted

Parameters:

Name Type Mandatory Description
symbol STRING NO
  • If the symbol is not sent, tickers for all symbols will be returned in an array.

Data Source: Memory

Response:

Symbol price ticker

Latest price for a symbol or symbols.

Weight: 1 for a single symbol; 2 when the symbol parameter is omitted

Parameters:

Name Type Mandatory Description
symbol STRING NO
  • If the symbol is not sent, prices for all symbols will be returned in an array.

Data Source: Memory

Response:

Symbol order book ticker

Best price/qty on the order book for a symbol or symbols.

Weight: 1 for a single symbol; 2 when the symbol parameter is omitted

Parameters:

Name Type Mandatory Description
symbol STRING NO
  • If the symbol is not sent, bookTickers for all symbols will be returned in an array.

Data Source: Memory

Response:

New order (TRADE)

Send in a new order.

Weight: 1

Parameters:

Name Type Mandatory Description
symbol STRING YES
side ENUM YES
type ENUM YES
timeInForce ENUM NO
quantity DECIMAL NO
quoteOrderQty DECIMAL NO
price DECIMAL NO
newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent.
Orders with the same newClientOrderID can be accepted only when the previous one is filled, otherwise the order will be rejected.
stopPrice DECIMAL NO Used with STOP_LOSS , STOP_LOSS_LIMIT , TAKE_PROFIT , and TAKE_PROFIT_LIMIT orders.
icebergQty DECIMAL NO Used with LIMIT , STOP_LOSS_LIMIT , and TAKE_PROFIT_LIMIT to create an iceberg order.
newOrderRespType ENUM NO Set the response JSON. ACK , RESULT , or FULL ; MARKET and LIMIT order types default to FULL , all other orders default to ACK .
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES

Some additional mandatory parameters based on order type :

Type Additional mandatory parameters Additional Information
LIMIT timeInForce , quantity , price
MARKET quantity or quoteOrderQty MARKET orders using the quantity field specifies the amount of the base asset the user wants to buy or sell at the market price.
E.g. MARKET order on BTCUSDT will specify how much BTC the user is buying or selling.

MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty .
E.g. Using the symbol BTCUSDT:
BUY side, the order will buy as many BTC as quoteOrderQty USDT can.
SELL side, the order will sell as much BTC needed to receive quoteOrderQty USDT.

STOP_LOSS quantity , stopPrice This will execute a MARKET order when the stopPrice is reached.
STOP_LOSS_LIMIT timeInForce , quantity , price , stopPrice
TAKE_PROFIT quantity , stopPrice This will execute a MARKET order when the stopPrice is reached.
TAKE_PROFIT_LIMIT timeInForce , quantity , price , stopPrice
LIMIT_MAKER quantity , price This is a LIMIT order that will be rejected if the order immediately matches and trades as a taker.
This is also known as a POST-ONLY order.

Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty .

Any order with an icebergQty MUST have timeInForce set to GTC .

MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty . Trigger order price rules against market price for both MARKET and LIMIT versions:

Price above market price: STOP_LOSS BUY , TAKE_PROFIT SELL

Price below market price: STOP_LOSS SELL , TAKE_PROFIT BUY

Data Source: Matching Engine

Источник

Читайте также:  Что такое идентификатор транзакции bitcoin
Оцените статью