FinexApi : Keyprice should be a decimal number, e.g. "123.456" - python

I'm trying to edit a simple code for automated put and take action on bitfinex market using FinexApi.
I get this error while performing a subtraction
Keyprice should be a decimal number, e.g. "123.456"
this is the code
#!/usr/bin/env python
#Places a put and take above and below current market price
import FinexAPI
diff = 0.00000150 #The amount above or below market price you want
ticker = FinexAPI.ticker()
available = float(FinexAPI.balances()[2]["available"])
ask = float(ticker["ask"])
amount = 1 #Amount of XRP to place orders
marketPrice = ticker["last_price"]
buyPrice = float(marketPrice) - diff
sellPrice = float(marketPrice) + diff
print FinexAPI.place_order(str(amount), str(buyPrice), "buy", "exchange limit")
print FinexAPI.place_order(str(amount), str(sellPrice), "sell", "exchange limit")
I get error on:
print FinexAPI.place_order(str(amount), str(buyPrice), "buy", "exchange limit")
Keyprice should be a decimal number, e.g. "123.456"
Let's assume marketPrice is 0.00003500
I would like the code to make a buy order at marketPrice - diff ( 0.00003500 - 0.00000150 ) and a sell order at marketPrice + diff ( 0.00003500 + 0.00000150 )
but I keep getting the same error.
I tried to put the diff number inside " ", I tried using decimal, I tried a few bunch of things but I got other errors or no solution at all.
I'm quite noobish at python, can someone help me and tell me what am I doing wrong, or how to fix it?
Thank you.

Related

Function returning different result despite the same inputs in Python

Here is my function that uses the Poloniex Exchange API. It gets a dict of asks (tuples of price and amount) and then calculates the total amount of BTC that would be obtained using a given spend.
But running the function several times returns different amounts despite the dict of asks and spend remaining the same. This problem should be replicable by printing "asks" (defined below) and the function result several times.
def findBuyAmount(spend):
#getOrderBook
URL = "https://poloniex.com/public?command=returnOrderBook&currencyPair=USDT_BTC&depth=20"
#request the bids and asks (returns nested dict)
r_ab = requests.get(url = URL)
# extracting data in json format -> returns a dict in this case!
ab_data = r_ab.json()
asks = ab_data.get('asks',[])
#convert strings into decimals
asks=[[float(elem[0]), elem[1]] for elem in asks]
amount=0
for elem in asks: #each elem is a tuple of price and amount
if spend > 0:
if elem[1]*elem[0] > spend: #check if the ask exceeds volume of our spend
amount = amount+((elem[1]/elem[0])*spend) #BTC that would be obtained using our spend at this price
spend = 0 #spend has been used entirely, leading to a loop break
if elem[1]*elem[0] < spend: #check if the spend exceeds the current ask
amount = amount + elem[1] #BTC that would be obtained using some of our spend at this price
spend = spend - elem[1]*elem[0] #remainder
else:
break
return amount
If the first ask in the asks dict was [51508.93591717, 0.62723766] and spend was 1000, I would expect amount to equal (0.62723766/51508.93591717) * 1000 but I get all kinds of varied outputs instead. How can I fix this?
You get all kinds of varied outputs because you're fetching new data every time you run the function. Split the fetch and the calculation into separate functions so you can test them independently. You can also make the logic much clearer by naming your variables properly:
import requests
def get_asks(url="https://poloniex.com/public?command=returnOrderBook&currencyPair=USDT_BTC&depth=20"):
response = requests.get(url=url)
ab_data = response.json()
asks = ab_data.get('asks', [])
#convert strings into decimals
return [(float(price), qty) for price, qty in asks]
def find_buy_amount(spend, asks):
amount = 0
for price, qty in asks:
if spend > 0:
ask_value = price * qty
if ask_value >= spend:
amount += spend / price
spend = 0
else:
amount += qty
spend -= ask_value
else:
break
return amount
asks = get_asks()
print("Asks:", asks)
print("Buy: ", find_buy_amount(1000, asks))
Your math was wrong for when the ask value exceeds remaining spend; the quantity on the order book doesn't matter at that point, so the amount you can buy is just spend / price.
With the functions split up, you can also run find_buy_amount any number of times with the same order book and see that the result is, in fact, always the same.
The problem is in your "we don't have enough money" path. In that case, the amount you can buy does not depend on the amount that was offered.
if elem[1]*elem[0] > spend:
amount += spend/elem[0]

How to convert time written "h.mm" to decimal form with Python?

