I'm having trouble with the code below which is asking the user to enter a 'wakeup' time, which the python script will then use to calculate how long until the clock reaches zero. From what I have below, I think that I need to place the tdelta calculation inside the while loop so that it constantly checks for the current time.
At the moment, It seems that tdelta will check for the current time in seconds and then use that same value to run through the while loop. Therefore never ending because it uses the same time over and over again. Should I be using a function inside of the while loop to continuously check for the new value and then evaluate true or false?
from datetime import datetime
import time
now = datetime.now()
hms = "%s:%s:%s" % (now.hour, now.minute, now.second)
ans = input('Enter hour:minute:seconds')
s1 = hms
s2 = ans # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
while tdelta.seconds != 0:
# Use this to see what is happening inside the loop. Here it continuously prints the same time in seconds so is a continuous loop. I need to somehow update the tdelta time.
if tdelta.seconds != 0:
print(tdelta.seconds)
time.sleep(1)
else:
print('time up...do something')
I've tried dozens of variations of the code above but with no luck. I appreciate any tips. Thanks.
Thanks to Padraic Cunningham who provided the missing code to get this working.
Step one: Import timedelta from datetime
Step two: add tdelta -= timedelta(seconds=1) to the first line under the while loop.
from datetime import datetime
from datetime import timedelta
import time
now = datetime.now()
hms = "%s:%s:%s" % (now.hour, now.minute, now.second)
ans = input('Enter hour:minute:seconds')
s1 = hms
s2 = ans # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
while tdelta.seconds != 0:
tdelta -= timedelta(seconds=1)
"""Use this to see what is happening inside the loop. Here it continuously prints the same time in seconds so is a continuous loop. I need to somehow update the tdelta time."""
if tdelta.seconds != 0:
print(tdelta.seconds)
time.sleep(1)
else:
print('time up...do something')
The end result is that the command line will count down to zero and once tdelta IS equal to 0, it will print from the else statement.
Related
I have a Transform job that runs a particular operation I'd like to prevent from occurring more often than some configurable time threshold, that is, it shouldn't run the operation more than once every X minutes.
My code looks like this:
from transforms.api import Input, Output, transform
#transform(
my_output=Output("/my/output/dataset"),
my_input=Input("/my/input/dataset")
)
def my_compute_function(my_input, my_output):
input_df = my_input.dataframe()
# Do some rate-limited processing...
my_call()
We can use two things here:
An incremental "last updated" output
Abort transaction
We'll store the state of when we last ran inside a second dataset output, and if we detect the timestamp we stored there is less than a certain threshold away, we will abort our run.
This code will look like the following:
from transforms.api import Input, Output, transform, incremental
from pyspark.sql import types as T
from datetime import datetime, timedelta
MIN_TIME_ELAPSED = timedelta(minutes=30)
RUN_RECORD_SCHEMA = StructType([ \
StructField("last_run", T.TimestampType(), False),
])
def maybe_get_run_rows(run_record):
last_run_df = run_record.dataframe("previous", schema=RUN_RECORD_SCHEMA)
last_run_rows = last_run_df.collect()
return last_run_rows
def within_run_window(run_record_rows):
current_run_time = datetime.now()
last_run_time = run_record_rows[0][0]
return (current_run_time - last_run_time) > MIN_TIME_ELAPSED:
def record_run(run_record, ctx):
# Record that we ran
new_run_record_df = ctx.spark_session.createDataFrame(
[[current_run_time]],
schema=RUN_RECORD_SCHEMA
)
run_record.set_mode("replace")
run_record.write_dataframe(new_run_record_df)
#incremental(semantic_version=1)
#transform(
my_output=Output("/my/output/dataset"),
run_record=Output("/my/output/run_record"),
my_input=Input("/my/input/dataset")
)
def my_compute_function(my_input, run_record, my_output, ctx):
input_df = my_input.dataframe()
run_record_rows = maybe_get_run_rows(run_record)
if len(run_record_rows) == 0:
# First run ever
# Do some rate-limited processing...
my_call()
record_run(run_record, ctx)
else:
# Not first run ever
if not within_run_window(run_record_rows):
# Built too quickly, do nothing
my_output.abort()
return
else:
# Proceed as normal
my_call()
record_run(run_record, ctx)
You can now configure the MIN_TIME_ELAPSED argument by passing the minimum time elapsed amount you'd like, per the timedelta docs
If for some reason you wanted to only run one time ever, then you could slightly modify your compute function to instead be:
#incremental(semantic_version=1)
#transform(
my_output=Output("/my/output/dataset"),
run_record=Output("/my/output/run_record"),
my_input=Input("/my/input/dataset")
)
def my_compute_function(my_input, run_record, my_output, ctx):
input_df = my_input.dataframe()
run_record_rows = maybe_get_run_rows(run_record)
if len(run_record_rows) == 0:
# First run ever
# Do some rate-limited processing...
my_call()
record_run(run_record, ctx)
else:
# Not first run ever
my_output.abort()
return
I would like to set up a trading bot via Google Cloud to run around the clock.
In Google Cloud Functions I use the Inline editor with runtime Python 3.7.
I have two questions:
1) Main.py section: Here I copied the full code of my Python script (Trading Bot) - see code below for reference (which works well when run as a script in my IDE Spyder).
However, below Google asks to provide a function to execute. However, my code is just a script with no main function. Can I just put at the top of the code e.g.: "def trading_bot(self):" and indent the remaining part below?
While the code as a script copied below works well, if I add the "def trading_bot(self):" at the top in my IDE (Spyder), the code doesnt seem to work properly...How can I make sure the code within the function runs properly, when I call the function from Google Cloud (or from my IDE).
2) Requirements.txt section: Can you provide guidance what exactly I need to put there, i.e. can I look up the dependencies used in my code somewhere? I use Anaconda for distribution, the classes imported for the script are at the top of the script provided below.
Thanks for any help. Glad also for your advice if you think Google Cloud Functions is not the best approach to run a trading bot but it seemed to me to be the simplest solution.
import bitmex
import json
from time import sleep
from bitmex_websocket import BitMEXWebsocket
import logging, time, requests
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from datetime import datetime
import math
from statistics import mean
#-------------------------
#variable
symbol = "XBTUSD"
#standard API connection
api_key = "XXX"
api_secret = "XXX"
#True for testnet
client = bitmex.bitmex(test=False, api_key=api_key, api_secret=api_secret)
#------------------
# Trading algorithm
symbol = "XBTUSD"
ordType = 'Stop'
#starting order quantity
orderQty = 1
leftBars = 6
rightBars = 2
#round to 0.5
def round_to_BTC(n):
result = round(n*2)/2
return result
t=1
while t < 1000000:
time_now = (time.strftime('%H:%M:%S', time.localtime(int(time.time()))))
t_now = time_now[6:8]
t1 = "00"
t2 = "59"
FMT = '%S'
def days_hours_minutes_seconds(td):
return td.days, td.seconds//3600, (td.seconds//60)%60, td.seconds
if t_now == str('00'):
#give 1 second to candlestick to properly close
sleep(1)
elif t_now > str('00') and t_now <= str('59'):
s1 = datetime.strptime(t2, FMT) - datetime.strptime(t_now, FMT)
s1_seconds = days_hours_minutes_seconds(s1)[3]+2
sleep(s1_seconds)
else:
pass
time_now = (time.strftime('%H:%M:%S', time.localtime(int(time.time()))))
print("The time is now: " + time_now)
#most recent swing candles, get highs and lows / #binsizes = {"1m": 1, "5m": 5, "1h": 60, "1d": 1440}
#+1 is the middle bar
totalBars = leftBars + rightBars + 1
swing_candles = client.Trade.Trade_getBucketed(symbol=symbol, binSize="1m", count=totalBars, reverse=True).result()[0]
last_highs = []
last_lows = []
i=0
while i <= (len(swing_candles)-1):
last_highs.append(swing_candles[i]["high"])
last_lows.append(swing_candles[i]["low"])
i += 1
#get the highest high and the lowest low
highest_high = max(last_highs)
lowest_low = min(last_lows)
#check if there are existing positions & orders
if client.Position.Position_get().result()[0] != []:
positions_quantity = client.Position.Position_get().result()[0][0]["currentQty"]
else:
positions_quantity = 0
#check existing orders
buy_orders_quantity = []
sell_orders_quantity = []
orders_quantity = client.Order.Order_getOrders(filter=json.dumps({"open": True})).result()[0]
h=0
while h <= len(orders_quantity)-1:
if orders_quantity[h]["side"] == "Sell":
sell_orders_quantity.append(orders_quantity[h])
elif orders_quantity[h]["side"] == "Buy":
buy_orders_quantity.append(orders_quantity[h])
h += 1
if highest_high == last_highs[rightBars] and positions_quantity == 0:
if buy_orders_quantity == []:
client.Order.Order_new(symbol = symbol, orderQty = orderQty*1, side = "Buy", ordType = 'Stop', stopPx = (highest_high+0.5), execInst ='LastPrice' ).result()
elif buy_orders_quantity != []:
orderID = buy_orders_quantity[0]["orderID"]
client.Order.Order_amend(orderID=orderID, orderQty=orderQty*1, stopPx = (highest_high+0.5)).result()
else:
pass
elif highest_high == last_highs[rightBars] and positions_quantity > 0:
#dont place any additional long
pass
elif highest_high == last_highs[rightBars] and positions_quantity < 0:
if buy_orders_quantity != []:
orderID = buy_orders_quantity[0]["orderID"]
client.Order.Order_amend(orderID=orderID, orderQty=orderQty*2, stopPx = (highest_high+0.5)).result()
else:
client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*2, side = "Buy", ordType = 'Stop', stopPx = (highest_high+0.5), execInst ='LastPrice' ).result()
elif lowest_low == last_lows[rightBars] and positions_quantity == 0:
if sell_orders_quantity == []:
client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*-1, side = "Sell", ordType = 'Stop', stopPx = (lowest_low-0.5), execInst ='LastPrice' ).result()
elif sell_orders_quantity != []:
orderID = sell_orders_quantity[0]["orderID"]
client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-1, stopPx = (lowest_low-0.5)).result()
else:
pass
elif lowest_low == last_lows[rightBars] and positions_quantity < 0:
#dont place any additional shorts
pass
elif lowest_low == last_lows[rightBars] and positions_quantity > 0:
if sell_orders_quantity != []:
orderID = sell_orders_quantity[0]["orderID"]
client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-2, stopPx = (lowest_low-0.5)).result()
else:
client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*-2, side = "Sell", ordType = 'Stop', stopPx = (lowest_low-0.5), execInst ='LastPrice' ).result()
positions_quantity = client.Position.Position_get().result()[0][0]["currentQty"]
buy_orders_quantity = []
sell_orders_quantity = []
orders_quantity = client.Order.Order_getOrders(filter=json.dumps({"open": True})).result()[0]
h=0
while h <= len(orders_quantity)-1:
if orders_quantity[h]["side"] == "Sell":
sell_orders_quantity.append(orders_quantity[h])
elif orders_quantity[h]["side"] == "Buy":
buy_orders_quantity.append(orders_quantity[h])
h += 1
if positions_quantity > 0:
if sell_orders_quantity != []:
orderID = sell_orders_quantity[0]["orderID"]
client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-2).result()
elif positions_quantity < 0:
if buy_orders_quantity != []:
orderID = buy_orders_quantity[0]["orderID"]
client.Order.Order_amend(orderID=orderID, orderQty=orderQty*2).result()
print("Your current position is " + str(positions_quantity))
print("This is iteration: " + str(t))
t += 1
As concerns my second question, I solved it in the following way:
In the command terminal, type: pip freeze > requirements.txt
The file contains all dependencies.
As concerns question 1 I still dont understand what code exactly needs to be put in the section main.py.
Thanks!
Cloud Functions is not an adequate product for your use case. They are mostly used for lightweight calculations or not high resource consuming methods.
The magic of CF consists in that they execute your code whenever you hit the URL that belongs to it. This is important to understand for your question number 1. If you want your function to work, you need to always create a method that accepts the "request" parameter. As it is the information from the HTTP request made when the URL is hit.
You can take a look at this document for reference.
You function should always start like this
from flask #import your dependencies
def my_awesome_function(request):
#Your logic
In this case you should write "my_awesome_function" on the Function to Execute textbox.
You also have to be careful with your resources, as CF have 5 presentations. They differ in CPU and Memory you can read more about this here.
This, among many reasons, you should not use Cloud Functions for your bot. I could recommend you to use a virtual machine, but activities related to use of the Services for cryptocurrency mining without Google's prior written approval are frowned upon and may result in the deactivation of your product as stated in the terms of service.
this is the code in Python, I really don't know how to do this, I am just a beginner and someone can understand my question and help me
def get_float(prompt, low, high):
while True:
prompt = input("Enter monthly investment:")
number= float(input(prompt))
if number > low or number <= high:
is_valid = True
return number
else:
print("Entry must be greater than {low}and less than or equal to {high}")
def main():
get_float(prompt,low,high)
if __name__ == "__main__":
main()
In main, you are passing in the prompt variable into get_float. However, prompt is not defined in main, therefore you are attempting to pass an undefined variable which is not allowed.
In fact, given that get_float reads the prompt from input (and not the value passed in), you do not need to pass prompt into get_float, and prompt can be removed from the function signature.
You cannot pass prompt as a Function argument cause you are reading the value inside the function
def get_float(low, high):
while True:
prompt = input("Enter monthly investment:")
number= float(input(prompt))
if number > low or number <= high:
is_valid = True
return number
else:
print("Entry must be greater than {low}and less than or equal to {high}")
def main():
get_float(200,1000)
if __name__== "__main__":
main()
I was making a game and now I want to see how could pygame know that I am in x of player and y of player.
I have to break in safe, to do that I must stand where it is and stay there for 3 seconds.
problem is even that I managed to alert pygame that I am in area where safe is,
is how could pygame know that I am in safe for 3 sec.
This is non-optimal:
import time
now = time.time()
future = now + 3
while future > now:
#IT DOESNT WORK WELL IN WHILE LOOP TO ALERT YA,
Is there a better solution?
What you could do to "alert" pygame/your code is you could use if statements if your using non-OOP and all you have is a list of coordinates for your player location, or if you do have an object for your player you could pygame.sprite.Sprite as a super class. Here's the solution if your using a coordinate list and not a big class.
loc = [x, y] # Don't run this because it won't understand what x and y are. This is just an example
safe_rect = ( x , y , w , h ) # Using tuple because I assume that the safe doesn't move
while True:
if loc[0] >= safe_rect[0] and # The newlines are for readability
loc[0] < safe_rect[0] + safe_rect[2] and
loc[1] >= safe_rect[1] and
loc[1] < safe_rect[1] + safe_rect[3]:
not_yet_existent_do_something_function() # Performs statements once inside the safe
If you want to include a timer, do this:
import time
loc = [x, y]
safe_rect = ( x , y , w , h )
# Time variables
time = time.time()
time_wanted = time + 3 # 3 seconds after the time is assigned to time
while True:
if loc[0] >= safe_rect[0] and
loc[0] < safe_rect[0] + safe_rect[2] and
loc[1] >= safe_rect[1] and
loc[1] < safe_rect[1] + safe_rect[3]:
if time.time() > time_wanted:
not_yet_existent_do_something_function()
I hope this works for you, if you have a question about what I did please ask me.
I want to write a program that loads data from a JSON database into a Python list of dictionary and adds all of the number of times the mean temperature was above versus below freezing. However, I am struggling to extract information from the database successfully/ I am concerned my algorithim is off. My plan:
1) define a function that loads data from the json file.
2) define a function that extracts information from the file
3) use that extracted information to tally the number of times the temp was above or below freezing
import json
def load_weather_data(): #function 1: Loads data
with open("NYC4-syr-weather-dec-2015.json", encoding = 'utf8') as w: #w for weather
data = w.read()
weather = json.loads(data)
print(type(weather))
return weather
def extract_temp(weather): #function 2: Extracts information on weather
info = {}
info['Mean TemperatureF'] = weather['Mean TemperatureF']#i keep getting a type error here
return info
print("Above and blelow freezing")
weather = load_weather_data()
info = extract_temp(weather)
above_freezing = 0
below_freezing = 0
for temperature in weather: # summing the number of times the weather was above versus below freezing
if info['Mean Temperature'] >32:
above_freezing=above_freezing+1
elif info['mean temperature']<32:
below_freezing = below_freezing +1
print(above_freezing)
print(below_freezing)
If you have any ideas, please let me know! Thank you.
You are trying to extract temperature from the weather list one time before starting the loop when really you should be doing it for each temperature object in the loop. You haven't posted sample data, but I think that weather is a list and you are trying to use it as a dict. Below is a fix with a couple of other changes for tidiness.
import json
# fixed: call with filename so that the function works on other files
def load_weather_data(filename): #function 1: Loads data
with open(filename, encoding = 'utf8') as w: #w for weather
# fixed: fewer steps
return json.load(w)
# fixed: not needed, doesn't simply anything
#def extract_temp(weather): #function 2: Extracts information on weather
# info = {}
# info['Mean TemperatureF'] = weather['Mean TemperatureF']#i keep getting a type error here
# return info
print("Above and blelow freezing")
weather = load_weather_data("NYC4-syr-weather-dec-2015.json")
above_freezing = 0
below_freezing = 0
for temperature in weather: # summing the number of times the weather was above versus below freezing
if info['Mean Temperature'] > 32:
above_freezing += 1
# fixed: capitalized above... so assuming it should be here too
elif info['Mean Temperature'] < 32:
below_freezing += 1
print(above_freezing)
print(below_freezing)