Hello,
I’m trying to cancel the take profit when the stop is triggered, or vice versa on binance futures testnet
It’s a websocket connection with the unicorn library.
The code cancels the take profit order successfully, but also throws an error.
There seem to be additional orders but I only created one stop_market and one take_profit_market
print('CCXT version:', ccxt.__version__)
pprint.pprint(orders)
def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
while True:
if binance_websocket_api_manager.is_manager_stopping():
exit(0)
oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
if oldest_stream_data_from_stream_buffer is False:
time.sleep(0.01)
else:
if oldest_stream_data_from_stream_buffer['o']['ot'] == 'STOP_MARKET':
exchange.cancel_order(orders[1]['id'], 'BCH/USDT')
print('TAKE PROFIT HAS BEEN CANCELLED')
binance_com_api_key = config.binance_com_api_key
binance_com_api_secret = config.binance_com_api_secret
binance_com_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com-futures-testnet",
throw_exception_if_unrepairable=True, output_default="dict")
binance_com_user_data_stream_id = binance_com_websocket_api_manager.create_stream('arr', '!userData',
api_key=binance_com_api_key,
api_secret=binance_com_api_secret, stream_label="dict", output="dict")
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_com_websocket_api_manager,))
worker_thread.start()
This is the printed order and the error:
CCXT version: 1.46.38
[{'amount': 1.0,
'average': None,
'clientOrderId': 'STOP',
'cost': 0.0,
'datetime': '2021-04-07T16:18:51.926Z',
'fee': None,
'fees': [],
'filled': 0.0,
'id': '471598386',
'info': {'avgPrice': '0',
'clientOrderId': 'STOP',
'closePosition': False,
'cumQuote': '0',
'executedQty': '0',
'orderId': '471598386',
'origQty': '1',
'origType': 'STOP_MARKET',
'positionSide': 'BOTH',
'price': '0',
'priceProtect': False,
'reduceOnly': False,
'side': 'BUY',
'status': 'NEW',
'stopPrice': '627.23',
'symbol': 'BCHUSDT',
'time': '1617812331926',
'timeInForce': 'GTC',
'type': 'STOP_MARKET',
'updateTime': '1617812331926',
'workingType': 'CONTRACT_PRICE'},
'lastTradeTimestamp': None,
'postOnly': False,
'price': 0.0,
'remaining': 1.0,
'side': 'buy',
'status': 'open',
'stopPrice': 627.23,
'symbol': 'BCH/USDT',
'timeInForce': 'GTC',
'timestamp': 1617812331926,
'trades': [],
'type': 'stop_market'},
{'amount': 1.0,
'average': None,
'clientOrderId': 'TP',
'cost': 0.0,
'datetime': '2021-04-07T16:18:52.619Z',
'fee': None,
'fees': [],
'filled': 0.0,
'id': '471598387',
'info': {'avgPrice': '0',
'clientOrderId': 'TP',
'closePosition': False,
'cumQuote': '0',
'executedQty': '0',
'orderId': '471598387',
'origQty': '1',
'origType': 'TAKE_PROFIT_MARKET',
'positionSide': 'BOTH',
'price': '0',
'priceProtect': False,
'reduceOnly': False,
'side': 'BUY',
'status': 'NEW',
'stopPrice': '625.97',
'symbol': 'BCHUSDT',
'time': '1617812332619',
'timeInForce': 'GTC',
'type': 'TAKE_PROFIT_MARKET',
'updateTime': '1617812332619',
'workingType': 'CONTRACT_PRICE'},
'lastTradeTimestamp': None,
'postOnly': False,
'price': 0.0,
'remaining': 1.0,
'side': 'buy',
'status': 'open',
'stopPrice': 625.97,
'symbol': 'BCH/USDT',
'timeInForce': 'GTC',
'timestamp': 1617812332619,
'trades': [],
'type': 'take_profit_market'}]
Request: DELETE https://testnet.binancefuture.com/fapi/v1/order?timestamp=1617812353328&recvWindow=5000&symbol=BCHUSDT&orderId=471598387&signature=b646abcd91f5f130d6d89db87beb39d8b619672726ce125d462ba44f4163d1e8 {'X-MBX-APIKEY': '1e0ff669e8f6973d5aa9e17133d1ea281649ec1cc8c9c6037be02ebd18b34d0e', 'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate'} None
Response: DELETE https://testnet.binancefuture.com/fapi/v1/order?timestamp=1617812353328&recvWindow=5000&symbol=BCHUSDT&orderId=471598387&signature=b646abcd91f5f130d6d89db87beb39d8b619672726ce125d462ba44f4163d1e8 200 {'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Date': 'Wed, 07 Apr 2021 16:19:13 GMT', 'Server': 'Bengine', 'Vary': 'Accept-Encoding', 'X-MBX-USED-WEIGHT-1M': '1', 'x-response-time': '3ms', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'origin-when-cross-origin', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'Content-Encoding': 'gzip', 'X-Cache': 'Miss from cloudfront', 'Via': '1.1 64c57433dbc269a88f86e72ae54bfe36.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'HAM50-C1', 'X-Amz-Cf-Id': '3lPL8YXbXxwDkH_95rlYTQmo1QqJImkUGb5SINyA6Yl_oRlFHivpdA=='} {"orderId":471598387,"symbol":"BCHUSDT","status":"CANCELED","clientOrderId":"TP","price":"0","avgPrice":"0.00000","origQty":"1","executedQty":"0","cumQty":"0","cumQuote":"0","timeInForce":"GTC","type":"TAKE_PROFIT_MARKET","reduceOnly":false,"closePosition":false,"side":"BUY","positionSide":"BOTH","stopPrice":"625.97","workingType":"CONTRACT_PRICE","priceProtect":false,"origType":"TAKE_PROFIT_MARKET","updateTime":1617812353459}
TAKE PROFIT HAS BEEN CANCELLED
Request: DELETE https://testnet.binancefuture.com/fapi/v1/order?timestamp=1617812353832&recvWindow=5000&symbol=BCHUSDT&orderId=471598387&signature=29a544d14f7c7ad19646a46532d03d510fbbe3988f9c0fa52d4fa42dd1239943 {'X-MBX-APIKEY': '1e0ff669e8f6973d5aa9e17133d1ea281649ec1cc8c9c6037be02ebd18b34d0e', 'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate'} None
Response: DELETE https://testnet.binancefuture.com/fapi/v1/order?timestamp=1617812353832&recvWindow=5000&symbol=BCHUSDT&orderId=471598387&signature=29a544d14f7c7ad19646a46532d03d510fbbe3988f9c0fa52d4fa42dd1239943 400 {'Content-Type': 'application/json', 'Content-Length': '42', 'Connection': 'keep-alive', 'Date': 'Wed, 07 Apr 2021 16:19:14 GMT', 'Server': 'Bengine', 'X-MBX-USED-WEIGHT-1M': '2', 'x-response-time': '3ms', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'origin-when-cross-origin', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 64c57433dbc269a88f86e72ae54bfe36.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'HAM50-C1', 'X-Amz-Cf-Id': '1kVBfIZ-PKgwke3RbR7F6u1F9k8UXl5OmPOwIAaQeW7Lb9svtxFxJw=='} {"code":-2011,"msg":"Unknown order sent."}
Exception in thread Thread-5:
Traceback (most recent call last):
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/base/exchange.py", line 602, in fetch
response.raise_for_status()
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/requests/models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://testnet.binancefuture.com/fapi/v1/order?timestamp=1617812353832&recvWindow=5000&symbol=BCHUSDT&orderId=471598387&signature=29a544d14f7c7ad19646a46532d03d510fbbe3988f9c0fa52d4fa42dd1239943
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/.conda/envs/untitled3/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/Users/user/.conda/envs/untitled3/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/user/Workfiles/Python/vs_binance_algo/testnet/binance_testnet_futures_stp+tp separately_merge.py", line 64, in print_stream_data_from_stream_buffer
exchange.cancel_order(int(orders[1]['id']), 'BCH/USDT')
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/binance.py", line 2070, in cancel_order
response = getattr(self, method)(self.extend(request, query))
File "/Users/user.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/base/exchange.py", line 470, in inner
return entry(_self, **inner_kwargs)
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/binance.py", line 2907, in request
response = self.fetch2(path, api, method, params, headers, body)
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/base/exchange.py", line 491, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/base/exchange.py", line 618, in fetch
self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/binance.py", line 2901, in handle_errors
self.throw_exactly_matched_exception(self.exceptions, error, feedback)
File "/Users/user/.conda/envs/untitled3/lib/python3.8/site-packages/ccxt/base/exchange.py", line 509, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.OrderNotFound: binance {"code":-2011,"msg":"Unknown order sent."}