CCXT solving connection errors - python

I'm getting the following error when I run my code:
I'm guessing the root of this error is when I execute the fetch_ticker() function.
I have two python scripts: main.py and functions.py (includes all the functions)
I've read somewhere else that strategically adding a time.sleep(0.01) can solve the issue.
Would it be wise to add time.sleep(0.01) before any line that requests something through BinanceUS API?
For example,
if now.hour == 0 and now.minute == 0 and (0 <= now.second < 10):
time.sleep(0.01)
target = calc_target(binanceUS, symbol)
time.sleep(0.01)
balance = binanceUS.fetch_balance()
time.sleep(0.01)
usd = balance['total']['USD']
op_mode = True
time.sleep(10)
Though I'm not sure if this will solve the issue...or I also thought about creating an error-handling code for all the functions that I use, but I'm not sure how I would go about it when the function includes one or more if-statements. For example,
def enter_position(exchange, symbol, cur_price, target, amount, position):
try_cnt = 3
while try_cnt > 0:
if cur_price > target:
try:
position['type'] = 'long'
position['amount'] = amount
exchange.create_market_buy_order(symbol=symbol, amount=amount)
except Exception as e:
print("Connection error, trying again...")
try_cnt -= 1
time.sleep(1)
else:
exchange.create_market_buy_order(symbol=symbol, amount=amount)
Not sure if this will work, though.
I'm very confused about how to go around this error. In fact, I'm not even sure what the error means. Would any of the two solutions look plausible?

Related

To Wrap a Loop - Python

If I want to call a function both in a single iteration and in a looping function, that reuses the same code, whats the proper way to create the two functions?
Here is an example single function DoStuff and 3 attempts to create a second way of calling it, in __name__=="__main__".
import time
def DoStuff(txt):
"""Do it one time"""
print(txt)
def LoopStuff(txt):
"""Function of a Function"""
try:
while True:
if time.time() % 5 < 1:
DoStuff(txt)
time.sleep(1)
except KeyboardInterrupt:
print("You killed it.")
except:
print("Loop Failed.")
def Loop(function):
"""This one's broken"""
try:
while True:
if time.time() % 5 < 1:
function()
time.sleep(1)
except KeyboardInterrupt:
print("You killed it.")
except:
print("Loop Failed.")
def Looped(function):
"""Wrapper"""
def wrap(*args,**kwargs):
try:
while True:
if time.time() % 5 < 1:
function(*args, **kwargs)
time.sleep(1)
except KeyboardInterrupt:
print("You killed it.")
except:
print("Loop Failed.")
return wrap
#Looped
def WrapStuff(txt):
"""Hows this work?"""
DoStuff(txt)
if __name__ == '__main__':
DoStuff("one time text")
LoopStuff("Function fuction")
Loop(DoStuff("what's your"))
WrapStuff("conjunction?")
I was trying to create a loop that ran every min, regardless of execution time, but I have shortened it to 5 seconds here for troubleshooting. Maybe there's a better way to do this with a chron type behavior, but that's not really the question I'm asking here.
The 1st and 3rd attempt work but the 2nd exits with
in <module> Loop(DoStuff("what's your"))
in Loop function()
TypeError: 'NoneType' is not callable
I just went trial and error until I found this code that worked. It seems like this will let me use Looped in a wrapper function and in this single line style. If you have a better answer, please share.
It's just a cleaner way of what I was trying to accomplish with WrapSuff.
ShortWrap = Looped(DoStuff)
ShortWrap('my text')
I can see, in hindsight, that the second example Loop(DoStuff("what's your")) is just a failed half-step between the first and third example.

Understanding how a try except logic works within two while loops

