Statistics server API update
This commit is contained in:
parent
4a1f1c844d
commit
12999a2189
|
|
@ -11,6 +11,7 @@ utils/close.py
|
||||||
utils/credentials.py
|
utils/credentials.py
|
||||||
utils/set_exchange.py
|
utils/set_exchange.py
|
||||||
utils/stuff.py
|
utils/stuff.py
|
||||||
|
utils/shorts_summary.py
|
||||||
logs/binance.log
|
logs/binance.log
|
||||||
logs/okex.log
|
logs/okex.log
|
||||||
logs/gateio.log
|
logs/gateio.log
|
||||||
|
|
|
||||||
|
|
@ -1,53 +1,61 @@
|
||||||
import sqlite3
|
'''
|
||||||
import os
|
Returns information on all running short traders:
|
||||||
import sys
|
'''
|
||||||
import json
|
|
||||||
import datetime
|
|
||||||
|
|
||||||
pair = sys.argv[1].replace("/","")
|
import json, datetime, credentials, requests, time
|
||||||
|
|
||||||
#Connect to db
|
def profit_since_date(base, quote, timestamp):
|
||||||
connection = sqlite3.connect("../profits/profits_database.db")
|
url = f"{base_statistics_url}/total_profit_by_pair_since_date?base={base}"e={quote}×tamp={timestamp}" #type: ignore
|
||||||
cursor = connection.cursor()
|
result = json.loads(requests.get(url,headers=headers).content)
|
||||||
|
return result["Total profit"]
|
||||||
|
|
||||||
#Load old_long info
|
def timestamp_to_seconds(timestamp_string):
|
||||||
try:
|
'''
|
||||||
with open(f"../status/{pair}.oldlong") as f:
|
Converts a timestamp string from this format "[YYYY/mm/dd HH:MM:SS]" to seconds.
|
||||||
old_long = json.load(f)
|
|
||||||
except Exception as e:
|
:param timestamp_string: timestamp string.
|
||||||
print(e)
|
:return: linux time in seconds.
|
||||||
print("No old_long file")
|
'''
|
||||||
os._exit(0)
|
|
||||||
|
dt = datetime.datetime.strptime(timestamp_string.strip('[]'), "%Y/%m/%d %H:%M:%S")
|
||||||
|
return int(dt.timestamp())
|
||||||
|
|
||||||
|
|
||||||
#Get time of switch to unix time
|
if __name__=="__main__":
|
||||||
old_date = old_long["datetime"][1:11]
|
api_key = credentials.get_credentials("mainnet_api_key")["key"]
|
||||||
linux_time = datetime.datetime.strptime(old_date,"%Y/%m/%d").timestamp()
|
base_statistics_url = f"{credentials.get_url('mainnet')}/statistics_server" #type: ignore
|
||||||
|
base_url = f"{credentials.get_url('mainnet')}" #type: ignore
|
||||||
|
results_dict = {}
|
||||||
|
|
||||||
#Query database
|
headers = {"X-API-KEY": api_key}
|
||||||
query = f"""SELECT pair, SUM(amount) AS total_profit
|
|
||||||
FROM profits_table
|
exchanges = ["binance", "gateio", "kucoin", "okex"]
|
||||||
WHERE timestamp >= '{linux_time}'
|
|
||||||
GROUP BY pair;"""
|
for exchange in exchanges:
|
||||||
cursor.execute(query)
|
#fetch all traders status
|
||||||
query_result = cursor.fetchall()
|
url = f"{base_url}/{exchange}/get_all_worker_status"
|
||||||
|
while True:
|
||||||
#Calculate profits
|
query = requests.get(url,headers=headers)
|
||||||
total = 0
|
if query.status_code != 503:
|
||||||
for item in query_result:
|
break
|
||||||
if item[0].replace("/","")==pair:
|
time.sleep(.2)
|
||||||
total = item[1]
|
workers_status = json.loads(query.content)
|
||||||
|
|
||||||
print(f"Profits since switch ({old_date}): {round(total,2)}")
|
#for each status_dict, extract pair, switch_date, old_long_amount
|
||||||
print(f"Profit needed to cover expenses: {round(old_long['quote_spent'],2)}")
|
for item in workers_status:
|
||||||
print(f"Difference: {round(old_long['quote_spent']-total,2)}")
|
if workers_status[item]["is_short"]:
|
||||||
|
print("Processing",item)
|
||||||
try:
|
base,quote = item.split("/")
|
||||||
with open(f"../status/{pair}.status") as f:
|
switch_date = timestamp_to_seconds(workers_status[item]["old_long"]["datetime"])
|
||||||
status_file = json.load(f)
|
profit_since_short = profit_since_date(base,quote,switch_date)
|
||||||
except Exception as e:
|
total_current_value = workers_status[item]["quote_spent"] + (workers_status[item]["old_long"]["tp_amount"]-workers_status[item]["base_bought"])*workers_status[item]["price"]
|
||||||
print(e)
|
|
||||||
print("No status file")
|
results_dict[item] = {
|
||||||
os._exit(0)
|
"switch_date": workers_status[item]["old_long"]["datetime"],
|
||||||
|
"profit_since_short": round(profit_since_short,2),
|
||||||
print(f"Old long price: {old_long['tp_price']}")
|
"old_long_quote_spent": round(workers_status[item]["old_long"]["quote_spent"]),
|
||||||
print(f"Current price: {status_file['price']}")
|
"total_current_value": round(total_current_value,2)
|
||||||
|
}
|
||||||
|
|
||||||
|
for item in results_dict:
|
||||||
|
print(item, results_dict[item])
|
||||||
|
|
|
||||||
|
|
@ -174,24 +174,25 @@ def profit_report():
|
||||||
"Total profit": total_amount}
|
"Total profit": total_amount}
|
||||||
|
|
||||||
|
|
||||||
def query_total_profit(pair=None):
|
def query_total_profit(pair=None, start_date=0):
|
||||||
'''
|
'''
|
||||||
Returns total profit of the trading pair.
|
Returns total profit of the trading pair.
|
||||||
If no pair specified, returns the grand total of all pairs.
|
If no pair specified, returns the grand total of all pairs.
|
||||||
'''
|
'''
|
||||||
|
|
||||||
if pair is None:
|
if pair is None:
|
||||||
query = "SELECT SUM(amount) AS total_profit FROM profits_table"
|
query = "SELECT SUM(amount) AS total_profit FROM profits_table WHERE timestamp >= ?"
|
||||||
with db_cursor() as cursor:
|
with db_cursor() as cursor:
|
||||||
cursor.execute(query)
|
cursor.execute(query, (start_date,))
|
||||||
query_result = cursor.fetchall()
|
query_result = cursor.fetchall()
|
||||||
return query_result[0][0]
|
return query_result[0][0]
|
||||||
else:
|
else:
|
||||||
query = """SELECT pair, SUM(amount) AS total_profit
|
query = """SELECT pair, SUM(amount) AS total_profit
|
||||||
FROM profits_table
|
FROM profits_table
|
||||||
|
WHERE timestamp >= ?
|
||||||
GROUP BY pair;"""
|
GROUP BY pair;"""
|
||||||
with db_cursor() as cursor:
|
with db_cursor() as cursor:
|
||||||
cursor.execute(query)
|
cursor.execute(query, (start_date,))
|
||||||
query_result = cursor.fetchall()
|
query_result = cursor.fetchall()
|
||||||
for item in query_result:
|
for item in query_result:
|
||||||
if item[0].replace("/","")==pair:
|
if item[0].replace("/","")==pair:
|
||||||
|
|
@ -566,6 +567,25 @@ def total_profit_by_pair():
|
||||||
return jsonify({'Error': 'Halp'})
|
return jsonify({'Error': 'Halp'})
|
||||||
|
|
||||||
|
|
||||||
|
@stats_api.route("/total_profit_by_pair_since_date")
|
||||||
|
def total_profit_by_pair_since_date():
|
||||||
|
'''
|
||||||
|
GET request
|
||||||
|
Parameters: 'base' -> string
|
||||||
|
'quote' -> string
|
||||||
|
'timestamp' -> int
|
||||||
|
'''
|
||||||
|
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys():
|
||||||
|
return jsonify({'Error': 'API key invalid'}), 401
|
||||||
|
try:
|
||||||
|
base = request.args.get("base")
|
||||||
|
quote = request.args.get("quote")
|
||||||
|
timestamp = int(request.args.get("timestamp")) # type: ignore
|
||||||
|
total = query_total_profit(f"{base}{quote}", timestamp)
|
||||||
|
return jsonify({"Total profit": total})
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return jsonify({'Error': 'Halp'})
|
||||||
|
|
||||||
if __name__=="__main__":
|
if __name__=="__main__":
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue