Gdax Candle Stick using Python - python

Anyone here with an idea of how to loop a constantly moving variable within a timeframe of 60 seconds to check it's highest, medium, lowest and average of the three?
Then creating more of a json objects of the past minutes
Tried using timer for custom threading and seems that it is not working for me
Below is my code. Kindly assist.
import sys, getopt
import time
from threading import Timer
import main.botlog as botlog
from main.settings import auth_client,product
class BotCandlestick(object):
def __init__(self, period=60, open=None, close=None, high=None, low=None, priceAverage=None):
self.current = None
self.open = open
self.close = close
self.high = high
self.low = low
self.startTime = time.time()
self.period = period
BotLog = botlog.BotLog
self.output = BotLog()
self.priceAverage = priceAverage
def tick(self, price):
# while True:
self.current = float(price)
if (self.open is None):
self.open = self.current
print(self.open)
if ((self.high is None) or (self.current > self.high)):
self.high = self.current
print(self.high)
if ((self.low is None) or (self.current < self.low)):
self.low = self.current
print(self.low)
if (time.time() >= (self.startTime + self.period)):
self.close = self.current
self.priceAverage = (self.high + self.low + self.close) / float(3)
print(self.priceAverage)
self.output.log(
"Open: " + str(self.open) + " Close: " + str(self.close) + " High: " + str(self.high) + " Low: " + str(
self.low) + " Current: " + str(self.current))
def isClosed(self):
if (self.close is not None):
return True
else:
return False
def main():
price = auth_client.get_product_ticker(product)
prices = float(price.get('price'))
price = BotCandlestick()
d = price.tick(prices)
t = Timer(10.0, d)
t.start()
if __name__ == '__main__':
main()

I did figure out a universal way to go about this problem. Kindly find the code below. It is more of a universal code to find value change within x time.
import gdax
import time
public = gdax.PublicClient()
while True:
endtime = time.time() + 60
x = []
while time.time() < endtime:
ticker = public.get_product_ticker('BTC-USD')
ticker = ticker['price']
ticker = float(ticker)
x.append(ticker)
change = ((x[0]-x[-1])/x[-1])
print(ticker)
time.sleep(1)
print("Open: {} High: {} Low: {} Close: {} Change: {}%".format(x[0], max(x), min(x), x[-1], change*100))
time.sleep(0)

Related

Python: NameError: global name 'searcher' is not defined

I'm pretty new to python and I'm trying to make a program for a class which should be able to run in the command line with argv attributes in order to find a certain target integer in a file of multiple integers. I am having issues with how my searcher class is being defined, was wondering where I've made a mistake, code is as follows:
import sys
import string
import math
import time
print('cmd entry:', sys.argv)
class searcher(object):
size = ""
def __init__(self, size):
pass
def get(self, f, target):
if sys.agrv != null:
f = open(sys.argv[1], 'r')
target = sys.argv[2]
print('target:', target)
else:
print('no file or target')
pass
def linearsearch(self, f, target, tic, toc, elapsed):
tic = time.perf_counter()
for line in f:
if target in line:
tok = time.perf_counter()
elapsed = toc - tic
return line,elapsed
pass
def binarysearch(self, f, target, tic, toc, elapsed, low, high):
low = 0
high = len(f) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# If t is greater, ignore left half
if arr[mid] < target:
low = mid + 1
# If t is smaller, ignore right half
elif arr[mid] > target:
high = mid - 1
# means t is present at mid
else:
return mid
# If we reach here, then the element was not present
return -1
pass
def output(self, line, elapsed):
print('line:', line)
print('elapsed:', elapsed)
pass
def main(args):
s = searcher(1000)
f = open(sys.argv[1], 'r')
target = sys.argv[2]
s.get(f, target)
s.linearsearch(f, target, tic, toc, elapsed)
s.binarysearch(f, target, tic, toc, elapsed, low, high)
s.output(line, elapsed)
if __name__ == '__main__':
main(sys.argv)

python class attribute not updating when updated in a function

