How To Handle CCXT Binance Intermittent Network Error - exception

I stumbled across an issue which causes the below script to throw an error every so often, like every other day on average.
The script is being run 24/7 and dozens of instances similar to it are being run simultaneously. That seems to be relevant because as can be seen from the error, it appears to throw it on another instance (different asset than the one being retrieved).
OS: W10
Programming Language version: 3.9
CCXT version: 1.54.87
import ccxt
import pandas_ta as ta
import config
import schedule
import pandas as pd
from datetime import datetime
import time
import socket
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 250)
exchange = ccxt.binance({
'apiKey': config.BINANCE_API_KEY,
'secret': config.BINANCE_API_SECRET,
'enableRateLimit': True,
'options': {
'defaultType': 'future'
},
})
in_position = False
free_balance = exchange.fetch_free_balance()
used_balance = exchange.fetch_used_balance()
free_usd = (free_balance['USDT'])
used_usd = (used_balance['USDT'])
amount = free_usd + used_usd
quantity = 0
new_quantity = 0
def trigger(df):
// strategy
def algo():
print(f"Loading data as of {datetime.now().isoformat()}")
bars = exchange.fetch_ohlcv('BNB/USDT', timeframe='30m', limit=50)
df = pd.DataFrame(bars, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
df['time'] = pd.to_datetime(df['time'], unit='ms')
df.set_index(pd.DatetimeIndex(df['time']), inplace=True)
trigger(df)
try:
schedule.every(2).seconds.do(algo)
while True:
schedule.run_pending()
time.sleep(1)
except ConnectionResetError:
schedule.every(3).seconds.do(algo)
while True:
schedule.run_pending()
time.sleep(1)
except socket.timeout:
schedule.every(3).seconds.do(algo)
while True:
schedule.run_pending()
time.sleep(1)
Traceback (most recent call last):
File "C:\Users\", line 699, in urlopen
httplib_response = self._make_request(
File "C:\Users\", line 445, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\", line 440, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\", line 1349, in getresponse
response.begin()
File "C:\Users\", line 316, in begin
version, status, reason = self._read_status()
File "C:\Users\", line 277, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\", line 704, in readinto
return self._sock.recv_into(b)
File "C:\Users\", line 1241, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\", line 1099, in read
return self._sslobj.read(len, buffer)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\", line 439, in send
resp = conn.urlopen(
File "C:\Users\", line 755, in urlopen
retries = retries.increment(
File "C:\Users\", line 532, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Users\", line 769, in reraise
raise value.with_traceback(tb)
File "C:\Users\", line 699, in urlopen
httplib_response = self._make_request(
File "C:\Users\", line 445, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\", line 440, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\", line 1349, in getresponse
response.begin()
File "C:\Users\", line 316, in begin
version, status, reason = self._read_status()
File "C:\Users\", line 277, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\", line 704, in readinto
return self._sock.recv_into(b)
File "C:\Users\", line 1241, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\", line 1099, in read
return self._sslobj.read(len, buffer)
urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\", line 571, in fetch
response = self.session.request(
File "C:\Users\", line 542, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\", line 655, in send
r = adapter.send(request, **kwargs)
File "C:\Users\", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\", line 79, in <module>
schedule.run_pending()
File "C:\Users\", line 780, in run_pending
default_scheduler.run_pending()
File "C:\Users\", line 100, in run_pending
self._run_job(job)
File "C:\Users\", line 172, in _run_job
ret = job.run()
File "C:\Users\", line 661, in run
ret = self.job_func()
File "C:\Users\", line 67, in algo
bars = exchange.fetch_ohlcv('ADA/USDT', timeframe='15m', limit=300)
File "C:\Users\", line 1724, in fetch_ohlcv
response = getattr(self, method)(self.extend(request, params))
File "C:\Users\", line 463, in inner
return entry(_self, **inner_kwargs)
File "C:\Users\", line 4119, in request
response = self.fetch2(path, api, method, params, headers, body)
File "C:\Users\", line 486, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "C:\Users\", line 623, in fetch
raise NetworkError(details) from e
ccxt.base.errors.NetworkError: binance GET https://fapi.binance.com/fapi/v1/klines?symbol=ADAUSDT&interval=15m&limit=300

I got the same problem, my browser was able to access the url fine, but pycharm ran with a network error, i m using proxy to access binance.com , and my pycharm proxy setting is manual and Connection detection is normal

Related

Dash Plotly error TypeError: Object of type DataFrame is not JSON serializable

Hello I am working with Dash for making dashboard.
Below is my code.
I tried to fix the error but not able to fix, Can anyone look into this?
on chrome i am getting. Error loading layout
I am getting TypeError
import dash_bootstrap_components as dbc
from dash import dcc
import dash_html_components as html
from dash import dash_table
import pandas as pd
import numpy as np
def getData():
return preprocess()
def back_to_df(dictio):
return pd.DataFrame.from_dict(dictio)
tblcols =[{"name": i, "id": i} for i in back_to_df(getData()).columns]
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
body = html.Div([
html.H1("Live rates")
, dbc.Row([
dbc.Col(html.Div([dcc.Interval('graph-update', interval = 80, n_intervals = 0),
dash_table.DataTable(
id = 'table',
data = getData(),
columns=tblcols,
page_size= 10,
style_table={'overflowX': 'auto'},
)]),width=3)
])
])
app.layout = html.Div([body])
#app.callback(
dash.dependencies.Output('table','data'),
[dash.dependencies.Input('graph-update', 'n_intervals')])
def updateTable(n):
return getData()
if __name__ == "__main__":
app.run_server(debug = False, port = 8010)
I tried to fix the error but not able to fix, Can anyone look into this?
I am getting error as follows.
Looking for help for below error. dash pandas plotly dataframe
Traceback (most recent call last):
File "C:\Users\Admin\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Admin\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Admin\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Admin\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Admin\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Admin\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Admin\anaconda3\lib\site-packages\dash\dash.py", line 569, in serve_layout
to_json(layout),
File "C:\Users\Admin\anaconda3\lib\site-packages\dash\_utils.py", line 20, in to_json
return to_json_plotly(value)
File "C:\Users\Admin\anaconda3\lib\site-packages\plotly\io\_json.py", line 124, in to_json_plotly
return json.dumps(plotly_object, cls=PlotlyJSONEncoder, **opts)
File "C:\Users\Admin\anaconda3\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\Admin\anaconda3\lib\site-packages\_plotly_utils\utils.py", line 59, in encode
encoded_o = super(PlotlyJSONEncoder, self).encode(o)
File "C:\Users\Admin\anaconda3\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Admin\anaconda3\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Admin\anaconda3\lib\site-packages\_plotly_utils\utils.py", line 136, in default
return _json.JSONEncoder.default(self, obj)
File "C:\Users\Admin\anaconda3\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type DataFrame is not JSON serializable```
Sounds like the getData function is returning a pandas DataFrame directly. That won't work. You'll need to do this:
return df.to_dict(orient='records')
That should work.

Intermittent IndexError with MySQL and Django running on Ubuntu

Here is what I'm getting:
Traceback (most recent call last):
File "/.../.env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view
if test_func(request.user):
File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 44, in <lambda>
lambda u: u.is_authenticated,
File "/.../.env/lib/python3.6/site-packages/django/utils/functional.py", line 213, in inner
self._setup()
File "/.../.env/lib/python3.6/site-packages/django/utils/functional.py", line 347, in _setup
self._wrapped = self._setupfunc()
File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 24, in <lambda>
request.user = SimpleLazyObject(lambda: get_user(request))
File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 12, in get_user
request._cached_user = auth.get_user(request)
File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 189, in get_user
user = backend.get_user(user_id)
File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/backends.py", line 98, in get_user
user = UserModel._default_manager.get(pk=user_id)
File "/.../.env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get
num = len(clone)
File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__
self._fetch_all()
File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 63, in __iter__
for row in compiler.results_iter(results):
File "/.../.env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1007, in apply_converters
value = row[pos]
IndexError: list index out of range
As you can see, there is none of my code in the stacktrace, all I know is that this code is happening somewhere in a very simple view that gets a queryset and renders it to JSON.
Most of the times it works, sometimes this traceback is thrown and the page 500s.
What the hell is going on?
Sometimes I get other weird errors:
unsupported operand type(s) for +=: 'int' and 'str'
triggered by
count += Model.objects.filter(...).count()
I've tried to replicate from a shell, but that's not working.

How to get https://stocks.exchange/api2/ticker

import json, requests
def tick():
r = requests.get('https://stocks.exchange/api2/ticker')
return r.json()
print tick()
This code outputs,
Traceback (most recent call last):
File "C:\Users\Steven\Desktop\Auto\tradeogre\stocksexchange.py", line 6, in
<module>
print tick()
File "C:\Users\Steven\Desktop\Auto\tradeogre\stocksexchange.py", line 4, in
tick
r = requests.get('https://stocks.exchange/api2/ticker')
File "C:\Python27\lib\site-packages\requests\api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "C:\Python27\lib\site-packages\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 508, in
request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests\adapters.py", line 506, in send
raise SSLError(e, request=request)
SSLError: HTTPSConnectionPool(host='stocks.exchange', port=443): Max retries
exceeded with url: /api2/ticker (Caused by SSLError(SSLEOFError(8, u'EOF
occurred in violation of protocol (_ssl.c:661)'),))
How would I do this without violating the protocol? I have used urllib, urllib2, and get similer responses. If I enter the url in the browser, it displays the data I need. Any help would be greatly appreciated.

AWS Beanstalk integration with codecommit

I have existing python project on AWS Beanstalk I decided to integrate it with codecommit but I get following err when I enter Branch name.
Enter Branch Name
***** Must have at least one commit to create a new branch with CodeCommit *****
(default is "develop"): develop
Traceback (most recent call last):
File "/home/fartash/.local/bin/eb", line 11, in <module>
sys.exit(main())
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/core/ebcore.py", line 150, in main
app.run()
File "/home/fartash/.local/lib/python3.5/site-packages/cement/core/foundation.py", line 797, in run
return_val = self.controller._dispatch()
File "/home/fartash/.local/lib/python3.5/site-packages/cement/core/controller.py", line 472, in _dispatch
return func()
File "/home/fartash/.local/lib/python3.5/site-packages/cement/core/controller.py", line 478, in _dispatch
return func()
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/core/abstractcontroller.py", line 57, in default
self.do_command()
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/controllers/initialize.py", line 172, in do_command
branch = get_branch_interactive(repository)
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/controllers/initialize.py", line 575, in get_branch_interactive
source_control.setup_new_codecommit_branch(branch_name=branch_name)
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/objects/sourcecontrol.py", line 313, in setup_new_codecommit_branch
self.fetch_remote_branches(self.codecommit_remote_name)
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/objects/sourcecontrol.py", line 397, in fetch_remote_branches
stdout, stderr, exitcode = self._run_cmd(['git', 'fetch', self.get_codecommit_presigned_remote_url(),
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/objects/sourcecontrol.py", line 434, in get_codecommit_presigned_remote_url
signed_url = codecommit.create_signed_url(remote_url)
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/lib/codecommit.py", line 138, in create_signed_url
password = _sign_codecommit_url(aws.get_region_name(), remote_url)
File "/home/fartash/.local/lib/python3.5/site-packages/ebcli/lib/codecommit.py", line 130, in _sign_codecommit_url
signature = signer.signature(string_to_sign, request)
File "/home/fartash/anaconda3/lib/python3.5/site-packages/botocore/auth.py", line 305, in signature
k_date = self._sign(('AWS4' + key).encode('utf-8'),
TypeError: Can't convert 'NoneType' object to str implicitly

urllib exception http.client.BadStatusLine

I can't for the life of me figure out why I can't catch this exception.
Looking here at this guide.
def get_team_names(get_team_id_url, team_id):
print(get_team_id_url + team_id)
try:
response = urllib.request.urlopen(get_team_id_url + team_id)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read())
except urllib.error.URLError as e:
print(e.code)
print(e.read())
exception:
Traceback (most recent call last):
File "queue_cleaner_main.py", line 60, in <module>
sys.exit(main())
File "queue_cleaner_main.py", line 57, in main
team_names_to_contact = queue_cleaner_functions.get_team_names(SERVICE_NOW_TEAM_NAME_URL, team[2])
File "D:\oppssup\old_job\queue_cleaner_functions.py", line 132, in get_team_names
response = urllib.request.urlopen(get_team_id_url + team_id)
File "C:\Python34\lib\urllib\request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "C:\Python34\lib\urllib\request.py", line 455, in open
response = self._open(req, data)
File "C:\Python34\lib\urllib\request.py", line 473, in _open
'_open', req)
File "C:\Python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 1202, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Python34\lib\urllib\request.py", line 1177, in do_open
r = h.getresponse()
File "C:\Python34\lib\http\client.py", line 1172, in getresponse
response.begin()
File "C:\Python34\lib\http\client.py", line 351, in begin
version, status, reason = self._read_status()
File "C:\Python34\lib\http\client.py", line 321, in _read_status
raise BadStatusLine(line)
http.client.BadStatusLine: ''
In addition, my entire method seems to be very clunky. I cannot figure out an elegant way to handle exceptions, including a case where no result is returned.
def get_team_names(get_team_id_url, team_id):
print(get_team_id_url + team_id)
try:
response = urllib.request.urlopen(get_team_id_url + team_id)
except Exception as e:
#print(e.code)
#print(e.read())
print('shit')
#print(response.read().decode('utf8'))
r_json = json.loads(response.read().decode('utf8'))
print(r_json['result'])
for i in r_json['result']:
print(i['group'])
Exception:
Traceback (most recent call last):
File "queue_cleaner_main.py", line 60, in <module>
sys.exit(main())
File "queue_cleaner_main.py", line 57, in main
team_names_to_contact = queue_cleaner_functions.get_team_names(SERVICE_NOW_TEAM_NAME_URL, team[2])
File "D:\oppssup\old_job\queue_cleaner_functions.py", line 141, in get_team_names
r_json = json.loads(response.read().decode('utf8'))
UnboundLocalError: local variable 'response' referenced before assignment
This http.client.BadStatusLine is a subclass of http.client.HTTPException. I think if you do:
try:
response = urllib.request.urlopen(get_team_id_url + team_id)
except http.client.HTTPException as e:
print(e)
then you shouldn't have problem catching it. However, what caused it is perhaps what you should concern.