python simple binance bot beginner - binance

I have a simple binance bot for my cryptocurrency trading.
The code is shown below:
from binance.client import Client#from Binance Sir Sam Chardy
from time import sleep
api_key = ''
api_secret = ''
client = Client(api_key,api_secret)
Altcoin=''
Symbol=''
class Balance:
def UsdtBalance(self):
x=client.get_asset_balance(asset='')
x=float(x['free'])
return x
def AltcoinBalance(self):
x=client.get_asset_balance(asset=Altcoin)
x=float(x['free'])
return x
a=Balance()
US=a.UsdtBalance()
AL=a.AltcoinBalance()
while order = False
if US > AL:
x=client.get_historical_klines(symbol=Symbol,interval='1m',start_str='1min ago UTC')
a=float(x[0][1]
d=float(x[0][4]
if a > d and a < 0.997:
print('BUY')
client.order_market_buy(symbol=Symbol,quantity=100,price=d)
else:
pass
if US > AL:
x=client.get_historical_klines(symbol=Symbol,interval='1m',start_str='1min ago UTC')
a=float(x[0][1]
d=float(x[0][4]
if a < d and a > 1.001:
print('SELL')
client.order_market_sell(symbol=Symbol,quantity=100,price=d)
else:
pass
sleep(8)
My problem with this code is that the moment the condition to buy or a condition to sell is satisfied the program will stop and I will run again the code to continue. I want it to continue indefinitely with out my intervention so that it will be truly autonomous.
I will very much appreciate your answers.
Thank you.
#messy code beginner programmer

before your first while begin with
while True:
and it will star over again and again

Try using a websocket and a run_forever() and correct the while loop as described above. Hope this helps

Related

Trying to make a can counter on a PI 4 in python, Strugging with code for two sensors running at the same time

So I work in the beverage industry and I decided to try and make a can counter using a Raspberry PI4. It needs to use two industrial sensors on the GPIO that detect the cans.
Full Disclosure I have just been googling most code and reading when I get errors in terminal to try and fix the issue. I have done some rudimentary C# and C++ programming doing PLC stuff but it's nothing like what i'm trying to do right now. Just some simple statements for conversions and formulas.
I have had it counting via the sensor on a very rudimentary code
import RPi.GPIO as GPIO
import time
GPIN = 16
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIN, GPIO.IN)
counting = 0
while True:
while GPIO.input(GPIN) == 0:
time.sleep(0.1)
counting = counting + 1
print(counting)
while GPIO.input(GPIN) == 1:
time.sleep(0.1)
This counts in the terminal. It is of note I need to count the on and off state with a slight delay to keep accidental double counts from happening. I have even added in a GUI with guizero that makes it count in a window. although currently I cannot replicate that from what I remember working and i foolishly didn't save that as i was trying to get to the next stage, but the rough of it was instead of the print(counting) section in the above code I had the app.display() info.
Problem is I need it to count 2 sensors at the same time, one before the can rejector and one after. So I did some reading and figured I needed to run two (or maybe 3) loops at the same time. as I have 2 sensors that need a constant loop, plus it seems like a need another loop that runs and refreshes the GUI. I got turned into threading and have been trying to implement it as that seems like what I want but haven't been able to make heads or tails of it. I can get the GUI to display, but the sensors don't read. If I switch back to my simple code it counts away. Im having trouble meshing the two together.
import threading
from guizero import App, Text, PushButton
import RPi.GPIO as GPIO
import time
GPIN1 = 16
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIN1, GPIO.IN)
GPIN2 = 15
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIN2, GPIO.IN)
counting1 = 0
counting2 = 0
counting3 = counting1 - counting2
def sensor1():
global counting1
while GPIO.input(GPIN1) == 0:
time.sleep(0.1)
counting1 = counting1 + 1
while GPIO.input(GPIN1) == 1:
time.sleep(0.1)
def sensor2():
global counting2
while GPIO.input(GPIN2) == 0:
time.sleep(0.1)
counting2 = counting2 + 1
while GPIO.input(GPIN2) == 1:
time.sleep(0.1)
x = threading.Thread(target=sensor1)
y = threading.Thread(target=sensor2)
x.start()
y.start()
while True:
app = App(title="Can Count")
message = Text(app, text="Total")
message = Text(app, text=(counting1))
message = Text(app, text="Rejected")
message = Text(app, text=(counting3))
app.display()
I'm just a bit stumped I'm sure my way isn't the best way to do this, any advice, tips or pointers in the right direction would be appreciated. I'm trying to crash course youtube python tutorials on the side but I am still coming up short.
It seems like I can get the display to show updates if i close the window via the x it restarts the window and shows the update but I have tried a few different things with guizero using a def text(): above that code and text.repeat(10, text) thinking this would redraw the screen but that doesn't work or breaks the gui or the code.
Also I know I call PushButton and don't use it, but the end goal will have a simple reset the counter button.. Just haven't got there yet.

How to use multipule functions for this?

I want to have a function and a input work together to create something like this:
import time, sys
def sprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
This last code is what I want to get to work. I want it to take input while performing the sprint function:
pas=input(sprint("LOGIN: ")
I think I know what you're looking for. There's an easy way to get around your problem.
import time
import sys
def sprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
pas = sprint("LOGIN: ")
pas = input("")
It will act exactly the same way as before too. All I did was separate the sprint and input because they cannot coexist. However, doing sprint and THEN asking for input will work.
Your solution is bizarre (the one proposed by Johnny is better), but if you insist on it, make your function return an empty string that would be used as a parameter to input():
def sprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
return ""

program keeps executing first if condition

I'm trying to build a speech recognition app in python,everything works fine but,when I'm executing program the first If condition always executes no matter what the input is.
import speech_recognition as sr
from gtts import gTTS
import os
from google_speech import Speech
import webbrowser
def speech():
while True:
try:
with sr.Microphone() as source:
r = sr.Recognizer()
audio = r.listen(source,timeout=3, phrase_time_limit=3)
x = r.recognize_google(audio)
print(x)
if 'hello' or 'Hello' or 'Hi' in x:
speech=Speech('Hello,How are you?','en')
speech.play()
print('Input: ',x)
print('output: Hello,How are you?',)
elif 'omkara' or 'Omkara' in x:
speech=Speech('Playing Omkara song on Youtube','en')
speech.play()
webbrowser.get('/usr/bin/google-chrome').open('https://youtu.be/NoPAKchuhxE?t=21')
except sr.UnknownValueError:
print("No clue what you said, listening again... \n")
speech()
if __name__ == '__main__':
print('Executine Voice based commands \n')
speech()
here is my code I have used while to continuously repeat the program but,In first if condition,it should only be executed when there is 'Hello','Hi' in input. First time I say 'Hi',if is valid then,but when the program loops again with another input like 'how are you' it still executes first IF condition,can anyone please help me with this.Thank you.
You use or in wrong way there. Try to use this code:
if any(check in x for check in ('hello', 'Hello', 'Hi')):
The problem occurs because if 'Hello' becomes True instantly. Once you have a condition which is true, it will always go to if condition.
You can try to check this using bool('Hello'). The solution is to check each string separately.
if ('hello' in x) or ('Hello' in x) or ('Hi' in x):
something

So, i've been trying to make a python program to take a time.sleep() input so user puts in the number then it asks which website you wanna open

import webbrowser
import time
while True:
num = input("In How Much Time Would You Like To Open?: ")
value = float(num)
time.sleep(num)
sites = input("What website would you like to open?: ")
visit = "http://{}".format(sites)
webbrowser.open(visit)
why won't this work? try it yourself and see the mistake I have really no idea please help!
In python3 input() is returning a string. The program is converting this to a float, but then does not use it, still calling time.sleep(num). The question does not include the error message, but it probably was:
TypeError: an integer is required (got type str)
Simply using the float the code makes will fix it
import webbrowser
import time
while True:
sites = input("What website would you like to open?: ")
num = input("In How Much Time Would You Like To Open?: ")
value = float(num)
time.sleep(value) # <<-- HERE - was time.sleep(num)
visit = "http://{}".format(sites)
webbrowser.open(visit)
EDIT: Changed to ask for the website first

Python Threading Issue, Is this Right?

I am attempting to make a few thousand dns queries. I have written my script to use python-adns. I have attempted to add threading and queue's to ensure the script runs optimally and efficiently.
However, I can only achieve mediocre results. The responses are choppy/intermittent. They start and stop, and most times pause for 10 to 20 seconds.
tlock = threading.Lock()#printing to screen
def async_dns(i):
s = adns.init()
for i in names:
tlock.acquire()
q.put(s.synchronous(i, adns.rr.NS)[0])
response = q.get()
q.task_done()
if response == 0:
dot_net.append("Y")
print(i + ", is Y")
elif response == 300:
dot_net.append("N")
print(i + ", is N")
tlock.release()
q = queue.Queue()
threads = []
for i in range(100):
t = threading.Thread(target=async_dns, args=(i,))
threads.append(t)
t.start()
print(threads)
I have spent countless hours on this. I would appreciate some input from expedienced pythonista's . Is this a networking issue ? Can this bottleneck/intermittent responses be solved by switching servers ?
Thanks.
Without answers to the questions, I asked in comments above, I'm not sure how well I can diagnose the issue you're seeing, but here are some thoughts:
It looks like each thread is processing all names instead of just a portion of them.
Your Queue seems to be doing nothing at all.
Your lock seems to guarantee that you actually only do one query at a time (defeating the purpose of having multiple threads).
Rather than trying to fix up this code, might I suggest using multiprocessing.pool.ThreadPool instead? Below is a full working example. (You could use adns instead of socket if you want... I just couldn't easily get it installed and so stuck with the built-in socket.)
In my testing, I also sometimes see pauses; my assumption is that I'm getting throttled somewhere.
import itertools
from multiprocessing.pool import ThreadPool
import socket
import string
def is_available(host):
print('Testing {}'.format(host))
try:
socket.gethostbyname(host)
return False
except socket.gaierror:
return True
# Test the first 1000 three-letter .com hosts
hosts = [''.join(tla) + '.com' for tla in itertools.permutations(string.ascii_lowercase, 3)][:1000]
with ThreadPool(100) as p:
results = p.map(is_available, hosts)
for host, available in zip(hosts, results):
print('{} is {}'.format(host, 'available' if available else 'not available'))

Resources