Content

  • Introduction

  • Prerequisites

    • Test network keys

    • Download and install Postman

  • Creating an environment

  • Import a collection

  • Execution of requests

  • Final thoughts


Introduction

Understanding and using the cryptocurrency trading API can open up a world of possibilities when it comes to entering and exiting positions. With some basic programming knowledge, you can connect to the exchange's backend to automate your trading strategies. By bypassing the website, you can get to the matching engine for high-performance applications much faster.

The purpose of this series is to introduce you to the Binance REST API and teach you how to interact with it. In the end, you should be confident in your ability to query the markets and your positions, and place a number of different types of orders.

In this article, we will use Postman to communicate with the exchange. Don't worry - we won't put real money at risk.


Prerequisites

Test network keys

We are going to use a testnet for our purposes. This will give us some funds that have no real value and with which we can experiment. They work exactly like real coins and tokens, so once you get used to the API, you can start using it to trade real money.


  1. Start by going to the Spot Test Network.

  2. You must be signed in with a GitHub account to gain access. Create it if you haven't already.

  3. Click "Authenticate" and sign in with GitHub.

  4. In the "API Keys" section, you will see that you have no registered keys. Click on Generate HMAC_SHA256 Key to generate a pair.

  5. On the next screen, give the keys a label. Name them whatever you want and click "Generate".

  6. You will be presented with two keys: API Key and Secret Key. It is important to write them down now. If you don't, you'll have to start the key generation process again. We recommend saving them in a note-taking application on your computer for easy copying later.

Note: Labeling your keys is something you should do when using a live exchange to manage different keys. Your account can have multiple keys with different permissions. If you use multiple trading bots, using individual keys with descriptive labels makes it easier to manage permissions or remove individual keys without changing all of your bots.


Download and install Postman

Postman is a platform for API collaboration. This is a perfect starting point for us – we will have access to Binance query collections to test without writing a single line of code.

The program is available for Mac, Windows and Linux. Go to the Downloads page and download the .zip file.

After that, find it in the explorer and install it. Open the app to get started. Please note that you can create an account to log in, but this is not required. If you want to skip this step, just select the appropriate option at the bottom of the window.


Creating an environment

At this point you should have an interface similar to the following.



First, you need to create an environment. It's just a way to add variables to the set of queries we're going to work with. To do this, we first need to get some information from the Binance GitHub repository. Go here and download the .zip file.



The download won't take long. Find it in your file explorer and unzip it. Then, we can go back to Postman.



Click the gear icon in the upper right corner (as shown above). You will see a "Manage Environments" pop-up window.

  1. Select "Import" and navigate to the newly unzipped folder (binance-postman-api).

  2. Then enter the environment folder.

  3. You will now see two files (one for the main network, one for the test network). We are looking for binance_com_spot_testnet_api.postman_environment.json. Make sure you choose the correct one because our keys don't work with others.



Almost done. Click on "Binance Spot Testnet API" and you will see the variables below. Edit the two parameters highlighted in red by inserting the keys you saved earlier. Click "Update" and exit the pop-up window.



On this screen, leave the "timestamp" and "signature" fields blank. These two values ​​will be automatically generated on each request.

There is still something left to do. To the right of the gear icon we clicked to set up the environment earlier, you'll see a drop-down menu that currently says "No Environment". Click on it and select "Binance Spot Testnet API".


Import a collection

Now we are going to import a collection which is a large set of queries that do the heavy lifting for us. To upload it to our environment, follow these steps:

  1. Click "Import" in the upper left corner.

  2. In the pop-up window, on the "File" tab, select "Upload Files".

  3. We are again looking for the binance-postman-api folder. Find and open it.

  4. This time enter "collections" in the subdirectory.

  5. Here are two files again. One for working with the futures API. But we are working with spot, so you need to select the binance_spot_api_v1.postman_collection.json file.

  6. You should now see a confirmation screen identifying the import as Postman collection format. Select "Import".

On the Collections tab on the left side of the window you will now notice that we have a folder with over 100 requests. Congratulations! All right. In the next section, we'll look at what requests we can send.


Execution of requests

If you expand the folders under the Collections tab, you'll see that we have tons of different queries that we can do. From the color coding, you can see that we can use three types of methods:


  • GET: The "GET" method is used to retrieve data from the server. We will use it to find out information about your account balance, asset prices, etc.

  • POST: We usually use the "POST" method to create information on the server. This is necessary for things like placing orders, requesting withdrawals, etc.

  • DELETE: The "DELETE" method is a request to the server to delete information. It will be useful for canceling orders.


