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
set to future
indicates that we are querying the balance of the futures (contract) account. If you want to query the spot account, set it to spot
. Those who have read the previous chapter should know this. Then, adding the indices ['total']
and ['USDT']
indicates querying the USDT balance; for other currencies, just change the index accordingly.
2. Query Position#
After opening a position, I checked the returned data:
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 in it, and several important ones that we need are:
contracts
: Number of contractscontractSize
: Size of each contract (should be related to the leverage)unrealizedPnl
: Floating profit and lossleverage
: Leverage sizecollateral
: Marginnotional
: Position size (margin plus floating profit and loss)markPrice
: Market priceentryPrice
: Entry priceside
: Direction (long for buy, short for sell)
Use position[0]["key"]
to retrieve these values, where key is the name of the data key you want to retrieve, and it should be 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 as the opening position to close it (you can also open a different amount, such as closing half).
For example, 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})
After that, if I want to close the position, I need to know the amount bought in the last opening, 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 get the amount from the last opening, 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, you can set reduceOnly
to True
to prevent the amount from being too small (<5) to trade successfully.