Repository: freqtrade/freqtrade

Issue:
Error when accessing Trades
**Describe the bug**
When accessing the trades, freqtrade generates an error (see below). I can't tell if frequi or freqtrade is to blame, the error is triggered by frequi I am using binance as exchange.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to trades
2. Click on Pairs-combined
3. Scroll down to ADA/BTC and select
4. See error below

**Expected behavior**
The chart should be loaded, however only 'No Data' is displayed. 

**Desktop (please complete the following information):**
 - OS: MacOS
 - Browser tested with Safari and Chrome
 - Version Big Sur

**Additional context**
The log contents from freqtrade:
```
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/root/.local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/root/.local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 86, in __call__
    await self.simple_response(scope, receive, send, request_headers=headers)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 142, in simple_response
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/root/.local/lib/python3.8/site-packages/fastapi/routing.py", line 220, in app
    response = actual_response_class(
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 49, in __init__
    self.body = self.render(content)
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 157, in render
    return json.dumps(
  File "/usr/local/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/local/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant
2021-02-20 09:23:18,195 - uvicorn.error - ERROR - Exception in ASGI application
Traceback (most recent call last):
  File "/root/.local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/root/.local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 86, in __call__
    await self.simple_response(scope, receive, send, request_headers=headers)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 142, in simple_response
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/root/.local/lib/python3.8/site-packages/fastapi/routing.py", line 220, in app
    response = actual_response_class(
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 49, in __init__
    self.body = self.render(content)
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 157, in render
    return json.dumps(
  File "/usr/local/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/local/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant
2021-02-20 09:23:26,959 - freqtrade.worker - INFO - Bot heartbeat. PID=1, version='2021.1', state='RUNNING'
```
Error when accessing Trades
**Describe the bug**
When accessing the trades, freqtrade generates an error (see below). I can't tell if frequi or freqtrade is to blame, the error is triggered by frequi I am using binance as exchange.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to trades
2. Click on Pairs-combined
3. Scroll down to ADA/BTC and select
4. See error below

**Expected behavior**
The chart should be loaded, however only 'No Data' is displayed. 

**Desktop (please complete the following information):**
 - OS: MacOS
 - Browser tested with Safari and Chrome
 - Version Big Sur

**Additional context**
The log contents from freqtrade:
```
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/root/.local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/root/.local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 86, in __call__
    await self.simple_response(scope, receive, send, request_headers=headers)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 142, in simple_response
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/root/.local/lib/python3.8/site-packages/fastapi/routing.py", line 220, in app
    response = actual_response_class(
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 49, in __init__
    self.body = self.render(content)
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 157, in render
    return json.dumps(
  File "/usr/local/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/local/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant
2021-02-20 09:23:18,195 - uvicorn.error - ERROR - Exception in ASGI application
Traceback (most recent call last):
  File "/root/.local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/root/.local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 86, in __call__
    await self.simple_response(scope, receive, send, request_headers=headers)
  File "/root/.local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 142, in simple_response
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/root/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/root/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/root/.local/lib/python3.8/site-packages/fastapi/routing.py", line 220, in app
    response = actual_response_class(
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 49, in __init__
    self.body = self.render(content)
  File "/root/.local/lib/python3.8/site-packages/starlette/responses.py", line 157, in render
    return json.dumps(
  File "/usr/local/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/local/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant
2021-02-20 09:23:26,959 - freqtrade.worker - INFO - Bot heartbeat. PID=1, version='2021.1', state='RUNNING'
```


Discussion:
as the logs are from freqtrade, it's a freqtrade issue.

While i've moved the issue now to the correct Repository - please fill out the issue template so we know which version you're using.
I am running freqtrade in docker on a linux host. My docker-compose.yml:
```
  freqtrade:
    image: freqtradeorg/freqtrade:stable
    restart: unless-stopped
    container_name: freqtrade
    network_mode: bridge
    ports:
      - 8081:8081
    volumes:
      - ${USERDIR}/freqtrade:/freqtrade/user_data
      - /etc/localtime:/etc/localtime:ro
    # Default command used when running `docker compose up`
    command: >
      trade
      --logfile /freqtrade/user_data/logs/freqtrade.log
      --db-url sqlite:////freqtrade/user_data/tradesv3.sqlite
      --config /freqtrade/user_data/config.json
      --strategy xxxx
```
Freqtrade version:
```
root@4e01255f5826:/freqtrade# freqtrade -V
freqtrade 2021.1
```
Please let me know if you need more info...
it seems like something in your trades becomes either infinitely small (or infinitely big).