Search for a list of symbols and trading rules

Time for our first query! We are going to get the symbols that can be traded on the exchange and the trading rules:

GET /exchangeInfo


This request doesn't take any additional parameters - you can copy and paste it into the address bar and you'll get a response. Postman makes it easier to view and modify queries where we include multiple parameters.

To download this request, select Market > Exchange Information. The following tab will appear:



We don't need to do anything else here, so click "Send". You will get the answer:



In the top highlighted section, you will see important information:

  • response status (200 means the request is successful, 400-499 means we have a problem)

  • time required to receive a response (less than a second)

  • response size (~22KB).


The second field contains the main part of the answer. It's beautifully printed to make it a little easier on the eyes. It contains information about the exchange itself, as well as the pairs you can trade with and their minimum/maximum amounts.

It seems that there is a lot of information, but the format makes it easy to work with it programmatically. When writing interaction scripts, you can easily select certain properties of certain elements from the response.


Checking the account balance

Let's check what assets we have and how many:

GET /account

This request can be found under "Trade" > "Account Information". Click on it and you will see a layout similar to the previous one. However, you'll also notice that we have two new variables: "timestamp" and "signature". Signature is a security measure. Since we are now asking for confidential information, this will prove that we are the owner of the account.

The timestamp tells the server when the request was sent. Because networks can be unreliable or down, the server may receive our request much later than expected. If too much time has passed, it will reject the request. You can specify how long you want to wait using the "recvWindow" parameter, which defaults to 5,000 milliseconds.

Postman handles the creation of both of these fields for us. Click "Send" and you will receive a reply. Under Balances, you should see six assets – BNB, BTC, BUSD, ETH, LTC and TRX. The balance will be divided into free and locked. We haven't blocked anything yet, so all your assets should be free.

Congratulations on your new (non-existent) wealth!


How to find out the current price of a symbol

We can get the current price of an asset in different ways. Perhaps the simplest is with such a request:

GET /api/v3/ticker/24hr

As you might have guessed, this will give us information on asset prices for the last 24 hours. Find it in "Market" > "24hr Ticker Price Change Statistic"s. The default pair we see as a symbol variable is BTCUSDT.

You can send it right now to see a breakdown of pricing information. You can also change the symbol (to BNBBUSD, LTCUSDT, etc.), or you can uncheck the variable to return data for 40 pairs.

We also have a simpler call ("Market" > "Symbol Price Ticker") that returns the current price at which the asset is trading:

GET /api/v3/price

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


Checking the current order book depth

The depth of the order book (also called the depth of the market or DOM) can tell us a lot about the market. We're going to make a call to return useful information:

GET api/v3/depth

When we send it with the default values ​​("Market" > "Order Book"), we get a response that tells us the bid and ask for BTCUSDT. The testnet server will not output 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 section highlighted above, we see the first trouble. Since we are looking at the ledger for BTCUSDT, the top number is the price someone is willing to pay for your BTC. Below is the amount they are willing to buy. So this suggests that this order is asking for 0.999 BTC at a rate of 9,704.65 USDT per BTC. If we were to continue scrolling down, we would see the offer price decrease - meaning the buyer will be paid less.

The best offer will naturally be the most attractive if you want to make a profit. However, if you try to sell on the market, say 3 BTC, you will only be able to sell 0.999 BTC at the best price. You will need to accept further (cheaper) bids until your order is fully filled.



Keep scrolling and you will see the ask. Functionally, they are similar to bids, except that they are orders to sell BTC for USDT.


Placing a test order

Now we will place a test order.

POST api/v3/order/test

Even though we are just using testnet funds, this request will not actually result in an order being placed. This can be useful for testing orders before sending them. Find it under "Trade" > "Test New Order (TRADE)".



