Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,96 +5,55 @@ from google.oauth2.service_account import Credentials
|
|
5 |
import ast
|
6 |
import requests
|
7 |
from datetime import datetime
|
|
|
8 |
import json
|
9 |
# Define the scope
|
10 |
start = False
|
11 |
starting_position = []
|
12 |
tradeHistory_positions = []
|
13 |
-
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
14 |
-
|
15 |
-
# Service account credentials as a dictionary
|
16 |
-
service_account_info = {
|
17 |
-
"type": "service_account",
|
18 |
-
"project_id": "primetrade-433011",
|
19 |
-
"private_key_id": "8bdab2f373343c045c8712c27e34f858132675df",
|
20 |
-
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtmNCg9Jkku2+W\nRXWqnOzoLQmXrn4BJC3yk7aaSGNh254/zMrWgyejTGpWxqklv0Hnxx1qn8nb3QoP\nKmRDbJnkt4doKupXFgfxPlebelLXgRT1JDbmVCTfCp8TcG8I1/9FpFNoqvpyeMZx\nd747UfP+bqym1pdhMr6rxCUEYVcKhc/4t+04k3i0IGGWW293CXGWGD54CIeFqWQX\n+SHo20pYfh8FKamytY8LHfwk1XbX1dMjnsxsQ/xZ8IjHZ//+m3bAG7n9QPe3a724\nG3L7iTZ15VET48j55aiSi4tJvHuy/I2kzOXrm/OuHRqJ+bH5+Ze8FVbmbBQlBjn8\nI8boxVSHAgMBAAECggEAMTAHEUwtJmjLpecZf5XGVMUKHkXtYxJmyICNMWsIad5q\nGQbEhIKWFSGeUecpX04xdOSI08Dh19/qLUDkNuyLMHDGN8BNNQ7DgloZRa8j0Pc8\nwncX7SxzZBVk3IOzmmxlYsy8a4BixVOuWtFEgBdpDLM8TWupafuQZigGGxcfrBWl\njgUoga05ybjpsdxW9c9+DoXXaOPHu/QQCEbv1X3dAJHJ0My2rBaO0s+0qoDJime1\nqNms6d36TnnoD6c0qhwD/E0eZfuaijcGxarq5BBnk9qsyxud2dmZd3M8jtVV/Env\n4o1rBV9Hao/z7DKbFdqOPNSMJRtY3e+hRjgm1/feaQKBgQDhKtsMRV+Ovkvu/JdA\nHG6We0nJ/kt8czEmbbW61rvUmJbI8hAK+0TERv/mwXaQqmo6JNhCREcx17vIE7Qy\nEzThGv7hYKotrrEXZq9Dje76KmAtk2zeJPXRriRu1rixRNPRwx9F2I+B3+iXaoqx\nsenzNMSy545P0YvssJYQLnKMTwKBgQDFXi3ZxtKCUwqdOvBEsVHeE00mUbqNm+fV\nDUgxFesQ8KkwuFib29NglnbxG3hgCVpA/4BoCsM2EyuZKap3gtoMW/EZqqhb9Hu+\nfwDoiJy3DmHivq6kHeEo6V6uTDxybqgPN+Yc08X+bqflDMYXLkBuJOnE+8O38TtE\n7BROW+EOSQKBgFiXHPH6BXvLAWM4/GVcCmKohUK1C4weYlMlTSACxooBsynCm29G\npyq2aI6oxXZrpjnUL0X7SSuiHp68qeQdzGtYzLlt5+brWX/EheaFXGYO8CJeY7IP\nRqxF4M2/K5GLa++W3qIDb4sAxql0YLdDMbHfrBhbpJFg97WbUJ9zNtxfAoGAdV23\n7lUpQY6YNT+jOXYotOLNcggP473ecvdfArGCA6TZN7uoFab3X+yZ9m7bemCVZymI\n9lXQGAv2VTJNyJvrhoX2LckqLOSJ4ZIsvBrg9op68xdpSvbpuiZsw0FagMIE9mfL\nU0Er8E1lUfPyqD482kLhMN52WJ//GtE4khBZGOECgYEAwD6mhwYdgQq1rujDZF8g\nzr4Ze3hiwoKGsEvybSYjqmsJMqwLWLCe9Wsj2bPWiMJmkpYdiCC+j3Wo6A1bdWy2\nFn/2T9dO35veJwM/HjP7/jMicyVr6S86vhMfzWuqvnQtuB/HAwctH+N4lJ5z0k8w\nn6WFbBEenJv8p5vZQi0NhHg=\n-----END PRIVATE KEY-----\n",
|
21 |
-
"client_email": "[email protected]",
|
22 |
-
"client_id": "104595139129046465243",
|
23 |
-
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
24 |
-
"token_uri": "https://oauth2.googleapis.com/token",
|
25 |
-
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
26 |
-
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myapi-994%40primetrade-433011.iam.gserviceaccount.com",
|
27 |
-
"universe_domain": "googleapis.com"
|
28 |
-
# Add your service account credentials here
|
29 |
-
}
|
30 |
-
cookie_str = "p20t=web.740861259.532251DB15AFA4E2C9D5A7A4AA7EB97E" #cookie_str get by logging into binance
|
31 |
-
csrft = "4f341a1a0b78bfb7ddb0bfc9b093ec06"
|
32 |
-
trade_type= "PERPETUAL" # perpetual or delivery
|
33 |
-
# Authenticate using the service account info
|
34 |
-
creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
|
35 |
-
client = gspread.authorize(creds)
|
36 |
-
|
37 |
-
# The ID of the Google Sheet (found in the URL of the sheet)
|
38 |
-
sheet_id = "1I_PuAeWTaRC4OhS5BA5gv0XQCA17VlIjpA1MvOlzVA8"
|
39 |
-
|
40 |
-
# Open the Google Sheet by sheet ID
|
41 |
-
workbook = client.open_by_key(sheet_id)
|
42 |
-
|
43 |
-
# Select the specific sheet in the workbook'
|
44 |
-
|
45 |
-
options = ["Select an option", "usdmHistory", "coinmHistory", "copyLeaderBoard"]
|
46 |
-
|
47 |
-
# Dropdown menu to select the sheet
|
48 |
-
selected_sheet = st.selectbox("Select a worksheet:", options)
|
49 |
-
|
50 |
-
# Ensure a valid selection is made
|
51 |
-
if selected_sheet != "Select an option":
|
52 |
-
sheet = workbook.worksheet(selected_sheet)
|
53 |
-
st.write(f"Selected sheet: {selected_sheet}")
|
54 |
-
else:
|
55 |
-
st.write("Please select a worksheet.")
|
56 |
-
|
57 |
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
|
62 |
-
df = pd.DataFrame(data, columns=headers)
|
63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
|
|
|
|
65 |
|
66 |
-
|
|
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
for uid, group in grouped:
|
75 |
-
# Combine chunks for each UID
|
76 |
-
|
77 |
-
trade_history_combined = ''.join(group['trade_history'].tolist())
|
78 |
|
79 |
-
#
|
80 |
-
|
81 |
-
'U_IDs': [uid],
|
82 |
-
'trade_history': [trade_history_combined]
|
83 |
-
})
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
|
92 |
-
df = df.fillna(value=pd.NA)
|
93 |
-
df = df.where(pd.notnull(df), None)
|
94 |
|
|
|
95 |
|
96 |
-
df = combine_chunks(df)
|
97 |
-
# df2 = combine_chunks(df2)
|
98 |
|
99 |
def convert_str_to_list_or_keep(value):
|
100 |
if isinstance(value, str):
|
@@ -106,13 +65,11 @@ def convert_str_to_list_or_keep(value):
|
|
106 |
return value
|
107 |
|
108 |
df = df.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
|
|
109 |
|
110 |
df['positionClosed'] = False
|
111 |
|
112 |
-
|
113 |
-
uid_input = int(st.text_input("Enter U_IDs to filter"))
|
114 |
-
else:
|
115 |
-
uid_input = str.upper(st.text_input("Enter U_IDs to filter"))
|
116 |
|
117 |
option = st.radio("Choose an option:", ["Show Position History", "Show Live Positions"])
|
118 |
|
@@ -125,6 +82,7 @@ if df is not None and uid_input:
|
|
125 |
|
126 |
|
127 |
filtered_df = df[df['U_IDs'] == uid_input].copy()
|
|
|
128 |
|
129 |
if not filtered_df.empty:
|
130 |
trade_list = filtered_df['trade_history'].iloc[0]
|
@@ -192,10 +150,7 @@ if df is not None and uid_input:
|
|
192 |
|
193 |
if 'symbol' in trade_list[i]:
|
194 |
symbol = trade_list[i]['symbol']
|
195 |
-
if
|
196 |
-
side ="buy" if float(trade_list[i]['amount'])>0 else "sell"
|
197 |
-
else:
|
198 |
-
side ="buy" if trade_list[i]['amount']>0 else "sell"
|
199 |
amount = trade_list[i]['amount']
|
200 |
symbol = trade_list[i]['symbol']
|
201 |
trade_list[i]['side'] =side
|
@@ -216,19 +171,18 @@ if df is not None and uid_input:
|
|
216 |
# Extract symbol and amount
|
217 |
symbol = new_position.get('symbol')
|
218 |
amount = new_position.get('amount')
|
219 |
-
if
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
start=True
|
232 |
# if start==False:
|
233 |
#
|
234 |
# start =True
|
@@ -259,21 +213,21 @@ if df is not None and uid_input:
|
|
259 |
for position in trade_list[j]['positions']:
|
260 |
# Check if 'Modified' is in the position and is a dict
|
261 |
if 'Modified' in position and isinstance(position['Modified'], dict):
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
modified_amount = get_amounts_from_positions_and_closed_trades(position)
|
278 |
modified_symbol = get_symbols_from_positions_and_closed_trades(position)
|
279 |
|
@@ -287,10 +241,7 @@ if df is not None and uid_input:
|
|
287 |
st.header(f"Data is from {datetime.now}")
|
288 |
start =True
|
289 |
position['Modified']['side'] = modified_side
|
290 |
-
if
|
291 |
-
position['Modified']['changeInAmount'] = float(amount) - modified_amount if modified_amount < 0 else modified_amount - float(amount)
|
292 |
-
else:
|
293 |
-
position['Modified']['changeInAmount'] = amount - modified_amount if modified_amount < 0 else modified_amount - amount
|
294 |
position['Modified']['i'] = i
|
295 |
amount = modified_amount
|
296 |
unique_lists.append(trade_list[j])
|
@@ -317,19 +268,14 @@ if df is not None and uid_input:
|
|
317 |
closed_side = "sell"
|
318 |
|
319 |
if symbol == closed_symbol and side == closed_side:
|
320 |
-
if
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
start =True
|
325 |
|
326 |
closed_trades_dict['side'] = closed_side
|
327 |
trade_info = closed_trades_dict['trade_info']
|
328 |
-
if
|
329 |
-
trade_info['changeInAmount'] = float(amount) - closed_amount if closed_amount < 0 else closed_amount - float(amount)
|
330 |
-
else:
|
331 |
-
|
332 |
-
trade_info['changeInAmount'] = amount - closed_amount if closed_amount < 0 else closed_amount - amount
|
333 |
amount = closed_amount
|
334 |
closed_trades_dict['trade_info']['i'] = i # Store index 'i' inside 'ClosedTrades'
|
335 |
closed_trades_dict['trade_info']['closed'] = True
|
@@ -394,27 +340,28 @@ if df is not None and uid_input:
|
|
394 |
unique_lists =[]
|
395 |
|
396 |
elif option == "Show Live Positions":
|
|
|
397 |
|
398 |
-
|
399 |
|
400 |
-
|
401 |
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
|
410 |
|
411 |
|
412 |
-
data3 = sheet3.get_all_values()
|
413 |
-
headers3 = data3.pop(0)
|
414 |
-
df3 = pd.DataFrame(data3, columns=headers3)
|
415 |
-
filtered_df3 = df3[df3['U_IDs'] == uid_input]
|
416 |
-
st.subheader("Performace")
|
417 |
-
st.dataframe(filtered_df3)
|
418 |
|
419 |
|
420 |
|
@@ -428,46 +375,40 @@ if df is not None and uid_input:
|
|
428 |
|
429 |
if position_history:
|
430 |
df_history = pd.DataFrame(position_history)
|
431 |
-
|
432 |
-
if selected_sheet == "copyLeaderBoard":
|
433 |
-
df_history['changeInAmount'] = pd.to_numeric(df_history['changeInAmount'], errors='coerce')
|
434 |
-
df_history['markPrice'] = pd.to_numeric(df_history['markPrice'], errors='coerce')
|
435 |
-
df_history['entryPrice'] = pd.to_numeric(df_history['entryPrice'], errors='coerce')
|
436 |
-
# df_history['amount'] = pd.to_numeric(df['amount'],errors='coerce')
|
437 |
-
|
438 |
-
# Replace NaN with 0 or handle as required
|
439 |
-
df_history.fillna(0, inplace=True)
|
440 |
|
441 |
# Update the global timestamp with the last update from history
|
442 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
443 |
|
444 |
# Create a transformed DataFrame for display
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
'Change in size in USDT': df_history['changeInAmount'] * -(df_history['markPrice']),
|
466 |
-
'Entry price': df_history['entryPrice'],
|
467 |
-
'Exit price': df_history['markPrice'],
|
468 |
-
'Leverage': df_history['leverage'],
|
469 |
-
})
|
470 |
-
|
471 |
if 'closed' in df_history.columns:
|
472 |
df_transformed['Position closed'] = df_history['closed']
|
473 |
|
@@ -503,34 +444,21 @@ if df is not None and uid_input:
|
|
503 |
df_starting = pd.DataFrame(starting_position)
|
504 |
|
505 |
for index, row in df_starting.iterrows():
|
506 |
-
if
|
507 |
-
side = True if float(row['amount']) > 0 else False
|
508 |
-
else:
|
509 |
-
side = True if row['amount'] > 0 else False
|
510 |
is_closed = isClosed(row['i'])
|
511 |
|
512 |
# Generate a unique key for the button
|
513 |
button_key = f"position_{row['i']}"
|
514 |
|
515 |
# Display a button for each trade position
|
516 |
-
if
|
517 |
-
if st.button(
|
518 |
-
f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
|
519 |
-
f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
|
520 |
-
f"Leverage: {row['leverage']}, TradeTakenAt: {row['updateTime']}, "
|
521 |
-
f"lastUpdated: {lastUpdated(row['i'])}, isClosed: {is_closed}",
|
522 |
-
key=button_key
|
523 |
-
):
|
524 |
-
show_position_history(row['i'])
|
525 |
-
|
526 |
-
else:
|
527 |
-
if st.button(
|
528 |
f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
|
529 |
f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
|
530 |
-
f"Leverage: {row['leverage']},
|
|
|
531 |
key=button_key
|
532 |
-
|
533 |
-
|
534 |
|
535 |
if __name__ == "__main__":
|
536 |
-
main()
|
|
|
5 |
import ast
|
6 |
import requests
|
7 |
from datetime import datetime
|
8 |
+
import boto3
|
9 |
import json
|
10 |
# Define the scope
|
11 |
start = False
|
12 |
starting_position = []
|
13 |
tradeHistory_positions = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
s3 = boto3.resource(
|
16 |
+
service_name = 's3',
|
17 |
+
region_name = 'ap-south-1',
|
18 |
+
aws_access_key_id = 'AKIA3TD2SOLYZML62HJR',
|
19 |
+
aws_secret_access_key ='mfk4Z48kAAivsIiCAqklP/+7v9iY6MxKMo3Rm1zD'
|
20 |
+
)
|
21 |
|
22 |
+
bucket_name = 'usdsmcoinmdata'
|
|
|
23 |
|
24 |
+
# File mapping for options
|
25 |
+
file_mapping = {
|
26 |
+
"usdm": "usdm_trade_history.csv",
|
27 |
+
"coinm": "coinm_trade_history.csv",
|
28 |
+
"copyLeaderboard": "copyLeaderBoard_trade_history.csv"
|
29 |
+
}
|
30 |
|
31 |
+
# Streamlit App
|
32 |
+
st.title("Trade History Viewer")
|
33 |
|
34 |
+
# Dropdown to select the trade history
|
35 |
+
option = st.selectbox("Choose the trade history to display:", list(file_mapping.keys()))
|
36 |
|
37 |
+
# Fetch and display the corresponding trade history
|
38 |
+
if option:
|
39 |
+
file_key = file_mapping[option]
|
40 |
+
try:
|
41 |
+
# Fetch the file from S3
|
42 |
+
obj = s3.Bucket(bucket_name).Object(file_key).get()
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
# Read the CSV into a DataFrame
|
45 |
+
df = pd.read_csv(obj['Body'], index_col=False)
|
|
|
|
|
|
|
46 |
|
47 |
+
# Display the DataFrame in Streamlit
|
48 |
+
st.write(f"Displaying data for: **{option}**")
|
49 |
+
except Exception as e:
|
50 |
+
st.error(f"Error fetching the file: {str(e)}")
|
51 |
+
|
52 |
+
|
53 |
|
|
|
|
|
54 |
|
55 |
+
df2 = pd.read_csv('df.csv')
|
56 |
|
|
|
|
|
57 |
|
58 |
def convert_str_to_list_or_keep(value):
|
59 |
if isinstance(value, str):
|
|
|
65 |
return value
|
66 |
|
67 |
df = df.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
68 |
+
df2 = df2.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
69 |
|
70 |
df['positionClosed'] = False
|
71 |
|
72 |
+
uid_input = str.upper(st.text_input("Enter U_IDs to filter"))
|
|
|
|
|
|
|
73 |
|
74 |
option = st.radio("Choose an option:", ["Show Position History", "Show Live Positions"])
|
75 |
|
|
|
82 |
|
83 |
|
84 |
filtered_df = df[df['U_IDs'] == uid_input].copy()
|
85 |
+
print(filtered_df,"filtered df")
|
86 |
|
87 |
if not filtered_df.empty:
|
88 |
trade_list = filtered_df['trade_history'].iloc[0]
|
|
|
150 |
|
151 |
if 'symbol' in trade_list[i]:
|
152 |
symbol = trade_list[i]['symbol']
|
153 |
+
side ="buy" if trade_list[i]['amount']>0 else "sell"
|
|
|
|
|
|
|
154 |
amount = trade_list[i]['amount']
|
155 |
symbol = trade_list[i]['symbol']
|
156 |
trade_list[i]['side'] =side
|
|
|
171 |
# Extract symbol and amount
|
172 |
symbol = new_position.get('symbol')
|
173 |
amount = new_position.get('amount')
|
174 |
+
if start==False:
|
175 |
+
start_time = new_position.get('updateTime')
|
176 |
+
year = start_time[0]
|
177 |
+
month = start_time[1]
|
178 |
+
day = start_time[2]
|
179 |
+
hour =start_time[3]
|
180 |
+
minute =start_time[4]
|
181 |
+
seconds = start_time[5]
|
182 |
+
dt = datetime(year, month, day, hour, minute, seconds)
|
183 |
+
human_readable_format = dt.strftime('%B %d, %Y, %I:%M:%S %p')
|
184 |
+
st.subheader(f"Data from {human_readable_format}")
|
185 |
+
start=True
|
|
|
186 |
# if start==False:
|
187 |
#
|
188 |
# start =True
|
|
|
213 |
for position in trade_list[j]['positions']:
|
214 |
# Check if 'Modified' is in the position and is a dict
|
215 |
if 'Modified' in position and isinstance(position['Modified'], dict):
|
216 |
+
|
217 |
+
if start==False:
|
218 |
+
for k,v in position.items():
|
219 |
+
start_time = v['updateTime']
|
220 |
+
|
221 |
+
year = start_time[0]
|
222 |
+
month = start_time[1]
|
223 |
+
day = start_time[2]
|
224 |
+
hour =start_time[3]
|
225 |
+
minute =start_time[4]
|
226 |
+
seconds = start_time[5]
|
227 |
+
dt = datetime(year, month, day, hour, minute, seconds)
|
228 |
+
human_readable_format = dt.strftime('%d-%m-%Y %H:%M:%S')
|
229 |
+
st.subheader(f"Data from {human_readable_format}")
|
230 |
+
start=True
|
231 |
modified_amount = get_amounts_from_positions_and_closed_trades(position)
|
232 |
modified_symbol = get_symbols_from_positions_and_closed_trades(position)
|
233 |
|
|
|
241 |
st.header(f"Data is from {datetime.now}")
|
242 |
start =True
|
243 |
position['Modified']['side'] = modified_side
|
244 |
+
position['Modified']['changeInAmount'] = amount - modified_amount if modified_amount < 0 else modified_amount - amount
|
|
|
|
|
|
|
245 |
position['Modified']['i'] = i
|
246 |
amount = modified_amount
|
247 |
unique_lists.append(trade_list[j])
|
|
|
268 |
closed_side = "sell"
|
269 |
|
270 |
if symbol == closed_symbol and side == closed_side:
|
271 |
+
if start==False:
|
272 |
+
for k,v in position.items():
|
273 |
+
start_time = v['updateTime']
|
274 |
+
start =True
|
|
|
275 |
|
276 |
closed_trades_dict['side'] = closed_side
|
277 |
trade_info = closed_trades_dict['trade_info']
|
278 |
+
trade_info['changeInAmount'] = amount - closed_amount if closed_amount < 0 else closed_amount - amount
|
|
|
|
|
|
|
|
|
279 |
amount = closed_amount
|
280 |
closed_trades_dict['trade_info']['i'] = i # Store index 'i' inside 'ClosedTrades'
|
281 |
closed_trades_dict['trade_info']['closed'] = True
|
|
|
340 |
unique_lists =[]
|
341 |
|
342 |
elif option == "Show Live Positions":
|
343 |
+
filtered_df2 = df2[df2['U_IDs'] == uid_input]
|
344 |
|
345 |
+
if not filtered_df2.empty:
|
346 |
|
347 |
+
positions_list = filtered_df2['Positions'].iloc[0] # Extract the first match
|
348 |
|
349 |
+
# Convert the list of dictionaries to a DataFrame
|
350 |
+
if isinstance(positions_list, list) and positions_list:
|
351 |
+
positions_df = pd.DataFrame(positions_list)
|
352 |
+
st.subheader("Live Positions")
|
353 |
+
st.dataframe(positions_df)
|
354 |
+
else:
|
355 |
+
st.write("No live positions data available for the given U_ID.")
|
356 |
|
357 |
|
358 |
|
359 |
+
# data3 = sheet3.get_all_values()
|
360 |
+
# headers3 = data3.pop(0)
|
361 |
+
# df3 = pd.DataFrame(data3, columns=headers3)
|
362 |
+
# filtered_df3 = df3[df3['U_IDs'] == uid_input]
|
363 |
+
# st.subheader("Performace")
|
364 |
+
# st.dataframe(filtered_df3)
|
365 |
|
366 |
|
367 |
|
|
|
375 |
|
376 |
if position_history:
|
377 |
df_history = pd.DataFrame(position_history)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
378 |
|
379 |
# Update the global timestamp with the last update from history
|
380 |
+
columns_to_check = [
|
381 |
+
'symbol', 'side', 'amount', 'changeInAmount', 'markPrice',
|
382 |
+
'entryPrice', 'pnl', 'roe', 'leverage', 'updateTime',
|
383 |
+
'tradeType', 'stopLossPrice', 'takeProfitPrice', 'weightedScoreRatio'
|
384 |
+
]
|
385 |
+
|
386 |
+
# Adding missing columns with None as default
|
387 |
+
for column in columns_to_check:
|
388 |
+
if column not in df_history.columns:
|
389 |
+
df_history[column] = None
|
390 |
|
391 |
# Create a transformed DataFrame for display
|
392 |
+
df_transformed = pd.DataFrame({
|
393 |
+
'Pair/Asset': df_history['symbol'],
|
394 |
+
'is long': df_history['side'],
|
395 |
+
'Current size after change': df_history['amount'],
|
396 |
+
'Change in size in Asset': df_history['changeInAmount'],
|
397 |
+
'Change in size in USDT': df_history['changeInAmount'] * -(df_history['markPrice']),
|
398 |
+
'Entry price': df_history['entryPrice'],
|
399 |
+
'Exit price': df_history['markPrice'],
|
400 |
+
'pnl in usdt': df_history['pnl'],
|
401 |
+
'pnl in %': df_history['roe'],
|
402 |
+
'Leverage': df_history['leverage'],
|
403 |
+
'updatedTime': df_history['updateTime'],
|
404 |
+
'Trade Type': df_history['tradeType'], # New field
|
405 |
+
'Stop Loss Price': df_history['stopLossPrice'], # New field
|
406 |
+
'Take Profit Price': df_history['takeProfitPrice'], # New field
|
407 |
+
'Weighted Score Ratio': df_history['weightedScoreRatio'], # New field
|
408 |
+
'Transaction Value in USDT': df_history['amount'] * df_history['markPrice'], # New calculation
|
409 |
+
'Profit/Loss Ratio': (df_history['markPrice'] - df_history['entryPrice']) / df_history['entryPrice'] # New calculation
|
410 |
+
})
|
411 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
412 |
if 'closed' in df_history.columns:
|
413 |
df_transformed['Position closed'] = df_history['closed']
|
414 |
|
|
|
444 |
df_starting = pd.DataFrame(starting_position)
|
445 |
|
446 |
for index, row in df_starting.iterrows():
|
447 |
+
side = True if row['amount'] > 0 else False
|
|
|
|
|
|
|
448 |
is_closed = isClosed(row['i'])
|
449 |
|
450 |
# Generate a unique key for the button
|
451 |
button_key = f"position_{row['i']}"
|
452 |
|
453 |
# Display a button for each trade position
|
454 |
+
if st.button(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
455 |
f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
|
456 |
f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
|
457 |
+
f"Leverage: {row['leverage']}, TradeTakenAt: {row['updateTime']}, "
|
458 |
+
f"lastUpdated: {lastUpdated(row['i'])}, isClosed: {is_closed}",
|
459 |
key=button_key
|
460 |
+
):
|
461 |
+
show_position_history(row['i'])
|
462 |
|
463 |
if __name__ == "__main__":
|
464 |
+
main()
|