# Buggy code
def check_handle_timedout(self) -> None:
    """
    Check if any orders are timed out and cancel if neccessary
    :param timeoutvalue: Number of minutes until order is considered timed out
    :return: None
    """
    buy_timeout = self.config["unfilledtimeout"]["buy"]
    sell_timeout = self.config["unfilledtimeout"]["sell"]
    buy_timeoutthreashold = arrow.utcnow().shift(minutes=-buy_timeout).datetime
    sell_timeoutthreashold = arrow.utcnow().shift(minutes=-sell_timeout).datetime

    for trade in Trade.query.filter(Trade.open_order_id.isnot(None)).all():
        try:
            # FIXME: Somehow the query above returns results
            # where the open_order_id is in fact None.
            # This is probably because the record got
            # updated via /forcesell in a different thread.
            if not trade.open_order_id:
                continue
            order = self.exchange.get_order(trade.open_order_id, trade.pair)
        except requests.exceptions.RequestException:
            logger.info(
                "Cannot query order for %s due to %s", trade, traceback.format_exc()
            )
            continue
        ordertime = arrow.get(order["datetime"]).datetime

        # Check if trade is still actually open
        if int(order["remaining"]) == 0:
            continue

        # Check if trade is still actually open
        if order["status"] == "open":
            if order["side"] == "buy" and ordertime < buy_timeoutthreashold:
                self.handle_timedout_limit_buy(trade, order)
            elif order["side"] == "sell" and ordertime < sell_timeoutthreashold:
                self.handle_timedout_limit_sell(trade, order)


