Binance API Series Pt. I – Spot Trading with Postman
HomeArtikel

Binance API Series Pt. I – Spot Trading with Postman

Advanced
3w ago
13m

Introduction

Understanding and using an API for cryptocurrency trading can open up a world of possibilities when it comes to entering and exiting positions. With some simple coding knowledge, you can plug into an exchange’s backend to automate your trading strategies. By sidestepping the website, you can take a much faster path to the matching engine for high-performance applications.

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.

In this article, we’ll be using Postman to communicate with the exchange. Don’t worry – we won’t be putting any real funds at risk.


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.

Note: labelling your keys is something worth doing when using the real exchange in order to manage different keys. Your account can have multiple keys with different permissions. If you’re running several trading bots, using separate keys with descriptive labels makes it easier to manage permissions or delete individual keys without changing all of your bots.


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.

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

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.



We want to first create our environment. This is just a way for us to add variables to the set of requests we’re going to work with. To do that, we’ll first need to grab some information from the Binance GitHub repository. Head over here and download the .zip file.



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



Click on the gear icon in the top right-hand corner (illustrated above). You’ll be greeted with a Manage Environments popup. 

  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.



Almost there. Click on Binance Spot Testnet API, and you’ll see the variables below. Edit the two parameters outlined in red by pasting in the keys you saved earlier. Click update and exit out of the popup.



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

There’s one last thing to do. To the right of the gear icon we clicked to set up the environment earlier, you’ll see a dropdown menu that currently says No Environment. Click it and select Binance Spot Testnet API.


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.

To load up this request, select Market > Exchange Information. A tab like the following will pop up:



We don’t need to do anything else here, so go ahead and hit Send. You’ll then get a response:



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

  • the status of the response (200 means we’ve been successful, 400-499 means we’ve run into an issue)

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

  • the size of the response (~22KB).


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:

GET /account

This one can be found under Trade > Account Information. Click on it, and you’ll see a similar layout to the previous one. You’ll also note, however, that we have two new variables: timestamp and signature. The signature is a security measure. Because we’re now asking for sensitive information, it will prove that we’re the account holder. 

The timestamp tells the server when the request was sent. Because networks can be unreliable or face downtime, the server might receive our request much later than intended. If too much time has passed, it will reject the request. You can specify how long you want to wait with the recvWindow parameter, which defaults to 5000 milliseconds.

Postman handles the generation of both of these fields for us. Click send, and you’ll get a response. Under balances, you should see six assets – BNB, BTC, BUSD, ETH, LTC, and TRX. The balance will be split across free and locked. We haven’t locked any up yet, so your assets should all be free.

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:

GET /api/v3/ticker/24hr

As you might guess, this will give us information about asset prices from the past twenty-four hours. Find it in Market > 24hr Ticker Price Change Statistics. The default pair we’re greeted with as the symbol variable is BTCUSDT

You can send this straight away to see a breakdown of price 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 that an asset is trading at:

GET /api/v3/price

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:

GET api/v3/depth

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.



Keep scrolling, and you’ll see the asks. They’re functionally similar to bids, except they represent orders to sell BTC for USDT. 


Place a test order

Now we’re going to post a test order.

POST api/v3/order/test

Even though we’re just using testnet funds, this request won’t actually place an order. It can come in useful for testing orders before actually submitting them. Find it under Trade > Test New Order (TRADE).



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.

Okay! Let’s create a test order now. We’re going to go with the automatically-generated values: a limit order to sell 0.1 BTC for USDT at $9000. Hit Send. If this was successful, then we’ll simply get {} as a response. 

 

Place a real order

Time to place a real fake order. 

POST /api/v3/order

Navigate to Trade > New Order. You’re familiar with test orders by now, so the parameters here will come as no surprise. Let’s leave all the values as they are, but since we’re permabulls, we’ll change the price that we’re selling at to $40,000. Tweak the price value to reflect this. Then, hit Send.

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.

GET /api/v3/openOrders

You’ll find this in Trade > Current Open Orders (USER_DATA). BTCUSDT is selected by default. If you hit Send, you’ll get all of your open BTCUSDT orders (so far, you should only see the one we set previously). You can choose not to specify a symbol, which will return all of your open orders instead.

GET /api/v3/allOrders

Trade > All Orders (USER_DATA) gives you an overview of all orders – not just open ones. Here, you must provide a symbol. orderId, startTime, endTime, and limit are optional parameters that can help you refine your search. We’ll leave them out here, so uncheck them. Hit Send, and you’ll see the same response as before. If you had any closed or canceled orders, you’d see them here too. 


Lastly, we can query specific orders with:

GET /api/v3/order

Get this under Trade > Query Order (USER_DATA). You’ll need to provide either the orderId or the origClientOrderId (the optional tag “newClientOrderId” you can add to orders). Uncheck orderId. For origClientOrderId, we’re going to provide the default tag from earlier – ”my_order_id_1”. Fill in the field and hit Send to get the response.


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:

DELETE /api/v3/order

Under Trade > Cancel Order is a request that will allow us to single out orders for cancelation. 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’ll see that it’s indeed canceled. To confirm this, use the GET /api/v3/openOrders endpoint again (giving you an empty list) or GET /api/v3/order with the origClientOrderId.


Place an order that fills instantly

Our previous order wasn’t filled because it was a limit order that would only trigger when the BTC price hit $40,000. With a market order, we’re basically saying “buy/sell at whatever price the asset is currently trading at.” This will fill instantly.

For that, let’s head back to Trade > New Order. We’re going to demonstrate the response type (newOrderRespType), which is a parameter we can tweak depending on the response we want to get from the server. There are three options here: ACK, RESULT, or FULL – you can see examples of each response here. We’re going to go with ACK, which will give us a simple acknowledgment that the order was received.

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:



You can verify that the order was filled with the /api/v3/allOrders endpoint.


Checking your trades

Let’s lastly look at the endpoint for checking your trades:

GET /api/v3/myTrades

This is located under Trade > Account Trade List (USER_DATA). It allows you to check each trade for a particular symbol. If you want to see all of your trades for the default symbol (BTCUSDT), simply uncheck startTime, endTime and fromId. The response will return up to 500 trades – simply tweak the limit if you want to see more.


Debugging with Postman

In Postman, it’s possible to further reveal the raw HTTP request and response.



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



Closing thoughts

The purpose of this guide was to gently introduce you to the Binance API without writing a single line of code. If you’ve followed along, you should now have an idea of how we can request and submit information.

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

Questions in the meantime? Head over to our growing Binance Developer Community forum, or take a look at the documentation.