I am trading BTC/USDT through binance api with ccxt library.
The error happens when I am trying to close my current position in futures account.
I fetch exact amount of BTC i'm trading from my position.(ex. 0.011BTC) and when i try to make an order to sell that amount of BTC to close my position, error message comes out saying Margin is insufficient. which means i am trying to sell more BTC than i have in my position.
BUT the amount of BTC i am trying to sell is just fetched 0.1 seconds ago, and it is not changing. so i have no idea what is going wrong.
and the problem is this error DO NOT come out everytime. same code sometimes works, and sometimes doesn't work.
I hope anyone have some idea how to fix this situation.
below is my code.
exchange = ccxt.binance({
'apiKey': my_api_key,
'secret': my_secret_key,
'enableRateLimit': True,
'options':{
'defaultType':'future',
'adjustForTimeDifference': True
}})
positions = exchange.fapiPrivateGetPositionRisk()
for position in positions:
# Check if position size is not zero
if float(position['positionAmt']) != 0:
# Determine the side of the order based on the position direction
if float(position['positionAmt']) > 0:
side = 'SELL'
else:
side = 'BUY'
# Create a market order to close the position
order = exchange.create_order(
symbol=position['symbol'],
type='MARKET',
side=side,
amount =abs(float(position['positionAmt'])),
params={'reduceOnly': True}
)
I get this error message
binance {"code":-2019,"msg":"Margin is insufficient."}
I have tried to fetch my position's BTC amount from other ccxt functions.
new code is below
balance = exchange.fetch_balance()
positions = balance['info']['positions']
for position in positions:
if position['symbol'] == "BTCUSDT":
amount = position['initialMargin']
above code also returns same error message,
binance {"code":-2019,"msg":"Margin is insufficient."}
still having problem to close my position.
help please.