get_balance

This commit is contained in:
Nicolás Sánchez 2024-12-02 19:41:02 -03:00
parent 6115b1460e
commit 90dc1b1a43
4 changed files with 61 additions and 14 deletions

View File

@ -1,3 +1,6 @@
2024.12.02:
. New endpoint: /get_balance.
2024.12.01:
. Added "generated_at" entry: When generating a config file, the generated timestamp is saved in the config file.
. If the switch price is lower than the next SO price, it displays it in green instead of the next SO price.

41
main.py
View File

@ -22,7 +22,7 @@ In case the permissions of the certificate changes, reset them this way:
# ll /etc/letsencrypt/
'''
version = "2024.12.01"
version = "2024.12.02"
'''
Color definitions. If you want to change them, check the reference at https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
@ -1097,7 +1097,7 @@ def get_log_list():
GET request
Parameters:
None
coin: str
'''
if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
@ -1105,6 +1105,21 @@ def get_log_list():
return jsonify({'Error': 'API key invalid'}), 401
@base_api.route("/get_balance", methods=['GET'])
def get_balance():
'''
GET request
Parameters:
coin: str
'''
if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
coin = request.args.get("coin")
return unwrapped_get_balance(coin)
return jsonify({'Error': 'API key invalid'}), 401
@base_api.route("/get_deals_cache", methods=['GET'])
def get_deals_cache():
'''
@ -2121,6 +2136,28 @@ def unwrapped_reload_safety_order(base,quote):
return jsonify({"Error": "Safety order couldn't be reloaded"})
def unwrapped_get_balance(coin):
'''
Returns the balance of a given coin.
Parameters:
coin (str): The coin to get the balance of.
Returns:
dict: A dictionary containing the balance of the coin.
'''
try:
balance = broker.get_coins_balance(coin)
if balance not in [None,0]:
return jsonify({f"{coin}": balance[coin]['free']})
return jsonify({"Error": f"Balance query returned {balance}"})
except Exception as e:
broker.logger.log_this(f"Exception while querying balance: {e}",1)
return jsonify({"Error": "Balance could not be queried"})
if __name__=="__main__":
#Logo

View File

@ -1627,7 +1627,6 @@ class trader:
high_price = self.status_dict["take_profit_price"]
low_boundary = '{:.20f}'.format(low_price)[:decimals].center(decimals)
low_boundary_color = red
mid_boundary = '{:.20f}'.format(mid_price)[:decimals].center(decimals)
high_boundary = '{:.20f}'.format(high_price)[:decimals].center(decimals)
@ -1648,6 +1647,7 @@ class trader:
if self.total_amount_of_base!=0:
line3 = draw_line(self.status_dict["price"],self.status_dict["next_so_price"],self.status_dict["take_profit_price"],self.total_amount_of_quote/self.total_amount_of_base)
p = "*PAUSED*" if self.pause==True else ""
low_boundary_color = red
price_color = white
target_price_color = green
pair_color = cyan
@ -1669,15 +1669,20 @@ class trader:
if percentage_to_profit>high_percentage:
pct_color = red
multiplier = 0
if self.is_short and "old_long" in self.status_dict:
#Switch price
try:
#Logic to display switch price
old_target = self.status_dict["old_long"]["tp_price"]*self.status_dict["old_long"]["tp_amount"]
base_left = self.status_dict["old_long"]["tp_amount"]-self.status_dict["base_bought"]
minimum_switch_price = (old_target - self.status_dict["quote_spent"])/base_left
if old_target-self.status_dict["quote_spent"]>0 and base_left>0 and minimum_switch_price<low_price:
low_boundary_color = bright_green
low_boundary = '{:.20f}'.format(minimum_switch_price)[:decimals].center(decimals)
#Logic for multiplier
#When adding a trader, this line always throws an exception since status_dict["price"] is not yet populated
percentage_to_switch = (self.status_dict["old_long"]["tp_price"]-self.status_dict["price"])*100/self.status_dict["price"]
multiplier = int(percentage_to_switch/100)+1
except Exception as e:
print(e)
@ -1687,15 +1692,9 @@ class trader:
line1 = f"{line1} | BOOSTED"
if self.config_dict["autoswitch"]:
line1 = f"{line1} | AUTO"
if self.is_short and "old_long" in self.status_dict:
try:
#When adding a trader, this line always throws an exception since status_dict["price"] is not yet populated
percentage_to_switch = (self.status_dict["old_long"]["tp_price"]-self.status_dict["price"])*100/self.status_dict["price"]
multiplier = int(percentage_to_switch/100)+1
if multiplier>1:
#Only displays the multiplier if autoswitch is enabled.
line1 = f"{line1}x{multiplier}"
except ZeroDivisionError as e:
print(e)
if "stop_time" in self.config_dict and time.time()<=int(self.config_dict["stop_time"]):
line1 = f"{line1} | PROGRAMMED LAST DEAL"
if self.stop_when_profit==True:

View File

@ -43,7 +43,7 @@ TRADERS
65) toggle_pause 66) toggle_cleanup 67) toggle_autoswitch
68) toggle_check_old_long_price 69) switch_quote_currency
70) reload_safety_order 71) view_old_long 72) switch_price
73) backtests
73) backtests 74) get_balance
98) Change broker 99) Exit
'''
@ -637,3 +637,11 @@ if __name__=="__main__":
for item in sorted_result:
print(item, sorted_result[item])
input("Press ENTER to continue ")
elif command==74:
print("Returns the free balance of a given coin")
coin = input("Input currency: ").upper()
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/get_balance?coin={coin}"
print(json.loads(requests.get(url,headers=headers).content))
input("Press ENTER to continue ")