# Private API

The **private API** is a class to send API requests that requires authorization, e.g. get my balance in Binance spot wallet, create a buy order of BTCUSDT, cancel an order, and etc.

It is initialized prior to your code as a variable named `privateAPI`. When initializing, it automatically gathers the API keys that you have registered.

{% hint style="info" %}
The private API class can only be used in **terminal**. In other words, it does not work in analytics.
{% endhint %}

{% hint style="warning" %}
If you didn't register the API key of some exchanges, then the functions which send  API requests to them will throw exceptions.
{% endhint %}

```python
...

import PrivateAPI

# `privateAPI` object is automatically initialized
# before running your code.
privateAPI = PrivateAPI()

# your python code is placed here
# In your code, you can send private API requests like below:
## privateAPI.buy('binance', 'BTCUSDT', 0.02, 28000)
```

***

## Common Functions

The **common functions** are the methods of the private API, available for (almost) any exchanges we support. By using these functions, you can easily switch the exchanges you want to send API request to.

Every common function has its first argument as an **exchange**. It specifies which exchange should the request be sent to. For example, you can get the balance in your Binance spot wallet by `privateAPI.get_balance('binance')`, while `privateAPI.get_balance('binance_um_futures')` returns the balance in your Binance USDⓈ-M futures wallet in a same response structure.

For now, the available exchanges are,

* `binance` : Binance Spot
* `binance_um_futures` : Binance USDⓈ-M Futures
* `binance_cm_futures` : Binance COIN-M Futures

### 1. Get Balance

{% code overflow="wrap" %}

```python
privateAPI.get_balance(exchange: str) -> dict
```

{% endcode %}

It is a function to get the asset information in the exchange's wallet.&#x20;

#### Arguments

* `exchange` : (string) The name of the exchange.

#### Returns

It returns the dictionary object with its **key** as a name of the **asset** in string, and **value** as the **information** on the asset. The information has three key:

* `amount` : (float) Current actual amount of the asset. `unrealized_pnl` is not included.
* `available` : (float) The amount of the asset available for trading.
* `unrealized_pnl` : (float) The unrealized PnL(profit & loss) of the asset by the derivatives such as futures position. If the exchange is spot-only, then it is always 0.

Usually, `amount = available + (locked amount because of open orders, maintenance margin, etc.)` holds.

```python
# returning object example
{
    'BTC':{
        'amount':0.122503,
        'available':0.122503,
        'unrealized_pnl':0
    },
    'USDT':{
        'amount':160.32,
        'available':131.681,
        'unrealized_pnl':-3.1252
    }
}
```

***

### 2. Get Positions

{% code overflow="wrap" %}

```python
privateAPI.get_positions(exchange: str) -> dict
```

{% endcode %}

It is a function to get the position information in the exchange's account.

{% hint style="info" %}
This function merges all open positions by the **symbol**. For example, if you have both **0.1 BTCUSDT long** and **-0.2 BTCUSDT short** position, then this method will return **BTCUSDT short** position with the amount = **-0.1**.
{% endhint %}

{% hint style="warning" %}
Only the exchanges which have **futures** are available. c.f. `binance`(= Binance spot) **cannot** be the value of the exchange argument for this function.
{% endhint %}

#### Arguments

* `exchange` : (string) The name of the exchange.

#### Returns

It returns the dictionary object with its **key** as a name of the **symbol** in string, and **value** as the **information** on the position. The information has three key:

* `side` : (string) `'long'` for long, or `'short'` for short.
* `amount` : (float) The amount of the position currently holding. Positive for long, negative for short.
* `unrealized_pnl` : (float) The unrealized PnL of the position.

```python
# returning object example
{
    'BTCUSDT':{
        'side':'short',
        'amount':-0.1125,
        'unrealized_pnl':21.3225
    },
    'BTCUSDT_220930':{
        'side':'long',
        'amount':0.351,
        'unrealized_pnl':-1.7862
    }
}
```

***

### 3. Buy

{% code overflow="wrap" %}

```python
privateAPI.buy(exchange: str, symbol: str, amount: float, price: float = None, order_type: str = 'limit', reduce_only: bool = False) -> None
```

{% endcode %}

Create a buy/long order.

#### Arguments

* `exchange` : (string) The name of the exchange.
* `symbol` : (string) The name of the symbol.
* `amount` : (float) The amount of the order. It must be positive.
* `price` : (float) The price of the order to be trade. Default value is `None`. It should be `None` when the `order_type == 'market'`.
* `order_type` : (string) The type of the order. `'limit'` for limit order, `'market'` for market order. Default value is `'limit'`.
* `reduce_only` : (boolean) **Futures** **only** arguments. Enable reduce only option. If it's true, then the order works only to close the current position. Default value is `False`.

#### Returns

None

***

### 4. Sell

{% code overflow="wrap" %}

```python
privateAPI.sell(exchange: str, symbol: str, amount: float=None, price: float = None, order_type: str = 'limit', reduce_only: bool = False, **kwargs) -> None
```

{% endcode %}

Create a sell/short order.

#### Arguments

* `exchange` : (string) The name of the exchange.
* `symbol` : (string) The name of the symbol.
* `amount` : (float) The amount of the order. It must be positive.
* `price` : (float) The price of the order to be trade. Default value is `None`. It should be `None` when the `order_type == 'market'`.
* `order_type` : (string) The type of the order. `'limit'` for limit order, `'market'` for market order. Default value is `'limit'`.
* `reduce_only` : (boolean) **Futures** **only** arguments. Enable reduce only option. If it's true, then the order works only to close the current position. Default value is `False`.

#### Returns

