This article currently does not support your language. Auto-translator is recommended for English.

Binance API: Spot Trading With Postman

2023-04-20

Main Takeaways

  • APIs are pieces of code that allow applications to share information and can be used to enhance cryptocurrency trading strategies.

  • Postman is an API platform that simplifies the process of building and using APIs.

  • Learn more about using Postman for spot trading in the Binance API ecosystem.

Binance API Series Pt. I – Spot Trading with Postman

Introduction

Understanding and using an API for cryptocurrency trading can open up a world of possibilities for 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.

In this article, we’ll use Postman, a simplified API platform, 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 current purposes. This simulation feature will give us some funds with no real-world value to play around with. They function the same as real coins and tokens, so once you’re comfortable with the API, you can start using it to trade real funds.

  1. Start by heading over to the Spot Test Network.

  2. To get access, log in with a GitHub account. You’ll need to 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. If you don’t you’ll need to start the key creation process again. We recommend storing them on your machine’s notes app for easy copy-pasting later.

Note: labeling your keys is worth doing when using the real exchange 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! You can create an account to log in, but it isn’t necessary. If you want to skip this step, simply 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.

First, we want to create our environment. This step is just a way to add variables to the requests we will work with. 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. You can 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 your extracted folder (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. Ensure you have the correct one because our keys won’t work with the other.

Almost there. Click on Binance Spot Testnet API to see the variables below. Edit the two parameters outlined in red by pasting the keys you saved earlier. Click update and exit 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 will import the collection – this is an extensive assortment of requests that do the heavy lifting for us when 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 must select the Binance Spot API.postman_collection.json file.

  6. You should now see a confirmation screen identifying 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 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 can make many different requests. 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 information about your account balance, asset prices, etc.

  • POST: We’ll generally use the POST method to create information on a server. This method is needed for things like placing orders, requesting withdrawals, etc.

  • DELETE: The DELETE method requests 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 /api/v3/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 Postman makes it easy to see and modify requests where we include several parameters.

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 that was 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. This box contains information on the exchange, the pairs you can trade, and their minimum/maximum amounts.

It looks like a lot of information, but the format makes it 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 /api/v3/account

You can find this one under Trade > Account Information. Click on it to see a layout similar 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 assets. We haven’t locked any up yet, so your assets should all be free.

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. You can find it in Market > 24hr Ticker Price Change Statistics. The default pair we’re greeted with as the symbol variable is BTC/USDT. 

You can send this straight away to see a breakdown of price information. You can also change the symbol (to BNB/USDT, LTC/USDT, etc.) or 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

The order book depth – also referred to as the depth of market (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 receive a response that tells us about the bids and asks for BTC/USDT. 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 BTC/USDT, the upper number is the price that someone is willing to pay for your BTC. Below is the amount they’re willing to buy. Therefore, this says 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 if you’re looking for a bang for your buck. Still, if you’re trying to sell 3 BTC, for example, you’ll only be able to sell 0.999 BTC for the best price. You’ll need to take the subsequent (cheaper) offers until 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 be helpful 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 BTC/USDT 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 canceled.

    • 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 canceled immediately.

    • 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 – the quantity of the asset you want to buy or sell.

  • price – the price at which you want to sell. For the BTC/USDT 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 will proceed with the automatically-generated values: a limit order to sell 0.1 BTC for USDT at $9000. Hit Send. If this is successful, we’ll get {} as a response. 

Place a real order

Time to place a real order. 

POST /api/v3/order

Navigate to Trade > New Order. You’re familiar with test orders by now, so the parameters here will be no surprise. Let’s leave all the values as they are but change the price we’re selling to 40,000 USD. 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 recheck it later? We have a few requests at our disposal.

GET /api/v3/openOrders

You’ll find this in Trade > Current Open Orders (USER_DATA). BTC/USDT is selected by default. If you hit Send, you’ll get all of your open BTC/USDT orders (so far, you should only see the one we set previously). You can also choose not to specify a symbol, which will return all 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 the following:

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 will 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 USD target is too optimistic, so we want to cancel it. In that case, we’d use the following:

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 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 USD. With a market order, we essentially say: “Buy or 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 will demonstrate the response type (newOrderRespType), which is a parameter we can tweak depending on the response we want from the server. There are three options here: ACK, RESULT, or FULL – you can see examples of each response here. We will go with ACK, which gives 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 your trades for the default symbol (BTC/USDT), 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 reveal the raw HTTP request and response further.

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

Get Started With Binance API

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.

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

Further Reading

246,366,029 users chose us. Find out why today.
Register Now