Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Tuesday, July 26, 2022

Setup Http client for API using OkHttp in Java

In this tutorial, we will learn how to use OkHttp for HTTP requests while consuming APIs.

OkHttp is an HTTP client which will do HTTP efficiently by loading faster and saving bandwidth. Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

Setup the OkHttp dependency:

If we are using the external Jar file, download the jar from okhttp maven.

Follow this tutorial for setting up the Jar file How to add external jar or library on IntelliJ IDEA project

Setup in maven project:

Add in pom.xml

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.10.0</version>
</dependency>

Setup in Gradle project:

Add in build.gradle under "dependencies"

dependencies {
//other dependencies
 
compile("com.squareup.okhttp3:okhttp:4.10.0")
}

Implementation:

Let's create a sample java class HttpClient.java and set up the OkHttp3 client.

import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response

class HttpClient {

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8")


    public static Response doGetRequest(url, String apiKey = '') {
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
        Request request = setHeadersConfig(requestBuilder, apiKey).build();
        Response response = getClient().newCall(request).execute()
        return response.body().string();
    }

    public static String doPostRequest(String json, String url, String apiKey = '') {
        RequestBody body = RequestBody.create(json, JSON)
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body)
        Request request = setHeadersConfig(requestBuilder, apiKey).build();
        Response response = getClient().newCall(request).execute()
        return response.body().string()
    }

    public static String doDeleteRequest(String json, String url, String apiKey = '') {
        RequestBody body = RequestBody.create(json, JSON)
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .delete(body)
        Request request = setHeadersConfig(requestBuilder, apiKey).build();
        Response response = getClient().newCall(request).execute()
        return response.body().string()
    }

    private static Request.Builder setHeadersConfig(Request.Builder requestBuilder, String apiKey) {
        requestBuilder.header("Content-Type", "application/json")
                .header("X-MBX-APIKEY", apiKey)
        return requestBuilder
    }

    private static OkHttpClient getClient() {
        return new OkHttpClient()
    }
}

This class contains the setup for the post, get and delete request.

Method setHeadersConfig is for setting up the headers we used sample X-MBX-APIKEY header configuration to set the API key. You can use your desired header configuration there.

We can pass the post body by formatting the data in JSON string.

Please don't forget to handle the Exception.

Getting Status Code:

We can get the status code from the Response response object in the above example as below:

 Response response = getClient().newCall(request).execute()
        int statusCode = response.code()

Using it from Java classes:

All the methods are static so we can simply use it from other java classes as below:

HttpClient.doPostRequest(json, url, apiKey)
Share:

Wednesday, July 6, 2022

Binance API code -1013 msg - Filter failure: PRICE_FILTER

While implementing the Binance API, we might get the following error.

{
"code":-1013,
"msg":"Filter failure: PRICE_FILTER"
}

This might be due to the mismatch of the given Filter for the price by Binance. As from the Binance Spot Api documentation, the condition that needs to be satisfied is

price >= minPrice
price <= maxPrice
price % tickSize == 0

We can get the Filter value for PRICE_FILTER as below.

For BTC USDT:

https://api.binance.us/api/v3/exchangeInfo?symbol=BTCUSDT

OR

https://api.binance.com/api/v3/exchangeInfo?symbol=BTCUSDT

The output of the above endpoint is:

{
   "timezone":"UTC",
   "serverTime":1657086978303,
   "rateLimits":[
      {
         "rateLimitType":"REQUEST_WEIGHT",
         "interval":"MINUTE",
         "intervalNum":1,
         "limit":1200
      },
      {
         "rateLimitType":"ORDERS",
         "interval":"SECOND",
         "intervalNum":10,
         "limit":100
      },
      {
         "rateLimitType":"ORDERS",
         "interval":"DAY",
         "intervalNum":1,
         "limit":200000
      },
      {
         "rateLimitType":"RAW_REQUESTS",
         "interval":"MINUTE",
         "intervalNum":5,
         "limit":6100
      }
   ],
   "exchangeFilters":[
      
   ],
   "symbols":[
      {
         "symbol":"BTCUSDT",
         "status":"TRADING",
         "baseAsset":"BTC",
         "baseAssetPrecision":8,
         "quoteAsset":"USDT",
         "quotePrecision":8,
         "quoteAssetPrecision":8,
         "baseCommissionPrecision":8,
         "quoteCommissionPrecision":8,
         "orderTypes":[
            "LIMIT",
            "LIMIT_MAKER",
            "MARKET",
            "STOP_LOSS_LIMIT",
            "TAKE_PROFIT_LIMIT"
         ],
         "icebergAllowed":true,
         "ocoAllowed":true,
         "quoteOrderQtyMarketAllowed":true,
         "allowTrailingStop":false,
         "cancelReplaceAllowed":false,
         "isSpotTradingAllowed":true,
         "isMarginTradingAllowed":false,
         "filters":[
            {
               "filterType":"PRICE_FILTER",
               "minPrice":"0.01000000",
               "maxPrice":"100000.00000000",
               "tickSize":"0.01000000"
            },
            {
               "filterType":"PERCENT_PRICE",
               "multiplierUp":"5",
               "multiplierDown":"0.2",
               "avgPriceMins":5
            },
            {
               "filterType":"LOT_SIZE",
               "minQty":"0.00000100",
               "maxQty":"9000.00000000",
               "stepSize":"0.00000100"
            },
            {
               "filterType":"MIN_NOTIONAL",
               "minNotional":"10.00000000",
               "applyToMarket":true,
               "avgPriceMins":5
            },
            {
               "filterType":"ICEBERG_PARTS",
               "limit":10
            },
            {
               "filterType":"MARKET_LOT_SIZE",
               "minQty":"0.00000000",
               "maxQty":"29.33387056",
               "stepSize":"0.00000000"
            },
            {
               "filterType":"MAX_NUM_ORDERS",
               "maxNumOrders":200
            },
            {
               "filterType":"MAX_NUM_ALGO_ORDERS",
               "maxNumAlgoOrders":5
            }
         ],
         "permissions":[
            "SPOT"
         ]
      }
   ]
}