I have a stopwatch of sorts going in the background using threading, and while it's updating the global variable, it doesn't change the output of my class attribute.
This is what I have:
import time
from threading import Thread
s = 0
m = 0
h = 0
stopped = False
def stopwatch():
global s
global m
global h
global stopped
while stopped == False:
s = s + 1
if s >= 60:
s = 0
m += 1
if m >= 60:
m = 0
h += 1
time.sleep(1)
class foo:
name = 'shirb'
time = str(h) + 'h' + str(m) + 'm' + str(s) +'s'
Thread(target = stopwatch).start()
input('press enter to stop the stopwatch')
stopped = True
print('Name: ' + foo.name + '\nTime: ' + foo.time)
Lets say I wait for one minute and 34 seconds.
The output should be:
press enter to stop the stopwatch
Name: shirb
Time: 0h1m34s
But this is what it actually puts out:
press enter to stop the stopwatch
Name: shirb
Time: 0h0m0s
I have no idea what is causing it to not update. When I try to print the variable itself with "print(s)" i get the correct amount of seconds, so there is something wrong with the class attribute that I don't know how to fix.
Class variables are initialized at module load time, so foo.time is set when h, m, and s, are zero. If you make it a class method, however, you will get the right result:
class foo:
name = 'shirb'
#classmethod
def cls_time(cls):
return str(h) + 'h' + str(m) + 'm' + str(s) +'s'
Thread(target = stopwatch).start()
input('press enter to stop the stopwatch')
stopped = True
print('Name: ' + foo.name + '\nTime: ' + foo.cls_time())
You could perhaps use just the one class:
import time
from threading import Thread
class stopwatch:
def __init__(self):
self.s = 0
self.m = 0
self.h = 0
self.stopped = False
self.name = "shirb"
def begin(self):
while self.stopped is False:
self.s += 1
if self.s >= 60:
self.s = 0
self.m += 1
if self.m >= 60:
self.m = 0
self.h += 1
time.sleep(1)
def get_time(self):
return str(self.h) + "h" + str(self.m) + "m" + str(self.s) + "s"
s = stopwatch()
Thread(target=s.begin).start()
input("press enter to stop the stopwatch")
s.stopped = True
print("Name: " + s.name + "\nTime: " + s.get_time())
This solves the issue.

MPI with class & for-loop

I want to use MPI for parallel processing the calculation of hamiltonian paths in a graph.
So, I achieved this:
from mpi4py import MPI
import random,time
comm = MPI.COMM_WORLD
my_rank = comm.Get_rank()
p = comm.Get_size()
numOfNodes = 10
numOfProblems = 11
class Graph:
def __init__(self, numOfNodes):
if numOfNodes > 0:
self.numOfNodes = numOfNodes
else:
print("Error")
def calculateMaxPairs(self):
self.maxPairs = self.numOfNodes*(self.numOfNodes - 1)//2
def generatePairs(self):
self.calculateMaxPairs()
self.pairs = []
startRange = self.numOfNodes
endRange = (self.numOfNodes - 10)*3 + 18
numOfPairs = random.randint(startRange, endRange)
while len(self.pairs) != numOfPairs:
try:
startNode = random.randint(1, self.numOfNodes)
endNode = random.randint(1, self.numOfNodes)
if startNode == endNode:
raise ValueError
except ValueError:
pass
else:
pair = (startNode, endNode)
invertedPair = (endNode, startNode)
if pair not in self.pairs and invertedPair not in self.pairs:
self.pairs.append(pair)
self.hamiltonianPath = []
def generatePathLink(self):
self.graphLink = {}
for x in self.pairs:
x = str(x)
splitNode = x.split(', ')
a = int(splitNode[0][1:])
b = int(splitNode[1][:-1])
try:
if b not in self.graphLink[a]:
self.graphLink[a].append(b)
except KeyError:
self.graphLink[a] = []
self.graphLink[a].append(b)
finally:
try:
if a not in self.graphLink[b]:
self.graphLink[b].append(a)
except KeyError:
self.graphLink[b] = []
self.graphLink[b].append(a)
finally:
pass
def findPaths(self, start, end, path = []):
path = path + [start]
if start == end:
return [path]
if start not in self.graphLink:
return []
paths = []
for node in self.graphLink[start]:
if node not in path:
newpaths = self.findPaths(node, end, path)
for newpath in newpaths:
paths.append(newpath)
if (len(newpath) == self.numOfNodes):
self.hamiltonianPath = newpath
raise OverflowError
return paths
def exhaustiveSearch(self):
try:
allPaths = []
for startNode in self.graphLink:
for endNode in self.graphLink:
newPaths = self.findPaths(startNode, endNode)
for path in newPaths:
if (len(path) == self.numOfNodes):
allPaths.append(path)
return allPaths
except OverflowError:
return self.hamiltonianPath
else:
pass
def isHamiltonianPathExist(self):
time_start = time.clock()
self.generatePathLink()
if len(self.graphLink) != self.numOfNodes:
time_elapsed = (time.clock() - time_start)
return [[], time_elapsed]
else:
result = self.exhaustiveSearch()
time_elapsed = (time.clock() - time_start)
if len(result) == 0:
print("There isn't any Hamiltonian Path.")
else:
print("Computing time:", round(time_elapsed, 2), "seconds\n")
return [result, time_elapsed]
comm.send(result, dest=0)
yes = 0
no = 0
total_computing_time = 0
for x in range(1, numOfProblems + 1):
if my_rank !=0:
graph = Graph(numOfNodes)
graph.generatePairs()
output = graph.isHamiltonianPathExist()
else:
for procid in range(1,p):
result = comm.recv(source=procid)
time_elapsed = comm.recv(source=procid, tag=12)
total_computing_time += time_elapsed
if len(result) == 0:
no += 1
else:
yes += 1
print("Have Hamiltonian Path:", yes)
print("Don't Have Hamiltonian Path:", no)
print("Total computing time for %s problems in %s processes: %s s"%(numOfProblems, p, str(round(total_computing_time, 2))))
As you can see in this script, there's two sections.
The first one is where we will generate a Graph and calculate the hamiltonian paths.
The second one is where we tell the script to run this graph generating script in parallel in multiple processors.
The problem here is that it generates the graph and calculate paths in every processor, not dividing the job between them.
Where am I doing wrong?