I prompt the user to input what time they start and finish their job. Then I need to calculate what they will earn (given a 97 currency/hour salary). The answer should also not have any decimals (so it should be rounded off). I can't seem to get it to work though.
As shown below, I tried taking the difference between the two inputs from the user and then splitting them to hours and minutes. After that just doing the calculations.
difference = round(float(finishing_time)-float(start_time), 2)
hours, minutes = str(difference).split(".")
salary_hours = int(hours)*97
salary_minutes = int(minutes)//60*97
salary = salary_hours + salary_minutes
So if start_time = 8.30 and finishing_time = 11.15 the salary should be 267, but I get 291 currency.
A couple of things to be careful of, is the rounding off that occurs at every level, which also occurs when you do math by hand and pencil! There is a reason why when you perform calculations one typically does the rounding off when the entire calculation has been performed otherwise one would come up with a vastly different answer as you pointed out.
I'd tackle this perhaps by doing something like this
from datetime import datetime
# quick way to generate a datetime object with start time would be like
start_time = datetime.now()
# replace the hours and minutes you want in your case its
start_time = start_time.replace(hour=8, minute=30)
end_time = start_time.replace(hour=11, minute=15)
# calling replace returns a new distinct datetime object
def calculate_salary(start_time, finish_time, pay_rate):
# will be in seconds
delta_seconds = finish_time - start_time
# convert to hours
hours_worked = (delta_seconds.seconds) / 3600
# calculate pay
pay = hours_worked * pay_rate
return pay
In this case calling the function gives a value of
In [1]: calculate_salary(start_time, end_time, 97)
Out[1]: 266.75
While i dont advocate doing calculations on time without a time module. I assume you know what your doing and that your calculations are simple I.E they wont rolle over midnight and the finish time will always be greater than the start time and finish on the same day. With that in mind the following code should produce your result without using a datetime module. However like #william bright answer, a datetime module would be my prefernce for code like this.
def get_hours(time_string):
time_split = time_string.split(".")
whole_hours = int(time_split[0])
fraction_hours = int(time_split[1]) / 60
return whole_hours + fraction_hours
start_time=input("start time: ")
finish_time=input("finish_time: ")
total_hours = get_hours(finish_time)-get_hours(start_time)
salary = total_hours*97
print(round(salary))
OUTPUT
start time: 8.30
finish_time: 11.15
267
So, my bad for perhaps being unclear in my statement, but since this is a work in progress for the next couple weeks/months, what I came up with was the following:
starting_time = input("At what time did you start working? ")
finishing_time = input("At what time did you finish working? ")
hours1, minutes1 = starting_time.split(".")
hours2, minutes2 = finishing_time.split(".")
minutes1 = float(minutes1)/60
starting_time_new = float(hours1)+minutes1
minutes2 = float(minutes2)/60
finishing_time_new = float(hours2)+minutes2
salary = round((finishing_time_new-starting_time_new)*97)
print("Started working at:",b)
print("Stopped working at:",s)
print("Your salary is",salary,"currency.")
The solution from where I started was to just focus on changing the minutes to the correct decimals instead of focusing on the hours too.
I am well aware that it is far from perfect, in fact, it is probably really bad. However, I am new to programming in Python and taking a course to be better.

Whats wrong with my python program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
tip and tax calculator
bill = price + tax + tip
price = raw_input("What is the price of the meal")
tax = price * .06
tip = price * 0.20
what is wrong with my code
I have tried everything
please answer and get back to me
a few things.
bill = price + tax + tip #You can't add up these values BEFORE calculating them
price = raw_input("What is the price of the meal") #raw_input returns a string, not a float which you will need for processing
tax = price * .06 #So here you need to do float(price) * .06
tip = price * 0.20 #And float(price) here as well.
#Then your " bill = price + tax + tip " step goes here
First of all, you can't use variables that you haven't defined: in your code your are using bill = price + tax + tip but your program doesn't even know what price, tax and tip are yet, so that line should be at the end of the code, after you've asked the price and calculated tax and tip.
Then, you have raw_input, this function returns a string, if you want to convert it to a decimal number that you can multiply and add (float) you can use price = float(raw_input("what is the price of the meal"))
Correct that two things and it should work...
Heres a couple of things wrong with the code:
You're trying to calculate the total before some variables have been defined.
The raw_input function returns a string so you can't do proper mathematical calculations before you coerce it into an integer.
In calculate the tips/tax you should use a float with the whole number 1(1.20) to take the whole value of the bill + 20%.
Below is a code snippet that should work how you want and give you something to think about on how to pass dynamic values into the modifiers within the calculate_bill function for custom tip floats and custom tax floats:
def calculate_bill(bill, bill_modifiers):
for modifier in bill_modifiers:
bill = modifier(bill)
return bill
def calculate_tip(bill, percentage=1.20):
return bill * percentage
def calculate_tax(bill, percentage=1.06):
return bill * percentage
if __name__ == '__main__':
bill = int(input("What is the price of the meal: "))
total_bill = calculate_bill(bill, [calculate_tip, calculate_tax])
print(total_bill)

Python car sales code issue

Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))

How do I get multiple user inputs in python?

Hi I got the following problem, I'm trying to build a program that reads a txt file that contains lines with name of fruits and their respective base prices as the following example:
apple $ 2.00
pearl $ 4.00
guava $ 2.50
and so it goes on.
Yesterday I had some help with people here and I've learned how to make python recognize their prices as a number instead of string, and i was able to multiply their values by one number that was asked to the user. Now I want to make this in a such way that I'm able to take each one of those prices and multiply them for different numbers (one different number for each price) that will be asked for the user to choose.
So far, with the help that I got yesterday I've done this:
print "this program will calculate the total price of the fruits"
y = input('insert a value = ')
with open('fruits.txt') as f:
for line in f:
name, price = line.rstrip().split('$')
price = float(price)
cost = price * (0.76+y)
tcost = cost + price
print name, tcost
Any ideas how to do this?
mult_by = int(raw_input('gimme a number for something: '))
try and familiarize yourself with the basic built in functions, should be helpful.
http://docs.python.org/library/functions.html

Categories