For PRICE_FILTER:

{
               "filterType":"PRICE_FILTER",
               "minPrice":"0.01000000",
               "maxPrice":"100000.00000000",
               "tickSize":"0.01000000"
            },

Lets look into the first condition; price >= minPrice price <= maxPrice

We need to have a price that must be greater or equal to min price and less than or equal to the max price.

Let's look into the second condition: price % tickSize == 0; For this, we might get the precision issue if we don't parse the price. Here, tickSize is in the 2 decimal place so we need to parse the price in 2 decimal places to validate the filter. This will help resolve the issue.

Share:

Tuesday, July 5, 2022

Binance Api code-1013 msg:Filter failure: MIN_NOTIONAL

This is a quick tutorial on how we can resolve the Filter failure: MIN_NOTIONAL

While using Binance API, when placing the order and calling API we might get the following error.

{
"code":-1013,
"msg":"Filter failure: MIN_NOTIONAL"
}

As described on binance spot API documentation, The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity

Now let's look into what is the required values for MIN_NOTIONAL. We can get it from the exchange info endpoint as below

For BTC USDT

https://api.binance.us/api/v3/exchangeInfo?symbol=BTCUSDT

The Output for the above endpoint is:

{
   "timezone":"UTC",
   "serverTime":1657007585516,
   "rateLimits":[
      {
         "rateLimitType":"REQUEST_WEIGHT",
         "interval":"MINUTE",
         "intervalNum":1,
         "limit":1200
      },
      {
         "rateLimitType":"ORDERS",
         "interval":"SECOND",
         "intervalNum":10,
         "limit":100
      },
      {
         "rateLimitType":"ORDERS",
         "interval":"DAY",
         "intervalNum":1,
         "limit":200000
      },
      {
         "rateLimitType":"RAW_REQUESTS",
         "interval":"MINUTE",
         "intervalNum":5,
         "limit":6100
      }
   ],
   "exchangeFilters":[
      
   ],
   "symbols":[
      {
         "symbol":"BTCUSDT",
         "status":"TRADING",
         "baseAsset":"BTC",
         "baseAssetPrecision":8,
         "quoteAsset":"USDT",
         "quotePrecision":8,
         "quoteAssetPrecision":8,
         "baseCommissionPrecision":8,
         "quoteCommissionPrecision":8,
         "orderTypes":[
            "LIMIT",
            "LIMIT_MAKER",
            "MARKET",
            "STOP_LOSS_LIMIT",
            "TAKE_PROFIT_LIMIT"
         ],
         "icebergAllowed":true,
         "ocoAllowed":true,
         "quoteOrderQtyMarketAllowed":true,
         "allowTrailingStop":false,
         "cancelReplaceAllowed":false,
         "isSpotTradingAllowed":true,
         "isMarginTradingAllowed":false,
         "filters":[
            {
               "filterType":"PRICE_FILTER",
               "minPrice":"0.01000000",
               "maxPrice":"100000.00000000",
               "tickSize":"0.01000000"
            },
            {
               "filterType":"PERCENT_PRICE",
               "multiplierUp":"5",
               "multiplierDown":"0.2",
               "avgPriceMins":5
            },
            {
               "filterType":"LOT_SIZE",
               "minQty":"0.00000100",
               "maxQty":"9000.00000000",
               "stepSize":"0.00000100"
            },
            {
               "filterType":"MIN_NOTIONAL",
               "minNotional":"10.00000000",
               "applyToMarket":true,
               "avgPriceMins":5
            },
            {
               "filterType":"ICEBERG_PARTS",
               "limit":10
            },
            {
               "filterType":"MARKET_LOT_SIZE",
               "minQty":"0.00000000",
               "maxQty":"29.33387056",
               "stepSize":"0.00000000"
            },
            {
               "filterType":"MAX_NUM_ORDERS",
               "maxNumOrders":200
            },
            {
               "filterType":"MAX_NUM_ALGO_ORDERS",
               "maxNumAlgoOrders":5
            }
         ],
         "permissions":[
            "SPOT"
         ]
      }
   ]
}

For MIN_NOTIONAL:

{
               "filterType":"MIN_NOTIONAL",
               "minNotional":"10.00000000",
               "applyToMarket":true,
               "avgPriceMins":5
            },

So this defines that the limit order placed must be minimum of $10 i.e price * quantity = total here, the total must be at least 10. If this doesn't satisfy then we will get the mentioned error. So the condition must be satisfied while calling the API.

Share: