Python-binance stop loss order

204 viewsJuly 17, 2021pythonbinance ccxt python python-asyncio
0
Python-binance stop loss order
Saswata383.07K July 17, 2021 0 Comments

I am attempting to create a

LONG TRADE
that will contain a
BUY ORDER
and a
STOP-LOSS
using
Python asyncio
,
ccxt API
(which is calling the
Binance API
for the Binance Crypto Exchange).

First I create the BUY ORDER. Afterwards, I am waiting until the order is filled. AFTER it is filled, I am attempting to create a STOP-LOSS order to go with the LONG that was created (Reason: I do not want to lose a lot of money if the trade moves against me).

According to the log, the BUY ORDER is being created OK. I am getting insufficient funds on the STOP-LIMIT order.

I do not understand why I would be getting insufficient funds on a STOP-LOSS order when the BUY order went through just fine (it even has the status of FILLED).

If I BUY .0015 BTC for

Python-binance stop loss order
8875 (again, to preserve the funds in the case the trade moves against me)

Why is this not working? Why can I not create a STOP-LOSS for my trade?

ETA: Saw this in a different thread:

TAKE_PROFIT is the opposite of STOP_LOSS. One executes on the downward, the other executes on the upward.

QUESTION: How can I structure the API so that the TAKE_PROFIT and STOP_LOSS can be set for an order?

async def execute_long_trade(self, trade: LongTrade): try: buy_price = trade.start_price sell_price = trade.exit_price symbol = trade.exchange_symbol amount = trade.amount stop_loss = trade.stop_loss order = self.exchange.ccxt_create_buy_order(symbol, amount, buy_price, 0 )

[ snip ]

logging.info(f'Opened long trade: {amount} of {symbol}. Target buy {stop_loss}, sell price {sell_price}') await self._wait_order_complete(order["data"][0]["id"], symbol) # set up a stop loss order order = self.exchange.ccxt_create_sell_order(symbol, amount, sell_price, stop_loss ) logging.info(f'Completed long trade: {amount} of {symbol}. Bought at {buy_price} and sold at {sell_price}') except ExchangeError as e: raise except Exception as e: print (" unexpected exception ") exit()

[ snip ]

CALLING BINANCE (for the BUY part which works fine) :

def ccxt_create_buy_order( self, symbol: str, amount: float, price: float, stop_price: float ): try: results = {} if ( stop_price > 0 ): params = { 'stopPrice': stop_price - 10 } output = self.ccxt_binance.createOrder(symbol, 'STOP_LOSS_LIMIT', amount=amount, side="buy", price = stop_price, params=params) else: output = self.ccxt_binance.create_order(symbol=symbol, type="limit", side="buy", amount=amount, price=price ) [ ... snip ...] return (results) except ccxt.InsufficientFunds as e: print ("insufficient funds) return except Exception as e: print (" unexpected error ") exit()

CALLING BINANCE (for the SELL PART getting insufficent funds error):

def ccxt_create_sell_order( self, symbol: str, amount: float, price: float, stop_price: float ): try: results = {} if ( stop_price > 0 ): params = { 'stopPrice': stop_price + 10 } output = self.ccxt_binance.createOrder(symbol, 'STOP_LOSS_LIMIT', amount=amount, side="sell", price = stop_price, params=params) print(output) else: output = self.ccxt_binance.create_order(symbol=symbol, type="limit", side="sell",amount=amount ) [ ... snip ...] return (results) except ccxt.InsufficientFunds as e: print ("insufficient funds) return except Exception as e: print (" unexpected error ") exit()

LOG FOR THE BUY PART

2020-06-10 01:01:08 - DEBUG - 16537 - ccxt.base.exchange - DEBUG MESSAGE : POST https://api.binance.com/api/v3/order, Request: {'X-MBX-APIKEY': 'JXXXXXXXX-XXXXXX', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate'} timestamp=1591750868935&recvWindow=5000&symbol=BTCUSDT&type=LIMIT&side=BUY&quantity=0.0015&newOrderRespType=RESULT&price=9777.99&timeInForce=GTC&signature=XXXXXXXXXXXX-XXXXXXXXXXXXXX 2020-06-10 01:01:09 - DEBUG - 16537 - urllib3.connectionpool - DEBUG MESSAGE : https://api.binance.com:443 "POST /api/v3/order HTTP/1.1" 200 None 2020-06-10 01:01:09 - DEBUG - 16537 - ccxt.base.exchange - DEBUG MESSAGE : POST https://api.binance.com/api/v3/order, Response: 200 {'Content-Type': 'application/json;charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Date': 'Wed, 10 Jun 2020 01:01:09 GMT', 'Server': 'nginx', 'X-MBX-UUID': 'XXXXXXXXX-XXXXx', 'X-MBX-USED-WEIGHT': '5', 'X-MBX-USED-WEIGHT-1M': '5', 'X-MBX-ORDER-COUNT-10S': '1', 'X-MBX-ORDER-COUNT-1D': '10', 'Content-Encoding': 'gzip', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', 'X-Cache': 'Miss from cloudfront', 'Via': '1.1 e9ccfc64a258a54713XXXXb7b.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'ATL56-C3', 'X-Amz-Cf-Id': 'gXXXXXXXXXXX-XXX9TzUqeLltao4UiQ=='} {"symbol":"BTCUSDT","orderId":2434736796,"orderListId":-1,"clientOrderId":"93XXXXXXXECejmtfb","transactTime":1591750869025,"price":"9777.99000000","origQty":"0.00150000","executedQty":"0.00150000","cummulativeQuoteQty":"14.66698500","status":"FILLED","timeInForce":"GTC","type":"LIMIT","side":"BUY"}

LOG FOR THE SELL PART:

2020-06-10 01:01:24 - DEBUG - 16537 - ccxt.base.exchange - DEBUG MESSAGE : POST https://api.binance.com/api/v3/order, Request: {'X-MBX-APIKEY': 'XXXXXXXXX-XXX', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate'} timestamp=1591750884617&recvWindow=5000&symbol=BTCUSDT&type=STOP_LOSS_LIMIT&side=SELL&quantity=0.0015&newOrderRespType=RESULT&price=9670.21&timeInForce=GTC&stopPrice=9680.21&signature=XXXXXXX-XXXXXXX-XXXXXXXXXXX-XXXXXXXXXXXXX 2020-06-10 01:01:24 - DEBUG - 16537 - urllib3.connectionpool - DEBUG MESSAGE : https://api.binance.com:443 "POST /api/v3/order HTTP/1.1" 400 None 2020-06-10 01:01:24 - DEBUG - 16537 - ccxt.base.exchange - DEBUG MESSAGE : POST https://api.binance.com/api/v3/order, Response: 400 {'Content-Type': 'application/json;charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Date': 'Wed, 10 Jun 2020 01:01:24 GMT', 'Server': 'nginx', 'X-MBX-UUID': 'XXXXXX-023741e9e18b', 'X-MBX-USED-WEIGHT': '7', 'X-MBX-USED-WEIGHT-1M': '7', 'X-MBX-ORDER-COUNT-10S': '1', 'X-MBX-ORDER-COUNT-1D': '11', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 e9XXXXXXXX-09e5b7b.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'ATL56-C3', 'X-Amz-Cf-Id': 'XXXXXXX'} {"code":-2010,"msg":"Account has insufficient balance for requested action."}

0 Answers

  • Active
  • Voted
  • Newest
  • Oldest
Register or Login