I'm having trouble understanding the mechanism of my code. I want to retrieve the realtime price data of a crypto from an exchange and print it every second, while creating a retry mechanism that catches an exception when it occurs.
while True:
try_cnt = 10
while try_cnt > 0:
try:
price = get_current_price(symbol) # function imported from elsewhere
print(price)
time.sleep(1)
try_cnt = 0
break
except Exception as e:
print(e)
try_cnt -= 1
This is how I have it set up but I'm having trouble follow the logic. This is how I see it as of now. After the code has been run:
Price is retrieved
try_cnt is set to 0 and the second while loop is broken
The next second, try_cnt is reset to 10 and price is retrieved
try_cnt is set to 0 again and the second while loop is broken
repeat of this process
Am I understanding this correctly?
EDIT: the reason why I have a while loop outside is that I have other things that are going on at specific times besides the part I mentioned here. The part that I mentioned is supposed to be running all the time every second. For example,
while True:
if now.hour == 0 and now.minute == 0 and now.second == 0:
A = functionA(x,y)
try_cnt = 10
while try_cnt > 0:
try:
price = get_current_price(symbol) # function imported from elsewhere
print(price)
time.sleep(1)
try_cnt = 0
break
except Exception as e:
print(e)
try_cnt -= 1
I think that you are understanding everything just fine, but the code itself is a little silly and redundant. For example, setting try_cnt to 0 and then following that with break is pointless - both lines do the same thing. And unless there is some significance to the variable try_cnt that is not present within the code you posted, its existence seems pretty much useless to me. Here's code that does the exact same thing as the code above, but without the redundancies:
while True:
try:
price = get_current_price(symbol)
print(price)
time.sleep(1)
except Exception as e:
print(e)
In response to your edit, the while True loop encompassing everything makes a lot more sense. However, this means that your code isn't doing what you want it to do. The outer while loop ensures that even if try_cnt reaches 0, try_cnt will just be reset to 10 on the next pass and it will be as if no Exceptions ever occurred (besides the ten error messages in the console). If you want that inner while loop to stop executing when ten Exceptions occur, you need to place the try_cnt = 10 statement outside of both while loops like so:
try_cnt = 10
while True:
if now.hour == 0 and now.minute == 0 and now.second == 0:
A = functionA(x,y)
while try_cnt > 0:
try:
price = get_current_price(symbol)
print(price)
time.sleep(1)
try_cnt = 10
break
except Exception as e:
print(e)
try_cnt -= 1

Python program uses takes up a lot of memory storage per iteration

I created a program that I'm distributing. The program checks for username availability, and after each check a variable named checkedCount gets updated. Each check costs about 4mb or ram, which makes the total memory usage high. For example, I ran the program for about two hours which resulted in 7gb's of ram being in use. I've tried to use clear = lambda: os.system('cls') after each request to clear the terminal, but that didn't work.
Code:
def screen(self):
clear()
print(r"""
/~\
C oo
_( ^)
/ ~\
""")
print(f"""{Fore.LIGHTBLACK_EX}[>]{Fore.RESET} Checks: {self.checkedCount}
{Fore.LIGHTBLACK_EX}[>]{Fore.RESET} Claims: {self.claimedCount}
{Fore.LIGHTBLACK_EX}[>]{Fore.RESET} Errors: {self.errorCount}
""")
def checker(self):
self.proxer = self.proxies()
while True:
self.screen()
[self.usernames.put(line.strip()) for line in open(f"external/{wordlistInput}")]
name = self.usernames.get(); self.usernames.put(name)
url = f"https://public-ubiservices.ubi.com/v3/profiles?nameOnPlatform={name}&platformType=uplay"
if len(name) > 2:
try:
r = requests.get(url, headers=self.headers, proxies=self.proxer)
ctypes.windll.kernel32.SetConsoleTitleW(f"{datetime.now().strftime('%H:%M')} | Developed by gxzs#2979")
if self.checkedCount % 75 == 0:
self.checkedCount += 1
self.proxer = self.proxies()
self.login()
if r.status_code == 200:
self.checkedCount += 1
if len(r.json()['profiles']) != 0:
pass
else:
self.create(name)
else:
with open('external/errors.txt', "a") as errorFile:
errorFile.write(f"{datetime.now().strftime('%H:%M')} | Error message: {r.text}\n")
self.errorCount += 1
self.proxer = self.proxies()
self.login()
except Exception:
pass
Edit: It doesn't seem to be a issue with the variable checkedCount. I removed it from the code and it still happens
I do not know what kind of data struture is self.username and if the .put() method overwrites already existing entries, but if it doesn't then
the line:
[self.usernames.put(line.strip()) for line in open(f"external/{wordlistInput}")]
Will put the content of f"external/{wordlistInput}" at every iteration in your while True: inside self.usernames without ever clearing it's content.
Also you are not exiting the while, I don't know if its intentional.
This is a shot in the dark since there isn't more information available.

Change value while program is runing