How to update tkinter labels that are stored in a list, using a button?

I need to update a list of labels that could be any size. All questions I've found already dealt in single labels instead of lists. I tried to extrapolate those answers to my problem and have not been successful.
I tried associating the list of labels with a list of StringVars and was not successful.
import nation
import game_time
def main():
Ven = nation.Nation("Venice", 1500000, 60, 5)
Mil = nation.Nation("Milan", 1250000, 10, 5)
Flo = nation.Nation("Florence", 7500000, 90, 5)
game_time.pass_time(1)
print ("test")
for n in nation.Nation._registry:
print (n.get_pop_stats())
if __name__ == '__main__':
main()
#NATION
name = ""
population = 0
econ_value = 0
owned_land = 0
GROWTH = .002
MONTH_GROWTH = .002/12
current_growth = 0
expected_growth = 0;
class Nation:
_registry = []
def __init__(self, name = "dummy", population = -1, econ_value = -1, owned_land = -1):
self.name = name
self.population = population
self.econ_value= econ_value
self.owned_land = owned_land
self._registry.append(self)
def get_pop_stats(self):
return "Nation: " + self.name + " Population: " + str(self.population) + " Current Growth: " + str(self.current_growth) + " Expected Growth: " + str(self.expected_growth) + "\n"
#TIME
import nation
GROWTH = .002
MONTH_GROWTH = .002/12
def pass_time(x):
while x > 0:
for p in nation.Nation._registry:
temp = p.population
p.population += p.population*(p.econ_value/100)*MONTH_GROWTH
p.current_growth = p.population - temp
p.expected_growth = p.population*(p.econ_value/100)*MONTH_GROWTH
x -= 1;
#ERROR
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.do_labels()
ran = 0
def do_labels(self):
pop_text = []
pop_stats = []
time = tk.Button(self, text="PASS TIME", fg="red", command= lambda: self.press())
time.pack(side="bottom")
i = 0
for n in nation.Nation._registry:
pop_text.append(tk.StringVar(value = n.get_pop_stats()))
pop_stats.append(tk.Label(self, textvariable = pop_text[i], command = print("initializing label")))
pop_stats[i].pack(side="top")
i+=1
self.ran = 1
self.pack()
root.update()
def press(self):
print("this works")
game_time.pass_time(1)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
My bad, Here is the nation class, required to run the code.
Expected: Numbers in the labels update.
Actual: Nothing happens in the window, but the button successfully prints in the console.