It's quite difficult to debug too, as it's unclear which endpoint this comes from.
Are you able to use the chrome (or firefox) dev tools and use the network tab to check which call fails? (I'll only need the url i think).

I suspect it's eihter `/status` - or `/trades` ... 
I just looped through all the pairs in the trade and all of them are working now... The typical demo effect. I did not change anything. I am on binance, and did notice some availability issues lately, as the log contains a number of message lines like ```freqtrade.data.converter - INFO - Missing data fillup for LINK/BTC: before: 999 - after: 1014```.  I do not recall if these are the same pairs having this issue. 

I will let you know as soon as this problem occurs again.
the "availability" issues tripped me up - i think I've found the problem - will have a look.
as the logs are from freqtrade, it's a freqtrade issue.

While i've moved the issue now to the correct Repository - please fill out the issue template so we know which version you're using.
I am running freqtrade in docker on a linux host. My docker-compose.yml:
```
  freqtrade:
    image: freqtradeorg/freqtrade:stable
    restart: unless-stopped
    container_name: freqtrade
    network_mode: bridge
    ports:
      - 8081:8081
    volumes:
      - ${USERDIR}/freqtrade:/freqtrade/user_data
      - /etc/localtime:/etc/localtime:ro
    # Default command used when running `docker compose up`
    command: >
      trade
      --logfile /freqtrade/user_data/logs/freqtrade.log
      --db-url sqlite:////freqtrade/user_data/tradesv3.sqlite
      --config /freqtrade/user_data/config.json
      --strategy xxxx
```
Freqtrade version:
```
root@4e01255f5826:/freqtrade# freqtrade -V
freqtrade 2021.1
```
Please let me know if you need more info...
it seems like something in your trades becomes either infinitely small (or infinitely big).

It's quite difficult to debug too, as it's unclear which endpoint this comes from.
Are you able to use the chrome (or firefox) dev tools and use the network tab to check which call fails? (I'll only need the url i think).

I suspect it's eihter `/status` - or `/trades` ... 
I just looped through all the pairs in the trade and all of them are working now... The typical demo effect. I did not change anything. I am on binance, and did notice some availability issues lately, as the log contains a number of message lines like ```freqtrade.data.converter - INFO - Missing data fillup for LINK/BTC: before: 999 - after: 1014```.  I do not recall if these are the same pairs having this issue. 

I will let you know as soon as this problem occurs again.
the "availability" issues tripped me up - i think I've found the problem - will have a look.

Resolving patch:
diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py
--- a/freqtrade/rpc/api_server/webserver.py
+++ b/freqtrade/rpc/api_server/webserver.py
@@ -2,6 +2,7 @@
 from ipaddress import IPv4Address
 from typing import Any, Dict
 
+import rapidjson
 import uvicorn
 from fastapi import Depends, FastAPI
 from fastapi.middleware.cors import CORSMiddleware
@@ -14,6 +15,17 @@
 logger = logging.getLogger(__name__)
 
 
+class FTJSONResponse(JSONResponse):
+    media_type = "application/json"
+
+    def render(self, content: Any) -> bytes:
+        """
+        Use rapidjson for responses
+        Handles NaN and Inf / -Inf in a javascript way by default.
+        """
+        return rapidjson.dumps(content).encode("utf-8")
+
+
 class ApiServer(RPCHandler):
 
     _rpc: RPC
@@ -32,6 +44,7 @@ def __init__(self, rpc: RPC, config: Dict[str, Any]) -> None:
         self.app = FastAPI(title="Freqtrade API",
                            docs_url='/docs' if api_config.get('enable_openapi', False) else None,
                            redoc_url=None,
+                           default_response_class=FTJSONResponse,
                            )
         self.configure_app(self.app, self._config)
 


Test patch:
diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py
--- a/tests/rpc/test_rpc_apiserver.py
+++ b/tests/rpc/test_rpc_apiserver.py
@@ -11,9 +11,11 @@
 from fastapi import FastAPI
 from fastapi.exceptions import HTTPException
 from fastapi.testclient import TestClient
+from numpy import isnan
 from requests.auth import _basic_auth_str
 
 from freqtrade.__init__ import __version__
+from freqtrade.exceptions import ExchangeError
 from freqtrade.loggers import setup_logging, setup_logging_pre
 from freqtrade.persistence import PairLocks, Trade
 from freqtrade.rpc import RPC
@@ -789,6 +791,15 @@ def test_api_status(botclient, mocker, ticker, fee, markets):
         'exchange': 'bittrex',
     }]
 
+    mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_sell_rate',
+                 MagicMock(side_effect=ExchangeError("Pair 'ETH/BTC' not available")))
+
+    rc = client_get(client, f"{BASE_URI}/status")
+    assert_response(rc)
+    resp_values = rc.json()
+    assert len(resp_values) == 1
+    assert isnan(resp_values[0]['profit_abs'])
+
 
 def test_api_version(botclient):
     ftbot, client = botclient