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as as pd
2
+ import streamlit as st
3
+ import gspread
4
+ from google.oauth2.service_account import Credentials
5
+ import ast
6
+ import requests
7
+ import pandas as pd
8
+ import boto3
9
+ from datetime import datetime
10
+ import json
11
+ # Define the scope
12
+ start = False
13
+ starting_position = []
14
+ tradeHistory_positions = []
15
+
16
+
17
+ s3 = boto3.resource(
18
+ service_name = 's3',
19
+ region_name = 'ap-south-1',
20
+ aws_access_key_id = 'AKIA3TD2SOLYZML62HJR',
21
+ aws_secret_access_key ='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'
22
+ )
23
+
24
+ obj = s3.Bucket('usdsmcoinmdata').Object('copyLeaderboard_trade_history.csv').get()
25
+ df = pd.read_csv(obj['Body'],index_col=False)
26
+
27
+ df2 = pd.read_csv('df.csv')
28
+
29
+ def convert_str_to_list_or_keep(value):
30
+ if isinstance(value, str):
31
+ try:
32
+ return ast.literal_eval(value)
33
+ except (SyntaxError, ValueError):
34
+ return value
35
+ else:
36
+ return value
37
+
38
+ df = df.apply(lambda col: col.map(convert_str_to_list_or_keep))
39
+ df2 = df2.apply(lambda col: col.map(convert_str_to_list_or_keep))
40
+
41
+
42
+
43
+
44
+
45
+ df['positionClosed'] = False
46
+
47
+ print(df)
48
+
49
+ uid_input = int(st.text_input("Enter U_IDs to filter"))
50
+
51
+ option = st.radio("Choose an option:", ["Show Position History", "Show Live Positions"])
52
+
53
+ if df is not None and uid_input:
54
+
55
+ if option == "Show Position History":
56
+ st.title("Position History Viewer")
57
+ # Display starting positions with clickable rows
58
+ st.header("Starting Positions")
59
+
60
+ filtered_df = df[df['U_IDs'] == uid_input].copy()
61
+ print("filtered df",filtered_df)
62
+
63
+ if not filtered_df.empty:
64
+ trade_list = filtered_df['trade_history'].iloc[0]
65
+ else:
66
+ st.write("No data found for the provided U_ID.")
67
+
68
+
69
+ unique_lists = []
70
+
71
+ def get_amounts_from_positions_and_closed_trades(data):
72
+ print("revheeeeeeeeeeeeeeeegfeggggggggggggg")
73
+ print('data',data)
74
+
75
+
76
+ # Check if 'Modified' key exists and extract amounts
77
+ if 'Modified' in data:
78
+ modified_positions = data['Modified']
79
+ print("reeeeeegggggggggggggg33")
80
+ print(modified_positions)
81
+ print(type(modified_positions))
82
+ # modified_positions = modified_positions[0]
83
+ if isinstance(modified_positions, dict) and 'amount' in modified_positions:
84
+ print("reafffffffff000000000")
85
+ amount = modified_positions.get('amount')
86
+ if isinstance(amount, (int, float)): # Check if amount is a number
87
+ amounts =amount
88
+ # Check if 'ClosedTrades' key exists and extract amounts
89
+ if 'ClosedTrades' in data:
90
+ closed_trades = data['ClosedTrades']
91
+ closed_trades =closed_trades[0]
92
+ if isinstance(closed_trades, dict) and 'amount' in closed_trades:
93
+ amount = closed_trades.get('amount')
94
+ if isinstance(amount, (int, float)): # Check if amount is a number
95
+ amounts = amount
96
+
97
+ return amounts
98
+
99
+ def get_symbols_from_positions_and_closed_trades(data):
100
+
101
+
102
+ # Check if 'Modified' key exists and extract symbols
103
+ if 'Modified' in data:
104
+ modified_positions = data['Modified']
105
+ # modified_positions =modified_positions
106
+ if isinstance(modified_positions, dict) and 'symbol' in modified_positions:
107
+ symbol = modified_positions['symbol']
108
+
109
+ # Check if 'ClosedTrades' key exists and extract symbols
110
+ if 'ClosedTrades' in data:
111
+ closed_trades = data['ClosedTrades']
112
+ closed_trades =closed_trades[0]
113
+ if isinstance(closed_trades, dict) and 'symbol' in closed_trades:
114
+ symbol = closed_trades['symbol']
115
+
116
+ return symbol
117
+
118
+ for i in range(len(trade_list)):
119
+
120
+
121
+ if trade_list[i]=="none":
122
+ continue
123
+
124
+ if not trade_list: # Check if the trade_list is empty
125
+ st.header("No data found, this may not be in the leaderboard")
126
+
127
+ if start ==False:
128
+ st.subheader(f"Data is from {datetime.now()}")
129
+ start =True
130
+ foundCLosed = False
131
+ changeInAmount = 0
132
+
133
+ if 'symbol' in trade_list[i]:
134
+ symbol = trade_list[i]['symbol']
135
+ side ="buy" if float(trade_list[i]['amount'])>0 else "sell"
136
+ amount = trade_list[i]['amount']
137
+ symbol = trade_list[i]['symbol']
138
+ trade_list[i]['side'] =side
139
+ trade_list[i]['changeInAmount'] = changeInAmount
140
+ trade_list[i]['i'] = i
141
+ unique_lists.append({"position":trade_list[i]})
142
+ trade_list[i] = "none"
143
+
144
+
145
+ else:
146
+ if 'positions' in trade_list[i]:
147
+ reached = False
148
+ # Collect necessary data first before modifying the dictionary
149
+ for k, v in list(trade_list[i].items()): # Convert to a list to avoid modifying during iteration
150
+ for entry in v:
151
+ if 'NewPosition' in entry:
152
+ new_position = entry.get('NewPosition', {})
153
+ # Extract symbol and amount
154
+ symbol = new_position.get('symbol')
155
+ amount = new_position.get('amount')
156
+ # if start==False:
157
+ # start_time = new_position.get('updateTime')
158
+ # year = start_time[0]
159
+ # month = start_time[1]
160
+ # day = start_time[2]
161
+ # hour =start_time[3]
162
+ # minute =start_time[4]
163
+ # seconds = start_time[5]
164
+ # dt = datetime(year, month, day, hour, minute, seconds)
165
+ # human_readable_format = dt.strftime('%B %d, %Y, %I:%M:%S %p')
166
+ # st.subheader(f"Data from {human_readable_format}")
167
+ # start=True
168
+ # if start==False:
169
+ #
170
+ # start =True
171
+ side = "buy" if amount > 0 else "sell"
172
+ new_position['side'] = side
173
+ new_position['changeInAmount'] = changeInAmount
174
+ new_position['i'] = i
175
+ # Update the entry with the modified 'NewPosition'
176
+ entry['NewPosition'] = new_position
177
+
178
+ # Append the updated trade_list[i] to unique_lists
179
+ unique_lists.append(trade_list[i])
180
+
181
+ reached = True
182
+
183
+ # Now safely modify the dictionary after iteration is complete
184
+ if reached:
185
+ trade_list[i] = "none"
186
+
187
+ # Now safely modify the dictionary after iteration is complete
188
+
189
+
190
+ for j in range(i+1, len(trade_list)):
191
+ if trade_list[j] == "none":
192
+ continue
193
+
194
+ if 'positions' in trade_list[j] and isinstance(trade_list[j]['positions'], list):
195
+ for position in trade_list[j]['positions']:
196
+ # Check if 'Modified' is in the position and is a dict
197
+ if 'Modified' in position and isinstance(position['Modified'], dict):
198
+
199
+ # if start==False:
200
+ # for k,v in position.items():
201
+ # start_time = v['updateTime']
202
+
203
+ # year = start_time[0]
204
+ # month = start_time[1]
205
+ # day = start_time[2]
206
+ # hour =start_time[3]
207
+ # minute =start_time[4]
208
+ # seconds = start_time[5]
209
+ # dt = datetime(year, month, day, hour, minute, seconds)
210
+ # human_readable_format = dt.strftime('%d-%m-%Y %H:%M:%S')
211
+ # st.subheader(f"Data from {human_readable_format}")
212
+ # start=True
213
+ modified_amount = get_amounts_from_positions_and_closed_trades(position)
214
+ modified_symbol = get_symbols_from_positions_and_closed_trades(position)
215
+
216
+ if modified_amount > 0:
217
+ modified_side = "buy"
218
+ else:
219
+ modified_side = "sell"
220
+
221
+ if symbol == modified_symbol and side == modified_side:
222
+ if start ==False:
223
+ st.header(f"Data is from {datetime.now}")
224
+ start =True
225
+ position['Modified']['side'] = modified_side
226
+ position['Modified']['changeInAmount'] = float(amount) - modified_amount if modified_amount < 0 else modified_amount - float(amount)
227
+ position['Modified']['i'] = i
228
+ amount = modified_amount
229
+ unique_lists.append(trade_list[j])
230
+ trade_list[j] = "none"
231
+
232
+ # Check if 'ClosedTrades' is in the position and is a tuple
233
+ if 'ClosedTrades' in position and isinstance(position['ClosedTrades'], tuple):
234
+ if start ==False:
235
+ st.header(f"Data is from {datetime.now}")
236
+ start =True
237
+ foundCLosed = False
238
+ closed_trades_tuple = position['ClosedTrades']
239
+ closed_trades_dict = {
240
+ 'trade_info': closed_trades_tuple[0],
241
+ 'side': closed_trades_tuple[1]
242
+ }
243
+
244
+ closed_amount = get_amounts_from_positions_and_closed_trades(position)
245
+ closed_symbol = get_symbols_from_positions_and_closed_trades(position)
246
+
247
+ if closed_amount > 0:
248
+ closed_side = "buy"
249
+ else:
250
+ closed_side = "sell"
251
+
252
+ if symbol == closed_symbol and side == closed_side:
253
+ # if start==False:
254
+ # for k,v in position.items():
255
+ # start_time = v['updateTime']
256
+ # start =True
257
+
258
+ closed_trades_dict['side'] = closed_side
259
+ trade_info = closed_trades_dict['trade_info']
260
+ trade_info['changeInAmount'] = float(amount) - closed_amount if closed_amount < 0 else closed_amount - float(amount)
261
+ amount = closed_amount
262
+ closed_trades_dict['trade_info']['i'] = i # Store index 'i' inside 'ClosedTrades'
263
+ closed_trades_dict['trade_info']['closed'] = True
264
+
265
+ # Append the updated trade_list[j] to unique_lists
266
+ unique_lists.append(trade_list[j])
267
+ trade_list[j] = "none"
268
+ foundCLosed = True
269
+ break
270
+
271
+ # Break the inner loop if a closed trade was found
272
+ if foundCLosed:
273
+ break
274
+
275
+
276
+
277
+
278
+ for k in range(len(unique_lists)):
279
+ data = unique_lists[k]
280
+
281
+
282
+ if k ==0:
283
+
284
+
285
+ if 'positions' in data:
286
+ if isinstance(data['positions'], list):
287
+ for a in data['positions']:
288
+ if 'NewPosition' in a:
289
+
290
+ position_data = a['NewPosition']
291
+ starting_position.append(position_data)
292
+ tradeHistory_positions.append(position_data)
293
+
294
+
295
+ else:
296
+ if 'position' in data:
297
+ position_data =data['position']
298
+ starting_position.append(position_data)
299
+ tradeHistory_positions.append(position_data)
300
+
301
+
302
+
303
+ if 'positions' in data:
304
+ if isinstance(data['positions'],list):
305
+ for a in data['positions']:
306
+ if 'ClosedTrades' in a:
307
+ position_data = a['ClosedTrades'][0]
308
+ tradeHistory_positions.append(position_data)
309
+
310
+
311
+
312
+ if 'positions' in data:
313
+ if isinstance(data['positions'],list):
314
+ for a in data['positions']:
315
+ if 'Modified' in a:
316
+ position_data = a['Modified']
317
+ tradeHistory_positions.append(position_data)
318
+
319
+
320
+
321
+
322
+ unique_lists =[]
323
+
324
+ elif option == "Show Live Positions":
325
+ filtered_df2 = df2[df2['U_IDs'] == uid_input]
326
+
327
+ if not filtered_df2.empty:
328
+
329
+ positions_list = filtered_df2['Positions'].iloc[0] # Extract the first match
330
+
331
+ # Convert the list of dictionaries to a DataFrame
332
+ if isinstance(positions_list, list) and positions_list:
333
+ positions_df = pd.DataFrame(positions_list)
334
+ st.subheader("Live Positions")
335
+ st.dataframe(positions_df)
336
+ else:
337
+ st.write("No live positions data available for the given U_ID.")
338
+
339
+
340
+
341
+ # data3 = sheet3.get_all_values()
342
+ # headers3 = data3.pop(0)
343
+ # df3 = pd.DataFrame(data3, columns=headers3)
344
+ # filtered_df3 = df3[df3['U_IDs'] == uid_input]
345
+ # st.subheader("Performace")
346
+ # st.dataframe(filtered_df3)
347
+
348
+
349
+
350
+ def show_position_history(selected_position):
351
+ st.header(f"History for {selected_position}")
352
+
353
+ # Filter trade history for the selected position
354
+ position_history = [pos for pos in tradeHistory_positions if pos['i'] == selected_position]
355
+
356
+
357
+
358
+ if position_history:
359
+ df_history = pd.DataFrame(position_history)
360
+
361
+ df_history['changeInAmount'] = pd.to_numeric(df_history['changeInAmount'], errors='coerce')
362
+ df_history['markPrice'] = pd.to_numeric(df_history['markPrice'], errors='coerce')
363
+ df_history['entryPrice'] = pd.to_numeric(df_history['entryPrice'], errors='coerce')
364
+
365
+ df_history['amount'] = pd.to_numeric(df_history['amount'],errors='coerce')
366
+
367
+ # Replace NaN with 0 or handle as required
368
+ df_history.fillna(0, inplace=True)
369
+
370
+ # Update the global timestamp with the last update from history
371
+ columns_to_check = [
372
+ 'symbol', 'side', 'amount', 'changeInAmount', 'markPrice',
373
+ 'entryPrice', 'pnl', 'roe', 'leverage', 'updateTime',
374
+ 'tradeType', 'stopLossPrice', 'takeProfitPrice', 'weightedScoreRatio'
375
+ ]
376
+
377
+ # Adding missing columns with None as default
378
+ for column in columns_to_check:
379
+ if column not in df_history.columns:
380
+ df_history[column] = None
381
+
382
+ # Create a transformed DataFrame for display
383
+ df_transformed = pd.DataFrame({
384
+ 'Pair/Asset': df_history['symbol'],
385
+ 'is long': df_history['side'],
386
+ 'Current size after change': df_history['amount'],
387
+ 'Change in size in Asset': df_history['changeInAmount'],
388
+ 'Change in size in USDT': df_history['changeInAmount'] * -(df_history['markPrice']),
389
+ 'Entry price': df_history['entryPrice'],
390
+ 'Exit price': df_history['markPrice'],
391
+ 'pnl in usdt': df_history['pnl'],
392
+ 'pnl in %': df_history['roe'],
393
+ 'Leverage': df_history['leverage'],
394
+ # 'updatedTime': df_history['updateTime'],
395
+ 'Trade Type': df_history['tradeType'], # New field
396
+ 'Stop Loss Price': df_history['stopLossPrice'], # New field
397
+ 'Take Profit Price': df_history['takeProfitPrice'], # New field
398
+ 'Weighted Score Ratio': df_history['weightedScoreRatio'], # New field
399
+ # 'Transaction Value in USDT': df_history['amount'] * df_history['markPrice'], # New calculation
400
+ 'Profit/Loss Ratio': (df_history['markPrice'] - df_history['entryPrice']) / df_history['entryPrice'] # New calculation
401
+ })
402
+
403
+ if 'closed' in df_history.columns:
404
+ df_transformed['Position closed'] = df_history['closed']
405
+
406
+ st.dataframe(df_transformed)
407
+
408
+ # Add the update timestamp to the transformed DataFrame
409
+
410
+ else:
411
+ st.write("No history found for this position.")
412
+
413
+ def lastUpdated(selected_position):
414
+ position_history = [pos for pos in tradeHistory_positions if pos['i'] == selected_position]
415
+ return position_history[-1]['updateTime']
416
+
417
+ def isClosed(selected_position):
418
+ # Filter trade history for the selected position
419
+ position_history = [pos for pos in tradeHistory_positions if pos['i'] == selected_position]
420
+
421
+ # Check if there are any records for the selected position
422
+ if not position_history:
423
+ return False
424
+
425
+ # Get the most recent entry for the selected position
426
+ last_entry = position_history[-1]
427
+
428
+ # Check if the 'closed' key exists and if it indicates the position is closed
429
+ return last_entry.get('closed', False)
430
+
431
+
432
+
433
+
434
+ def main():
435
+ df_starting = pd.DataFrame(starting_position)
436
+
437
+ for index, row in df_starting.iterrows():
438
+ side = True if float(row['amount']) > 0 else False
439
+ is_closed = isClosed(row['i'])
440
+
441
+ # Generate a unique key for the button
442
+ button_key = f"position_{row['i']}"
443
+
444
+ # Display a button for each trade position
445
+ if st.button(
446
+ f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
447
+ f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
448
+ f"Leverage: {row['leverage']}, isClosed: {is_closed}",
449
+ key=button_key
450
+ ):
451
+ show_position_history(row['i'])
452
+
453
+ if __name__ == "__main__":
454
+ main()