loop instance method with list elements

I am trying to write a program (API testing) to loop through instance methods in a class. One of the methods "get_one_sale_license" has a variable "self.sale_sgid_in_test" I need to assign this variable each element in the list "sale_list_final" .The variable is used in the instance method as well as the main function. I put a for loop outside the class and it works fine with the output( this is modified part of a single file from the application using framework).
However, I want to remove the loop wrapping the class and try in a more pythonic way.
import json
from datetime import *
from N import NSession
from N import NArgParser
from i_data_provider import iDataProvider
sale_list = open("sales.txt").readlines()
sale_list_final = [s.rstrip() for s in sale_list]
tests_list = open("tests.txt").readlines()
tests_list_final = [t.rstrip() for t in tests_list]
cnt=0
cnt2=0
cnt3=0
cnt6=0
cnt11=0
for i in sale_list_final:
class iDeployChecks:
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
# self.sale_sgid_list = []
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
def get_all_saleable_sales(self):
global cnt2
if cnt2 == 0:
self.i_session.get_sale_seller_info()
self.logger.info('SUCCESS..... Get all sales api\n')
cnt2 += 1
def get_all_sale_dashboard(self):
global cnt6
if cnt6 == 0:
self.i_session.get_All_sale()
self.logger.info('SUCCESS..... Get all sales on dashboard api\n')
cnt6 += 1
def get_current_user_sale_dashboard(self):
global cnt11
if cnt11 == 0:
self.i_session.get_current_user_sale()
self.logger.info('SUCCESS..... Get current sales on dashboard api\n')
cnt11 += 1
def get_one_sale_license(self):
self.logger.info('Getting sale details from:')
self.sale_sgid_list1 = [item.get('salesgid') for item in self.i_session.get_sale_seller_info()]
#self.sale_sgid_list =[item.get('salesgid') for item in self.i_session.get_sale_seller_info() if item.get('salesgid') == i]
print " for sale " + str(i)
self.sale_sgid_in_test = ''.join(i)
self.logger.info('\n')
self.logger.info('Get License for sale with sale sgid {}'.format(self.sale_sgid_in_test))
self.i_session.get_sale_license(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... Get license api\n')
def get_weekly_stats_count(self):
global cnt
if cnt == 0:
self.i_session.get_weekly_statistics()
self.logger.info('SUCCESS..... Weekly statistics api\n')
cnt += 1
def get_sconfig_value_count(self):
self.i_session.get_sconfig_value(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... sconfig api\n')
def main(self):
start = datetime.utcnow()
# check if the method in the list is present in the class, if yes run it.
for j in tests_list_final:
k = "self." + j + "()"
l= [x.strip() for x in j.split(',')]
m= "self."+l[0]+"(self,year)"
n= "self."+l[0]+"(self,year,month)"
if k == str("self.get_all_saleable_sales()"):
if cnt2 == 0:
self.logger.info('Get All sales')
self.get_all_saleable_sales()
self.logger.info('checking if sale with GSID ' + i + ' exists')
if i not in str(self.i_session.get_sale_seller_info()):
print "the sale with GSID " + i + " does not exist !!"
end1 = datetime.utcnow()
self.logger.info('i health check completed in {} seconds.'.format((end1 - start).seconds))
return
else:
print "sale exists !!"
continue
elif k == str("self.get_one_sale_license()"):
self.get_one_sale_license()
continue
elif k == str("self.get_sale_node_status_value()"):
try:
self.logger.info('Get sale node status for sale sgid {}'.format(self.sale_sgid_in_test))
self.get_sale_node_status_value()
except Exception as e: print e
else:
global cnt3
if (cnt3==0):
print '\n'
print " The testcase " +k + "test does not exist,please recheck test name !!"
print '\n'
cnt3 +=1
end = datetime.utcnow()
self.logger.info('IBDL health check completed in {} seconds.'.format((end - start).seconds))
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
iDeployChecks(args.badge, args.environment).main()
Remove the loop and include in the init
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
self.sale_sgid_list = [i for i in sale_list_final]
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
Then loop for the same list element while calling the main
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
for i in sale_sgid_list:
iDeployChecks(args.badge, args.environment,i).main()

Categories

Resources