banner
stmoonar

stmoonar

无心而为
github
telegram
email
zhihu
x

Binance API Usage (IV. Position Status Retrieval and Closing Positions)

Previously, we introduced how to trade using the Binance API. This chapter will cover how to obtain the current position status for further closing operations. If you haven't registered on the Binance exchange yet, feel free to use my referral link for fee discounts: https://accounts.binance.com/register?ref=DPVSZVI3

After a successful trade, we would like to retrieve and parse the information about the current position. Next, I will briefly introduce how to call these interfaces in ccxt. If you are not familiar with ccxt, you can refer back to the second article.

1. Query Balance#

balance = exchange.fetch_balance({'type': 'future'})['total']['USDT']

Here, the function fetch_balance is used, passing a dictionary as a parameter. The type is set to future, indicating that we are querying the balance of the futures (contract) account. If you want to query the spot account, set it to spot, which should be known to those who have read the previous chapter. Then, by adding the indices ['total'] and ['USDT'], we are querying the USDT balance; for other currencies, just change the index accordingly.

2. Query Position#

After opening a position, I checked the returned data for the position:

position = exchange.fetch_positions([COIN])

The parameter is a list of the currencies for which you want to query the position, such as [BTC/USDT, ETH/USDT]. Printing the returned result shows that it returns a list of dictionaries:

[
    {
        'info': 
        {
            'symbol': 'JUPUSDT', 
            'positionAmt': '6', 
            'entryPrice': '0.9947', 
            'breakEvenPrice': '0.99519735', 
            'markPrice': '0.99363270', 
            'unRealizedProfit': '-0.00640380', 
            'liquidationPrice': '0', 
            'leverage': '1', 
            'maxNotionalValue': '8000000.0', 
            'marginType': 'isolated', 
            'isolatedMargin': '5.96820000', 
            'isAutoAddMargin': 'false', 
            'positionSide': 'BOTH', 
            'notional': '5.96179620', 
            'isolatedWallet': '5.97460380', 
            'updateTime': '1713106952248', 
            'isolated': True, 'adlQuantile': '2'
        }, 
        'id': None, 
        'symbol': 'JUP/USDT:USDT', 
        'contracts': 6.0, 
        'contractSize': 1.0, 
        'unrealizedPnl': -0.0064038, 
        'leverage': 1.0, 
        'liquidationPrice': None, 
        'collateral': 5.9682, 
        'notional': 5.9617962, 
        'markPrice': 0.9936327, 
        'entryPrice': 0.9947, 
        'timestamp': 1713106952248, 
        'initialMargin': 5.9617962, 
        'initialMarginPercentage': 1.0, 
        'maintenanceMargin': 0.089426943, 
        'maintenanceMarginPercentage': 0.015, 
        'marginRatio': 0.015, 
        'datetime': '2024-04-14T15: 02: 32.248Z', 
        'marginMode': 'isolated', 
        'marginType': 'isolated', 
        'side': 'long', 
        'hedged': False, 
        'percentage': -0.1, 
        'stopLossPrice': None, 
        'takeProfitPrice': None
    }
]

There are many keys inside, and several important ones that we need are:

  • contracts: Number of contracts
  • contractSize: Size of each contract (should be related to the leverage)
  • unrealizedPnl: Floating profit and loss
  • leverage: Leverage size
  • collateral: Margin
  • notional: Position size (margin plus floating profit and loss)
  • markPrice: Market price
  • entryPrice: Entry price
  • side: Direction (long or short)

Use position[0]["key"] to retrieve these values, where the key is the name of the data you want to retrieve, enclosed in double quotes, such as "side".

3. Closing Position#

The Binance API documentation does not explicitly provide an interface for closing positions, but closing a position is essentially equivalent to opening a position in the opposite direction of the current position. For example, if you go long (buy) a certain amount of COIN, closing the position means selling the corresponding amount of that COIN. Therefore, you only need to open a position in the opposite direction with the same amount to close it (you can also open a different amount, such as closing half).

For instance, I first open a long position at market price:

exchange.set_leverage(5, "BTC/USDT")  # Set leverage
exchange.create_market_order("BTC/USDT", "buy", 6, params={'reduceOnly': False})

Then, if I want to close the position, I need to know the amount I bought in the last trade, which requires using the position query interface mentioned above:

position = exchange.fetch_positions(["BTC/USDT"])
last_amount = position[0]['contracts'] * position[0]['contractSize']

By multiplying the number of contracts by the size of each contract, I can obtain the amount from the last trade, and then open a position in the opposite direction to close it:

exchange.create_market_order("BTC/USDT", "sell", last_amount, params={'reduceOnly': True})

You can also close half by setting amount to 0.5*last_amount. When closing a position, you can set reduceOnly to True to prevent the amount from being too small (<5), which would result in a failed trade.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.