# Traceback (requests.exceptions.HTTPError)
2018-09-25 18:09:50,160 - freqtrade.freqtradebot - INFO - Checking buy signals to create a new trade with stake_amount: 0.002000 ...
2018-09-25 18:09:50,941 - freqtrade.freqtradebot - INFO - Found no buy signals for whitelisted currencies. Trying again..
2018-09-25 18:09:55,168 - freqtrade.freqtradebot - INFO - Checking buy signals to create a new trade with stake_amount: 0.002000 ...
2018-09-25 18:09:56,007 - freqtrade.freqtradebot - INFO - Found no buy signals for whitelisted currencies. Trying again..
2018-09-25 18:10:00,167 - freqtrade.freqtradebot - INFO - Checking buy signals to create a new trade with stake_amount: 0.002000 ...
2018-09-25 18:10:01,052 - freqtrade.freqtradebot - INFO - Found no buy signals for whitelisted currencies. Trying again..
2018-09-25 18:10:21,230 - freqtrade.freqtradebot - INFO - Checking buy signals to create a new trade with stake_amount: 0.002000 ...
2018-09-25 18:10:21,952 - freqtrade.freqtradebot - INFO - Getting price from order book
2018-09-25 18:10:22,452 - freqtrade.freqtradebot - INFO - ...top 2 order book buy rate 0.00000014
2018-09-25 18:10:23,463 - freqtrade.rpc.rpc_manager - INFO - Sending rpc message: {'type': buy, 'exchange': 'Binance', 'pair': 'HOT/BTC', 'market_url': 'https://www.binance.com/tradeDetail.html?symbol=HOT_BTC', 'limit': 1.4e-07, 'stake_amount': 0.002, 'stake_currency': 'BTC', 'fiat_currency': 'GBP'}
2018-09-25 18:10:23,962 - freqtrade.exchange - WARNING - get_order() returned exception: "Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}"
2018-09-25 18:10:23,962 - freqtrade.exchange - WARNING - retrying get_order() still for 3 times
2018-09-25 18:10:24,460 - freqtrade.exchange - WARNING - get_order() returned exception: "Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}"
2018-09-25 18:10:24,461 - freqtrade.exchange - WARNING - retrying get_order() still for 2 times
2018-09-25 18:10:24,957 - freqtrade.exchange - WARNING - get_order() returned exception: "Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}"
2018-09-25 18:10:24,958 - freqtrade.exchange - WARNING - retrying get_order() still for 1 times
2018-09-25 18:10:25,466 - freqtrade.exchange - WARNING - get_order() returned exception: "Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}"
2018-09-25 18:10:25,466 - freqtrade.exchange - WARNING - retrying get_order() still for 0 times
2018-09-25 18:10:25,959 - freqtrade.exchange - WARNING - get_order() returned exception: "Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}"
2018-09-25 18:10:25,960 - freqtrade.exchange - WARNING - Giving up retrying: get_order()
2018-09-25 18:10:25,960 - freqtrade - ERROR - Fatal exception!
Traceback (most recent call last):
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 434, in fetch
response.raise_for_status()
File "/root/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 939, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.binance.com/api/v3/order?timestamp=1537899023710&amp;recvWindow=5000&amp;symbol=HOTBTC&amp;orderId=2051166&amp;signature=4a7aaff595303645d54c0af72ef76cbb281e0d3c5c2d32a4eac258f7f293c7be

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 546, in get_order
return self._api.fetch_order(order_id, pair)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 723, in fetch_order
response = self.privateGetOrder(self.extend(request, params))
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1093, in request
response = self.fetch2(path, api, method, params, headers, body)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 359, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 446, in fetch
self.handle_errors(response.status_code, response.reason, url, method, headers, http_response)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1086, in handle_errors
raise exceptions[error](self.id + ' ' + body)
ccxt.base.errors.OrderNotFound: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 51, in wrapper
return f(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 549, in get_order
f'Could not get order. Message: {e}')
freqtrade.DependencyException: Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 434, in fetch
response.raise_for_status()
File "/root/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 939, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.binance.com/api/v3/order?timestamp=1537899024211&amp;recvWindow=5000&amp;symbol=HOTBTC&amp;orderId=2051166&amp;signature=7c719ae0e77db0691637f935241add7ab8e15e9790f4397dc440e68dca44f76b

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 546, in get_order
return self._api.fetch_order(order_id, pair)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 723, in fetch_order
response = self.privateGetOrder(self.extend(request, params))
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1093, in request
response = self.fetch2(path, api, method, params, headers, body)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 359, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 446, in fetch
self.handle_errors(response.status_code, response.reason, url, method, headers, http_response)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1086, in handle_errors
raise exceptions[error](self.id + ' ' + body)
ccxt.base.errors.OrderNotFound: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 51, in wrapper
return f(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 549, in get_order
f'Could not get order. Message: {e}')
freqtrade.DependencyException: Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 434, in fetch
response.raise_for_status()
File "/root/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 939, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.binance.com/api/v3/order?timestamp=1537899024711&amp;recvWindow=5000&amp;symbol=HOTBTC&amp;orderId=2051166&amp;signature=9acb95288916421e7eefd8a4fc628b366318ce762c8255efd255b3e489cef38c

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 546, in get_order
return self._api.fetch_order(order_id, pair)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 723, in fetch_order
response = self.privateGetOrder(self.extend(request, params))
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1093, in request
response = self.fetch2(path, api, method, params, headers, body)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 359, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 446, in fetch
self.handle_errors(response.status_code, response.reason, url, method, headers, http_response)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1086, in handle_errors
raise exceptions[error](self.id + ' ' + body)
ccxt.base.errors.OrderNotFound: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 51, in wrapper
return f(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 549, in get_order
f'Could not get order. Message: {e}')
freqtrade.DependencyException: Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 434, in fetch
response.raise_for_status()
File "/root/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 939, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.binance.com/api/v3/order?timestamp=1537899025212&amp;recvWindow=5000&amp;symbol=HOTBTC&amp;orderId=2051166&amp;signature=e7e73efc7fb54ca3e0fc72c57dd1d1b86d02347499c80f2673fdfae2d7614485

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 546, in get_order
return self._api.fetch_order(order_id, pair)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 723, in fetch_order
response = self.privateGetOrder(self.extend(request, params))
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1093, in request
response = self.fetch2(path, api, method, params, headers, body)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 359, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 446, in fetch
self.handle_errors(response.status_code, response.reason, url, method, headers, http_response)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1086, in handle_errors
raise exceptions[error](self.id + ' ' + body)
ccxt.base.errors.OrderNotFound: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 51, in wrapper
return f(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 549, in get_order
f'Could not get order. Message: {e}')
freqtrade.DependencyException: Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 434, in fetch
response.raise_for_status()
File "/root/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 939, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.binance.com/api/v3/order?timestamp=1537899025712&amp;recvWindow=5000&amp;symbol=HOTBTC&amp;orderId=2051166&amp;signature=532a46bbd2fb7d29e9616101c42a43f16c9d7667a268558af885c26c43c0d606

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 546, in get_order
return self._api.fetch_order(order_id, pair)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 723, in fetch_order
response = self.privateGetOrder(self.extend(request, params))
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1093, in request
response = self.fetch2(path, api, method, params, headers, body)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 359, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/base/exchange.py", line 446, in fetch
self.handle_errors(response.status_code, response.reason, url, method, headers, http_response)
File "/root/freqtrade/.env/lib/python3.6/site-packages/ccxt/binance.py", line 1086, in handle_errors
raise exceptions[error](self.id + ' ' + body)
ccxt.base.errors.OrderNotFound: binance {"code":-2013,"msg":"Order does not exist."}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "freqtrade/main.py", line 49, in main
state = freqtrade.worker(old_state=state)
File "/root/freqtrade/freqtrade/freqtradebot.py", line 114, in worker
nb_assets=nb_assets)
File "/root/freqtrade/freqtrade/freqtradebot.py", line 158, in _throttle
result = func(*args, **kwargs)
File "/root/freqtrade/freqtrade/freqtradebot.py", line 201, in _process
self.check_handle_timedout()
File "/root/freqtrade/freqtrade/freqtradebot.py", line 648, in check_handle_timedout
order = self.exchange.get_order(trade.open_order_id, trade.pair)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 58, in wrapper
return wrapper(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 58, in wrapper
return wrapper(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 58, in wrapper
return wrapper(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 61, in wrapper
raise ex
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 51, in wrapper
return f(*args, **kwargs)
File "/root/freqtrade/freqtrade/exchange/__init__.py", line 549, in get_order
f'Could not get order. Message: {e}')
freqtrade.DependencyException: Could not get order. Message: binance {"code":-2013,"msg":"Order does not exist."}
2018-09-25 18:10:25,969 - freqtrade.rpc.rpc_manager - INFO - Sending rpc message: {'type': status, 'status': 'process died'}
2018-09-25 18:10:26,008 - freqtrade.freqtradebot - INFO - Cleaning up modules ...
2018-09-25 18:10:26,008 - freqtrade.rpc.rpc_manager - INFO - Cleaning up rpc modules ...

# Fixed code
def check_handle_timedout(self) -> None:
    """
    Check if any orders are timed out and cancel if neccessary
    :param timeoutvalue: Number of minutes until order is considered timed out
    :return: None
    """
    buy_timeout = self.config["unfilledtimeout"]["buy"]
    sell_timeout = self.config["unfilledtimeout"]["sell"]
    buy_timeoutthreashold = arrow.utcnow().shift(minutes=-buy_timeout).datetime
    sell_timeoutthreashold = arrow.utcnow().shift(minutes=-sell_timeout).datetime

    for trade in Trade.query.filter(Trade.open_order_id.isnot(None)).all():
        try:
            # FIXME: Somehow the query above returns results
            # where the open_order_id is in fact None.
            # This is probably because the record got
            # updated via /forcesell in a different thread.
            if not trade.open_order_id:
                continue
            order = self.exchange.get_order(trade.open_order_id, trade.pair)
        except (RequestException, DependencyException):
            logger.info(
                "Cannot query order for %s due to %s", trade, traceback.format_exc()
            )
            continue
        ordertime = arrow.get(order["datetime"]).datetime

        # Check if trade is still actually open
        if int(order["remaining"]) == 0:
            continue

        # Check if trade is still actually open
        if order["status"] == "open":
            if order["side"] == "buy" and ordertime < buy_timeoutthreashold:
                self.handle_timedout_limit_buy(trade, order)
            elif order["side"] == "sell" and ordertime < sell_timeoutthreashold:
                self.handle_timedout_limit_sell(trade, order)