Why can't I get my account info binance api - python

When I use the function print(client.get_account()) this is my code followed by the output
from binance.client import Client,
import pandas as pd,
import mplfinance as mpl,
import numpy as np,
import os,
import matplotlib.pyplot as plt,
#I set up my credential for this api
api_key = '(my credential)'
api_secret= '(my credential)'
client=Client(api_key,api_secret)
print(client.get_account())
output
Traceback (most recent call last):
File "c:\Users\berge\OneDrive\Documents\Binance Bot\Mean_Reversion.py", line 13, in <module>
print(client.get_account())
File "C:\Users\berge\OneDrive\Documents\Binance Bot\.venv\lib\site-packages\binance\client.py", line 1956, in get_account
return self._get('account', True, data=params)
File "C:\Users\berge\OneDrive\Documents\Binance Bot\.venv\lib\site-packages\binance\client.py", line 371, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\berge\OneDrive\Documents\Binance Bot\.venv\lib\site-packages\binance\client.py", line 334, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\berge\OneDrive\Documents\Binance Bot\.venv\lib\site-packages\binance\client.py", line 315, in _request
return self._handle_response(self.response)
File "C:\Users\berge\OneDrive\Documents\Binance Bot\.venv\lib\site-packages\binance\client.py", line 324, in _handle_response
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request is outside of the recvWindow.

This is a very common problem, and the solution is very simple. For the Binance API to work, your system time should be synced with the Binance time.
Fix: In Windows, go to your Date & Time setting and click on "Sync now". Voila! fixed.

Related

Can't read from a .env file