As you can see, we have even more parameters involved. Let's go through the marked:


  • symbol - we've seen this before. This is the pair you want to trade.

  • side – here you indicate whether you want to BUY or SELL. For the BTCUSDT pair, BUY indicates that you want to buy BTC for USDT, while SELL will sell BTC for USDT.

  • type – the type of order you want to send. Possible values ​​(details 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 be executed:

    • GTC (Good Until Canceled) is perhaps the most popular setting. GTC guarantees that your order is valid until it is executed or until you cancel it.

    • FOK (Execute or Cancel) – FOK instructs the exchange to execute the order immediately. If the exchange cannot do this, the order will be canceled immediately.

    • IOC (Execute Immediately or Cancel) – The order must be executed in whole or in part immediately or it will be cancelled. Unlike FOK, orders are not canceled if they can be partially executed.

  • quantity is simply the amount of the asset 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 – order identifier. This is not a required field, but you can set it to an identifier that will simplify the query later. Otherwise, it is randomly generated on the exchange.

Fine! Now let's create a test order. We are going to use the automatically generated values: a sell limit order of 0.1 BTC per USDT at a price of $9,000. Click "Send". If everything was successful, we'll just get {{}} as a response.

 

Placing a real order

Time to place a real fake order.

POST /api/v3/order

Go to Trade > New Order. You are already familiar with test orders, so the parameters here will not surprise you. Let's leave all the values ​​as they are, but change the price we're selling at to $40,000. Change the price value to reflect this. Then click "Send".

If successful, your response will contain detailed information about the order.


Checking the status of an open order

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

GET /api/v3/openOrders

You will find it under "Trade" > "Current Open Orders (USER_DATA)". BTCUSDT is selected by default. If you press "Send" you will receive all your open BTCUSDT orders (so far you should only see the one we set earlier). You can leave out the symbol, which will instead return all your open orders.

GET /api/v3/allOrders

"Trade" > "All Orders (USER_DATA)" gives you an overview of all orders, not just open ones. Here you must specify the symbol. "orderId", "startTime", "endTime" are optional parameters that can help you refine your search. We'll leave them here, so uncheck the boxes. Click "Send" and you will see the same response as before. If you have had closed or canceled orders, you will also see them here.


Finally, we can request specific orders using:

GET /api/v3/order

Get it under "Trade" > "Query Order (USER_DATA)". You will need to specify either "orderId" or "origClientOrderId" (an optional "newClientOrderId" tag that can be added to orders). Uncheck "orderId". For "origClientOrderId" we are going to provide the default tag that was used before - "my_order_id_1". Fill in the field and click "Send" to receive a response.


Order cancellation

After some time, we may decide that the $40,000 target is too optimistic, so we want to cancel the order. In this case we would use:

DELETE /api/v3/order

Under "Trade" > "Cancel Order", a query that will allow us to highlight orders for cancellation. Uncheck "orderId" and "newClientOrderId" and pass "my_order_id_1" as the value for "origClientOrderId".

When you send this request, the order will be returned. If you scroll down to "status" you will see that it is indeed cancelled. To confirm this, again use the GET /api/v3/openOrders endpoint (with an empty list) or GET /api/v3/order with origClientOrderId .


Blurring of the order, which is filled instantly

Our previous order was not executed because it was a limit order that will only work when the price of BTC reaches $40,000. In the case of a market order, we are essentially saying "buy/sell at whatever price the asset is currently trading at". This order will fill instantly.

For this, let's return to "Trade" > "New Order". We are going to demonstrate the response type (newOrderRespType), which is a parameter that we can configure depending on the response we want to receive from the server. There are three options here: ACK, RESULT, or FULL - you can see examples of each response here. We are going to use an "ACK" which will give us a simple confirmation that the order has been received.

Below you can see that we are going to send a market order to sell BNB for BUSD at the current market price.



Note that the response gives us minimal information:



You can verify that the order has been filled through the /api/v3/allOrders endpoint.


Checking your deals

Finally, let's look at an endpoint for verifying your transactions:

GET /api/v3/myTrades

The request is in the "Trade" > "Account Trade List (USER_DATA)" section. It allows you to check each transaction by a specific symbol. If you want to see all your trades for the default symbol (BTCUSDT), just uncheck "startTime", "endTime" and "fromId". The answer will return up to 500 trades - just change the limit if you want to see more.


Debugging with Postman

In Postman, you can additionally expose the raw HTTP request and response.



This menu will open the Postman console, which shows the details of each request.



Final thoughts

The purpose of this guide is to introduce you to the Binance API without writing a single line of code. If you have completed all the necessary steps, you should now understand how we can request and send information.

In the next parts of this series, we will introduce some basic coding concepts that allow us to automate the buying and selling of cryptocurrencies and other digital assets.

Do you have any more questions? Visit our growing Binance developer community forum, or check out the documentation.