None

***

### 5. Get Open Orders

{% code overflow="wrap" %}

```python
privateAPI.get_open_orders(exchange: str, **kwargs) -> list
```

{% endcode %}

Get the list of the open orders' symbol and order ID.

{% hint style="warning" %}
Some exchanges may require additional arguments.
{% endhint %}

#### Arguments

* `exchange` : (string) The name of the exchange.
* `**kwargs` : Additional arguments.
  * `symbol` : (string) The symbol of the orders. `binance`, `binance_um_futures`, and `binance_cm_futures` require symbol argument.&#x20;

#### Returns

It returns a **list** of the **order element**. The **order element** is a dictionary of `symbol` and `order_id`.

* `symbol` : (string) The symbol of the order.
* `order_id` : (string) The order ID of the order.

{% code overflow="wrap" %}

```python
# function example that requires additional `symbol` argument.
# Without symbol='BTCUSDT' in the argument, it would raise an exception.
orders = privateAPI.get_open_orders('binance', symbol='BTCUSDT')

# returning object example
[
    {
        'symbol':'BTCUSDT',
        'order_id':'123612397'
    },
    ...
]
```

{% endcode %}

***

### 6. Cancel an Order

{% code overflow="wrap" %}

```python
privateAPI.cancel_order(exchange: str, order_id, **kwargs) -> None
```

{% endcode %}

Cancel an open order by its order ID.

{% hint style="warning" %}
Some exchanges may require additional arguments.
{% endhint %}

#### Arguments

* `exchange` : (string) The name of the exchange.
* `order_id` : An ID of the order to cancel.
* `**kwargs` : Additional arguments.
  * `symbol` : (string) The symbol of the orders. `binance`, `binance_um_futures`, and `binance_cm_futures` require symbol argument.&#x20;

#### Returns

None

{% code overflow="wrap" %}

```python
# function example that requires additional `symbol` argument.
# Without symbol='ETHUSDT' in the argument, it would raise an exception.
privateAPI.cancel_order('binance', '12312722', symbol='ETHUSDT')
```

{% endcode %}

***

### 7. Cancel All Orders

{% code overflow="wrap" %}

```python
privateAPI.cancel_all_orders(exchange: str, **kwargs) -> None
```

{% endcode %}

Cancel all the open orders.

{% hint style="warning" %}
Some exchanges may require additional arguments.
{% endhint %}

#### Arguments

* `exchange` : (string) The name of the exchange.
* `**kwargs` : Additional arguments.
  * `symbol` : (string) The symbol of the orders. `binance`, `binance_um_futures`, and `binance_cm_futures` require symbol argument.&#x20;

#### Returns

None

{% code overflow="wrap" %}

```python
# function example that requires additional `symbol` argument.
# Without symbol='BTCUSD' in the argument, it would raise an exception.
privateAPI.cancel_all_orders('binance_cm_futures', symbol='BTCUSD')
```

{% endcode %}

***

### 8. Set Leverage

{% code overflow="wrap" %}

```python
privateAPI.set_leverage(exchange: str, leverage:int, **kwargs) -> None
```

{% endcode %}

Set leverage value.

{% hint style="warning" %}
Some exchanges may require additional arguments.
{% endhint %}

{% hint style="warning" %}
Only the exchanges which have **futures** are available. c.f. `binance`(= Binance spot) **cannot** be the value of the exchange argument for this function.
{% endhint %}

#### Arguments

* `exchange` : (string) The name of the exchange.
* `leverage` : The leverage value to set. It is usually a positive integer value.
* `**kwargs` : Additional arguments.
  * `symbol` : (string) The symbol of the orders. `binance_um_futures`, and `binance_cm_futures` require symbol argument.&#x20;

#### Returns

None

{% code overflow="wrap" %}

```python
# function example that requires additional `symbol` argument.
# Without symbol='BTCUSDT' in the argument, it would raise an exception.
privateAPI.set_leverage('binance_um_futures', 5, symbol='BTCUSDT')
```

{% endcode %}

***

### 9. Get API request result

{% code overflow="wrap" %}

```python
privateAPI._get(exchange: str, api_url:str, **kwargs) -> Any
```

{% endcode %}

This is a special function that can call any API requests that read/get the information.

{% hint style="info" %}
If you are about the get **public** API requests such as getting orderbook, getting exchange info, and etc, then user `publicAPI._get()`
{% endhint %}

#### Arguments

* `exchange` : (string) The name of the exchange.
* `api_url` : (string) Endpoint of the request, such as `'/api/v1/exchangeIfo'`.
* `**kwargs` : Additional arguments. They will be used as the parameters of the request.

#### Returns

None

{% code overflow="wrap" %}

```python
# This code will returns the leverage bracket information of 'BTCUSDT'.
# Link : https://binance-docs.github.io/apidocs/futures/en/#notional-and-leverage-brackets-user_data
result = privateAPI._get(
    exchange = 'binance_um_futures', 
    api_url = '/fapi/v1/leverageBracket',
    symbol='BTCUSDT'
)
```

{% endcode %}

***

## Exchange-Only Functions

While common functions make it easy to switch exchanges, there are API requests which are specialized for the specific exchanges. Or, you may want to handle detailed options or values that the common functions cannot cover. In that case, the exchange-only functions can help you with that.

Most of the exchange-only functions have `**kwargs` to support **all the parameters** that the API can have.

The returns are the object obtained by parsing the API response(Usually in JSON format). Therefore, the type of them are **dict**, **list** or **None**.

### Binance

[Binance](/library/python-library/private-api/binance.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.unblinked.com/library/python-library/private-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