I'm new to python, and I am trying to build a little Reddit bot to get some practice.
My bot works just fine (tested many times) but once I try to move the credentials to a .env file it fails.
I've ran pip3 install python-dotenv
This is my code, just one file, removing irrelevant stuff:
import os
import praw
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from dotenv import load_dotenv
load_dotenv()
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://makideat-6a-default-db.firebaseio.com'
})
db_ref = db.reference()
reddit = praw.Reddit(
client_id=os.getenv('CLIENT_ID'),
client_secret=os.getenv('CLIENT_SECRET'),
username=os.getenv('USERNAME'),
password=os.getenv('PASSWORD'),
user_agent=os.getenv('USER_AGENT')
)
def summoned_reply(comment):
DO SOME STUFF...
messages = reddit.inbox.stream() # creates an iterable for your inbox and streams it
for message in messages: # iterates through your messages
try:
if message in reddit.inbox.mentions() and message in reddit.inbox.unread():
summoned_reply(message)
message.mark_read()
except praw.exceptions.APIException:
print("probably a rate limit....")
And this is the error I'm getting (line 56 is for message in messages:):
Traceback (most recent call last):
File "C:\Users\Yanay\Documents\Coding\NiceAndPretty\main.py", line 56, in <module>
for message in messages: # iterates through your messages
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\util.py", line 195, in stream_generator
for item in reversed(list(function(limit=limit, **function_kwargs))):
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\listing\generator.py", line 63, in __next__
self._next_batch()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\listing\generator.py", line 89, in _next_batch
self._listing = self._reddit.get(self.url, params=self.params)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 634, in get
return self._objectify_request(method="GET", params=params, path=path)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 739, in _objectify_request
self.request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 941, in request
return self._core.request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 330, in request
return self._request_with_retries(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\auth.py", line 425, in refresh
self._request_token(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
Then, in the same directory I have a .env file in the following structure (changed characters for everything here of course, but haven't changed the structure or added or removed spaces from anywhere):
CLIENT_ID=gGATUW-Ea507LoQ
CLIENT_SECRET=_b6vCCHKBCqVHzlJin3sEQ
USERNAME=Maddeeat
PASSWORD=!Neatat!
USER_AGENT=Maddeeat:1.0.0 (by u/Maddeeat)

error related to Tornado when calling bokeh

I am running a code using bokeh to display interactive plots. it was working fine until suddenly i get error related to tornado. I have installed latest version of bokeh and tornado but it does not solve the problem.the traceback is very long :
I am using pyarpes code developped for apres data reduction pyarpes:
import arpes
from arpes.io import(load_example_data, load_without_dataset, direct_load)
from arpes.utilities import default_dataset
from arpes.utilities.conversion import convert_to_kspace
from arpes.utilities.conversion import *
from arpes.fits import *
from pathlib import Path
import arpes.corrections
import arpes.plotting
from arpes.analysis import *
from arpes.provenance import update_provenance
#DIRECT DATA LOADING test
p = Path('.')/'arpes'/'example_data'/'test.nxs'
load_without_dataset(p)
f = load_without_dataset(p, location='xxx')
data = f.sel(psi=2, phi=slice(-0.01, 0.07), eV=slice(95.2, 96.5)).transpose('eV', 'phi') # pocket selection
data_mean = (data - data.mean('eV')) # background substraction
data_mean.S.show()
ERROR:tornado.application:Uncaught exception GET /autoload.js?bokeh-autoload-element=1001&bokeh-absolute-url=http://localhost:52526&resources=none (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:52526', method='GET', uri='/autoload.js?bokeh-autoload-element=1001&bokeh-absolute-url=http://localhost:52526&resources=none', version='HTTP/1.1', remote_ip='127.0.0.1')
Traceback (most recent call last):
File "C:\Users\xxx\Anaconda3\lib\site-packages\tornado\web.py", line 1704, in _execute
result = await result
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\server\views\autoload_js_handler.py", line 60, in get
session = await self.get_session()
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\server\views\session_handler.py", line 120, in get_session
session = await self.application_context.create_session_if_needed(session_id, self.request, token)
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\server\contexts.py", line 218, in create_session_if_needed
self._application.initialize_document(doc)
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\application\application.py", line 171, in initialize_document
h.modify_document(doc)
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\application\handlers\function.py", line 132, in modify_document
self._func(doc)
File "C:\Users\xxx\arpes\arpes\plotting\interactive.py", line 43, in tool_handler
return self.tool_handler_2d(doc)
File "C:\Users\xxx\arpes\arpes\plotting\interactive.py", line 225, in tool_handler_2d
color_mode_dropdown.on_change('value', on_change_color_mode)
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\model.py", line 551, in on_change
descriptor = self.lookup(attr)
File "C:\Users\xxx\Anaconda3\lib\site-packages\bokeh\core\has_props.py", line 492, in lookup
raise AttributeError(f"{cls.__name__}.{name} property descriptor does not exist")
AttributeError: Dropdown.value property descriptor does not exist
ERROR:tornado.access:500 GET /autoload.js?bokeh-autoload-element=1001&bokeh-absolute-url=http://localhost:52526&resources=none (127.0.0.1) 80.00ms
thanks for helping

eBay and Authlib Unconventional token type

I'm trying to use Authlib library to access new eBay REST API (as Authorization code grant)
Here is my code;
import json
import os
import webbrowser
from time import time
from authlib.integrations.requests_client import OAuth2Session
from rpi_order_data_sync import settings
def auth(seller):
def token_updater(token, seller=seller):
if not os.path.exists(seller):
open(seller, "w").close()
with open(seller, "w") as token_file:
json.dump(token, token_file)
scope = ["https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly"]
if not os.path.exists(seller):
ebay = OAuth2Session(
settings.E_APP_ID,
settings.E_CERT_ID,
redirect_uri=settings.E_RU_NAME,
scope=scope,
)
uri, state = ebay.create_authorization_url(
"https://auth.sandbox.ebay.com/oauth2/authorize",
)
print("Please go to {} and authorize access.".format(uri))
try:
webbrowser.open_new_tab(uri)
except webbrowser.Error:
pass
authorization_response = input("Please enter callback URL: ") # nosec
token = ebay.fetch_token(
"https://api.sandbox.ebay.com/identity/v1/oauth2/token",
authorization_response=authorization_response,
)
print(token)
token_updater(token)
return ebay
The problem is eBay's token response has an unconventional token type named "User Access Token" instead of "Bearer". Therefore I get this error;
Traceback (most recent call last):
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 37, in __call__
req.url, req.headers, req.body = self.prepare(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/oauth2/auth.py", line 91, in prepare
sign = self.SIGN_METHODS[token_type.lower()]
KeyError: 'user access token'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/bin/rods", line 11, in <module>
load_entry_point('rpi-order-data-sync', 'console_scripts', 'rods')()
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/thiras/HDD/freelancer/contentassasin/rpi-order-data-sync/rpi_order_data_sync/main.py", line 132, in sync_ebay_orders
orders = ebay.get(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 543, in get
return self.request('GET', url, **kwargs)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 113, in request
return super(OAuth2Session, self).request(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 516, in request
prep = self.prepare_request(req)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 449, in prepare_request
p.prepare(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/models.py", line 318, in prepare
self.prepare_auth(auth, url)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/models.py", line 549, in prepare_auth
r = auth(self)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 41, in __call__
raise UnsupportedTokenTypeError(description=description)
authlib.integrations.base_client.errors.UnsupportedTokenTypeError: unsupported_token_type: Unsupported token_type: 'user access token'
I've noticed Compliance fix for non-standard section at Authlib documentation but couldn't figure out how to do this fix or even possible in this way.
I've found a solution and it also works with requests-oauthlib package. It seems working flawlessly so far. The main struggle was to create a fake request.Response model since request.Response has no setter for .text or .content attributes so modifying them was impossible.
So I've created a FakeResponse class that only mimics .json() method since it was the only method used by Authlib.
class FakeResponse:
""" Fake Class for Request Response class. """
def __init__(self, data):
self.data = data
def json(self):
""" Mocks requests.Response.json(). """
return self.data
After that I've created an access_token_response hook;
def non_compliant_token_type(resp):
data = resp.json()
data["token_type"] = "Bearer"
fake_resp = FakeResponse(data=data)
return fake_resp
Please let me know if you have a better answer or any recommendations to improve it.

Api Request WSDL Python

I am trying to make an api connection via wsdl-soap in Python.
Here are the codes I used.
import zeep
wsdl = 'http://dev.gittigidiyor.com:8080/listingapi/ws/CategoryService?wsdl'
client = zeep.Client(wsdl=wsdl)
send_data=[{
'cat:getCategories' :[
{
'startOffSet' : 0,
'rowCount' : 4,
'withSpecs':'true',
'withDeepest':'true',
'withCatalog':'true',
'lang':'tr'
}
] } ]
print(client.service.getCategories(send_data))
The offical documentation suggests:
WSDL Address: http://dev.gittigidiyor.com:8080/listingapi/ws/CategoryService?wsdl
Service Method Signature: CategoryServiceResponse getCategories(int startOffSet, int rowCount, boolean withSpecs, boolean withDeepest, boolean withCatalog, String lang)
Request Example
<cat:getCategories>
<startOffSet>0</startOffSet>
<rowCount>4</rowCount>
<withSpecs>true</withSpecs>
<withDeepest>true</withDeepest>
<withCatalog>true</withCatalog>
<lang>tr</lang>
</cat:getCategories>
However I can't achieve to get any data from the source. I am getting errors like:
Traceback (most recent call last):
File "/Users/maydin/Desktop/z.py", line 22, in <module>
print(client.service.getCategories(send_data))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/proxy.py", line 42, in __call__
self._op_name, args, kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/bindings/soap.py", line 115, in send
options=options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/bindings/soap.py", line 68, in _create
serialized = operation_obj.create(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/definitions.py", line 200, in create
return self.input.serialize(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/messages/soap.py", line 65, in serialize
self.body.render(body, body_value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 191, in render
self._render_value_item(parent, value, render_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 215, in _render_value_item
return self.type.render(node, value, None, render_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/types/complex.py", line 253, in render
element.render(parent, element_value, child_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/indicators.py", line 241, in render
element.render(parent, element_value, child_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 185, in render
self.validate(value, render_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 236, in validate
"Missing element %s" % (self.name), path=render_path)
zeep.exceptions.ValidationError: Missing element rowCount (getCategories.rowCount)
>>>
Any help (new library suggestions, code correction etc.) will be appriciated.
Thanks in advance!
I finally solved my own problem.. The thing that I have missed is that it was needing an authentication layer.
Here are the codes for those who may need to solve similar problems.
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client
from zeep.transports import Transport
session = Session()
session.auth = HTTPBasicAuth('user_name', 'password')
client = Client('wsdl_url',
transport=Transport(session=session))
print(client.service.service_name(parameter1,parameter2,parameter3..))
Here is the source I made use of..

google-api-python-client broken because of OAuth2?

I am trying to check if a certain dataset exists in bigquery using the Google Api Client in Python. It always worked untill the last update where I got this strange error I don't know how to fix:
Traceback (most recent call last):
File "/root/miniconda/lib/python2.7/site-packages/dsUtils/bq_utils.py", line 106, in _get
resp = bq_service.datasets().get(projectId=self.project_id, datasetId=self.id).execute(num_retries=2)
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper
return wrapped(*args, **kwargs)
File "/root/miniconda/lib/python2.7/site-packages/googleapiclient/http.py", line 755, in execute
method=str(self.method), body=self.body, headers=self.headers)
File "/root/miniconda/lib/python2.7/site-packages/googleapiclient/http.py", line 93, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 598, in new_request
self._refresh(request_orig)
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 864, in _refresh
self._do_refresh_request(http_request)
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 891, in _do_refresh_request
body = self._generate_refresh_request_body()
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 1597, in _generate_refresh_req
uest_body
assertion = self._generate_assertion()
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/service_account.py", line 263, in _generate_ass
ertion
key_id=self._private_key_id)
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/crypt.py", line 97, in make_signed_jwt
signature = signer.sign(signing_input)
File "/root/miniconda/lib/python2.7/site-packages/oauth2client/_pycrypto_crypt.py", line 101, in sign
return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Signature/PKCS1_v1_5.py", line 112, in sign
m = self._key.decrypt(em)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 174, in decrypt
return pubkey.pubkey.decrypt(self, ciphertext)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/PublicKey/pubkey.py", line 93, in decrypt
plaintext=self._decrypt(ciphertext)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 235, in _decrypt
r = getRandomRange(1, self.key.n-1, randfunc=self._randfunc)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Util/number.py", line 123, in getRandomRange
value = getRandomInteger(bits, randfunc)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Util/number.py", line 104, in getRandomInteger
S = randfunc(N>>3)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 202, in read
return self._singleton.read(bytes)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 178, in read
return _UserFriendlyRNG.read(self, bytes)
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 137, in read
self._check_pid()
File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 153, in _check_pid
raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")
AssertionError: PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()
Is someone understanding what is hapening?
Note that I also get this error with other bricks like GCStorage.
Note also that I use the following command to load my Google credentials:
from oauth2client.client import GoogleCredentials
def get_credentials(credentials_path): #my json credentials path
logger.info('Getting credentials...')
try:
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path
credentials = GoogleCredentials.get_application_default()
return credentials
except Exception as e:
raise e
So if anyone know a better way to load my google credentials using my json service account file, and which would avoid the error, please tell me.
It looks like the error is in the PyCrypto module, which appears to be used under the hood by Google's OAuth2 implementation. If your code is calling os.fork() at some point, you may need to call Crypto.Random.atfork() afterward in both the parent and child process in order to update the module's internal state.
See here for PyCrypto docs; search for "atfork" for more info:
https://github.com/dlitz/pycrypto
This question and answer might also be relevant:
PyCrypto : AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")

Categories