I need a program on raspberry pi, in which I can change the value of a variable delay while the program is running and is not interrupted by any input(). I came up with only one solution: read a value from a text file and change it using another program. But my solution doesn't work very well... When I overwrite a value in a text file, sometimes it happens that the program can't convert it to a float... sometimes it works well and sometimes it prints this error:
ValueError: could not convert string to float: ''
But the value in the text file seems to be fine...
So, this is main program:
def pause():
file = open('delay.txt', 'r')
pause = file.readline()
return pause
delay = float(pause())
while True:
GPIO.output(STEP, GPIO.HIGH)
delay = float(pause())
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
delay = float(pause())
sleep(delay)
And this is the program, which is changing value in the text file:
while True:
rpm = float(input('RPM: '))
delay = (1/(rpm*60))/800
file = open('delay.txt', 'w')
file.write(str(delay))
file.close()
I really can't move with this... I'll be grateful for any advice and help in solving it.
You don't have to stick to my idea with a text file, maybe there is a better solution, but I couldn't think of anything better.
I'd suggest you use threading for this. I've made a small code example for you to get you started:
import threading
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG, filename="thread_output.txt", format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')
running = True
delay = 1
def worker(delay, running):
while running():
logging.debug(1)
sleep(delay())
logging.debug(0)
sleep(delay())
x = threading.Thread(target=worker, args=(lambda: delay, lambda: running))
x.start()
while running:
code = input("""
Make a choice:
1) Set delay
2) quit
""")
code = int(code)
if code == 1:
try:
val = input("Give up the desired delay between 0 and 10 seconds:")
val = int(val)
assert val >= 0 and val <= 10
delay = val
except ValueError:
print("Invalid input! Returning to home menu")
continue
elif code == 2:
running = False
else:
print("invalid option! Returning to home menu")
continue
print("quiting...")
x.join()
The part that helps you here is the fact that you pass the value of delay (and in the example also of running) as a lambda function. This means that every time the value is used, the value refetched. If you then were to change the value of the variable, it would get passed on :)
Hit me up if you have more questions!

In Python how would one wait a specific time while waiting for an image to possibly occur?

More specifically, I have a Sikuli code that works fine for the most part. However, during my 5400 second wait sometimes I have a network connection error that pops a button on the screen I need to click that occurs at no specific time during those 5400 seconds. Also, if that network button occurs and I click it I need to start the code over from the beginning.
I assume I can do a nested While loop waiting for that network connection button to pop up and if it doesn't occur continue with the code but how would I write that? Here's the code currently:
while True:
exists("start.png", 10*60)
click(Pattern("start.png").targetOffset(-1,0))
wait("enter.png", 5)
click(Pattern("enter.png").targetOffset(2,30), 5)
wait(5400)
type(Key.ESC)
exists("leave.png", 5)
click(Pattern("leave.png").targetOffset(-11,0))
#the following if statements could or could not occur and could come in no specific order. This part of the code could be incorrect
if exists("close1.png", 5):
click(Pattern("close1.png").targetOffset(0,1))
elif exists("close2.png", 20):
click("close2.png")
elif exists("close3.png", 20):
click("close3.png")
wait(5)
A suggestion from RaiMan from SikuliX (not tested ;-)
"""
#the following if statements could or could not occur and could come in no specific order.
#This part of the code could be incorrect
if exists("close1.png", 5):
click(Pattern("close1.png").targetOffset(0,1))
elif exists("close2.png", 20):
click("close2.png")
elif exists("close3.png", 20):
click("close3.png")
"""
netError = False
def handler(event):
global netError
netError = True
click(event.getMatch())
onAppear("close1.png", handler)
onAppear("close2.png", handler)
onAppear("close3.png", handler)
while True:
netError = False
observeInBackground(FOREVER)
#exists("start.png", 10*60)
#click(Pattern("start.png").targetOffset(-1,0))
click(wait("start.png", 1))
#wait("enter.png", 5)
#click(Pattern("enter.png").targetOffset(2,30), 5)
click(wait(Pattern("enter.png").targetOffset(2,30), 5)
towait = 5400
while not netError and toWait > 0:
wait(1)
towait -= 1
if netError:
stopObserver()
continue
type(Key.ESC)
#exists("leave.png", 5)
#click(Pattern("leave.png").targetOffset(-11,0))
click(wait(Pattern("leave.png").targetOffset(-11,0), 5)
stopObserver()
wait(5)
Here is some alternative without observer events. I personally find it simpler to work in this way :-).
I used your original code and just replaced wait(5400) with a time based loop that checks for images that might occur.
import time
while True:
exists("start.png", 10*60)
click(Pattern("start.png").targetOffset(-1,0))
wait("enter.png", 5)
click(Pattern("enter.png").targetOffset(2,30), 5)
t0 = time.time()
while (time.time()-t0 < 5400):
#the following if statements could or could not occur and could come in no specific order. This part of the code could be incorrect
if exists("close1.png", 5):
click(Pattern("close1.png").targetOffset(0,1))
elif exists("close2.png", 20):
click("close2.png")
elif exists("close3.png", 20):
click("close3.png")
type(Key.ESC)
exists("leave.png", 5)
click(Pattern("leave.png").targetOffset(-11,0))
wait(5)

Categories

Resources