GOKULSINGHSHAH123
commited on
Commit
•
116a154
1
Parent(s):
b2d6a81
Update app.py
Browse files
app.py
CHANGED
@@ -4,28 +4,58 @@ 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 ='mfk4Z48kAAivsIiCAqklP/+7v9iY6MxKMo3Rm1zD'
|
22 |
)
|
23 |
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
|
@@ -38,27 +68,26 @@ def convert_str_to_list_or_keep(value):
|
|
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 |
-
|
|
|
48 |
|
49 |
-
|
|
|
50 |
|
51 |
-
|
|
|
52 |
|
53 |
if df is not None and uid_input:
|
54 |
|
55 |
-
if
|
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]
|
@@ -69,19 +98,13 @@ if df is not None and uid_input:
|
|
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
|
@@ -132,7 +155,7 @@ if df is not None and uid_input:
|
|
132 |
|
133 |
if 'symbol' in trade_list[i]:
|
134 |
symbol = trade_list[i]['symbol']
|
135 |
-
side ="buy" if
|
136 |
amount = trade_list[i]['amount']
|
137 |
symbol = trade_list[i]['symbol']
|
138 |
trade_list[i]['side'] =side
|
@@ -153,18 +176,19 @@ if df is not None and uid_input:
|
|
153 |
# Extract symbol and amount
|
154 |
symbol = new_position.get('symbol')
|
155 |
amount = new_position.get('amount')
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
|
|
168 |
# if start==False:
|
169 |
#
|
170 |
# start =True
|
@@ -195,21 +219,21 @@ if df is not None and uid_input:
|
|
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 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
modified_amount = get_amounts_from_positions_and_closed_trades(position)
|
214 |
modified_symbol = get_symbols_from_positions_and_closed_trades(position)
|
215 |
|
@@ -223,7 +247,7 @@ if df is not None and uid_input:
|
|
223 |
st.header(f"Data is from {datetime.now}")
|
224 |
start =True
|
225 |
position['Modified']['side'] = modified_side
|
226 |
-
position['Modified']['changeInAmount'] =
|
227 |
position['Modified']['i'] = i
|
228 |
amount = modified_amount
|
229 |
unique_lists.append(trade_list[j])
|
@@ -250,14 +274,15 @@ if df is not None and uid_input:
|
|
250 |
closed_side = "sell"
|
251 |
|
252 |
if symbol == closed_symbol and side == closed_side:
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
|
|
257 |
|
258 |
closed_trades_dict['side'] = closed_side
|
259 |
trade_info = closed_trades_dict['trade_info']
|
260 |
-
trade_info['changeInAmount'] =
|
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
|
@@ -321,7 +346,7 @@ if df is not None and uid_input:
|
|
321 |
|
322 |
unique_lists =[]
|
323 |
|
324 |
-
elif
|
325 |
filtered_df2 = df2[df2['U_IDs'] == uid_input]
|
326 |
|
327 |
if not filtered_df2.empty:
|
@@ -358,14 +383,16 @@ if df is not None and uid_input:
|
|
358 |
if position_history:
|
359 |
df_history = pd.DataFrame(position_history)
|
360 |
|
361 |
-
|
362 |
-
|
363 |
-
|
|
|
364 |
|
365 |
-
|
366 |
|
367 |
-
# Replace NaN with 0 or handle as required
|
368 |
-
|
|
|
369 |
|
370 |
# Update the global timestamp with the last update from history
|
371 |
columns_to_check = [
|
@@ -391,12 +418,12 @@ if df is not None and uid_input:
|
|
391 |
'pnl in usdt': df_history['pnl'],
|
392 |
'pnl in %': df_history['roe'],
|
393 |
'Leverage': df_history['leverage'],
|
394 |
-
|
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 |
-
|
400 |
'Profit/Loss Ratio': (df_history['markPrice'] - df_history['entryPrice']) / df_history['entryPrice'] # New calculation
|
401 |
})
|
402 |
|
@@ -411,7 +438,7 @@ if df is not None and uid_input:
|
|
411 |
st.write("No history found for this position.")
|
412 |
|
413 |
def lastUpdated(selected_position):
|
414 |
-
position_history = [pos for pos in tradeHistory_positions
|
415 |
return position_history[-1]['updateTime']
|
416 |
|
417 |
def isClosed(selected_position):
|
@@ -435,20 +462,31 @@ if df is not None and uid_input:
|
|
435 |
df_starting = pd.DataFrame(starting_position)
|
436 |
|
437 |
for index, row in df_starting.iterrows():
|
438 |
-
side = True if
|
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
|
|
|
446 |
f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
|
447 |
f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
|
448 |
-
f"Leverage: {row['leverage']},
|
|
|
449 |
key=button_key
|
450 |
-
|
451 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
452 |
|
453 |
if __name__ == "__main__":
|
454 |
main()
|
|
|
4 |
from google.oauth2.service_account import Credentials
|
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 |
+
|
38 |
+
# Fetch and display the corresponding trade history
|
39 |
+
if option:
|
40 |
+
file_key = file_mapping[option]
|
41 |
+
try:
|
42 |
+
# Fetch the file from S3
|
43 |
+
obj = s3.Bucket(bucket_name).Object(file_key).get()
|
44 |
+
|
45 |
+
# Read the CSV into a DataFrame
|
46 |
+
df = pd.read_csv(obj['Body'], index_col=False)
|
47 |
+
|
48 |
+
# Display the DataFrame in Streamlit
|
49 |
+
st.write(f"Displaying data for: **{option}**")
|
50 |
+
except Exception as e:
|
51 |
+
st.error(f"Error fetching the file: {str(e)}")
|
52 |
+
|
53 |
+
|
54 |
+
|
55 |
|
56 |
df2 = pd.read_csv('df.csv')
|
57 |
|
58 |
+
|
59 |
def convert_str_to_list_or_keep(value):
|
60 |
if isinstance(value, str):
|
61 |
try:
|
|
|
68 |
df = df.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
69 |
df2 = df2.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
70 |
|
|
|
|
|
|
|
|
|
71 |
df['positionClosed'] = False
|
72 |
|
73 |
+
if option =="copyLeaderboard":
|
74 |
+
uid_input = int(st.text_input("Enter U_IDs to filter"))
|
75 |
|
76 |
+
else:
|
77 |
+
uid_input = str.upper(st.text_input("Enter U_IDs to filter"))
|
78 |
|
79 |
+
|
80 |
+
option2 = st.radio("Choose an option:", ["Show Position History", "Show Live Positions"])
|
81 |
|
82 |
if df is not None and uid_input:
|
83 |
|
84 |
+
if option2 == "Show Position History":
|
85 |
st.title("Position History Viewer")
|
86 |
# Display starting positions with clickable rows
|
87 |
st.header("Starting Positions")
|
88 |
|
89 |
+
|
90 |
filtered_df = df[df['U_IDs'] == uid_input].copy()
|
|
|
91 |
|
92 |
if not filtered_df.empty:
|
93 |
trade_list = filtered_df['trade_history'].iloc[0]
|
|
|
98 |
unique_lists = []
|
99 |
|
100 |
def get_amounts_from_positions_and_closed_trades(data):
|
|
|
|
|
101 |
|
102 |
|
103 |
# Check if 'Modified' key exists and extract amounts
|
104 |
if 'Modified' in data:
|
105 |
modified_positions = data['Modified']
|
|
|
|
|
|
|
106 |
# modified_positions = modified_positions[0]
|
107 |
if isinstance(modified_positions, dict) and 'amount' in modified_positions:
|
|
|
108 |
amount = modified_positions.get('amount')
|
109 |
if isinstance(amount, (int, float)): # Check if amount is a number
|
110 |
amounts =amount
|
|
|
155 |
|
156 |
if 'symbol' in trade_list[i]:
|
157 |
symbol = trade_list[i]['symbol']
|
158 |
+
side ="buy" if trade_list[i]['amount']>0 else "sell"
|
159 |
amount = trade_list[i]['amount']
|
160 |
symbol = trade_list[i]['symbol']
|
161 |
trade_list[i]['side'] =side
|
|
|
176 |
# Extract symbol and amount
|
177 |
symbol = new_position.get('symbol')
|
178 |
amount = new_position.get('amount')
|
179 |
+
if option != "copyLeaderBoard":
|
180 |
+
if start==False:
|
181 |
+
start_time = new_position.get('updateTime')
|
182 |
+
year = start_time[0]
|
183 |
+
month = start_time[1]
|
184 |
+
day = start_time[2]
|
185 |
+
hour =start_time[3]
|
186 |
+
minute =start_time[4]
|
187 |
+
seconds = start_time[5]
|
188 |
+
dt = datetime(year, month, day, hour, minute, seconds)
|
189 |
+
human_readable_format = dt.strftime('%B %d, %Y, %I:%M:%S %p')
|
190 |
+
st.subheader(f"Data from {human_readable_format}")
|
191 |
+
start=True
|
192 |
# if start==False:
|
193 |
#
|
194 |
# start =True
|
|
|
219 |
for position in trade_list[j]['positions']:
|
220 |
# Check if 'Modified' is in the position and is a dict
|
221 |
if 'Modified' in position and isinstance(position['Modified'], dict):
|
222 |
+
if option!="copyLeaderboard":
|
223 |
+
if start==False:
|
224 |
+
for k,v in position.items():
|
225 |
+
start_time = v['updateTime']
|
226 |
+
|
227 |
+
year = start_time[0]
|
228 |
+
month = start_time[1]
|
229 |
+
day = start_time[2]
|
230 |
+
hour =start_time[3]
|
231 |
+
minute =start_time[4]
|
232 |
+
seconds = start_time[5]
|
233 |
+
dt = datetime(year, month, day, hour, minute, seconds)
|
234 |
+
human_readable_format = dt.strftime('%d-%m-%Y %H:%M:%S')
|
235 |
+
st.subheader(f"Data from {human_readable_format}")
|
236 |
+
start=True
|
237 |
modified_amount = get_amounts_from_positions_and_closed_trades(position)
|
238 |
modified_symbol = get_symbols_from_positions_and_closed_trades(position)
|
239 |
|
|
|
247 |
st.header(f"Data is from {datetime.now}")
|
248 |
start =True
|
249 |
position['Modified']['side'] = modified_side
|
250 |
+
position['Modified']['changeInAmount'] = amount - modified_amount if modified_amount < 0 else modified_amount - amount
|
251 |
position['Modified']['i'] = i
|
252 |
amount = modified_amount
|
253 |
unique_lists.append(trade_list[j])
|
|
|
274 |
closed_side = "sell"
|
275 |
|
276 |
if symbol == closed_symbol and side == closed_side:
|
277 |
+
if option!= "copyLeaderboard":
|
278 |
+
if start==False:
|
279 |
+
for k,v in position.items():
|
280 |
+
start_time = v['updateTime']
|
281 |
+
start =True
|
282 |
|
283 |
closed_trades_dict['side'] = closed_side
|
284 |
trade_info = closed_trades_dict['trade_info']
|
285 |
+
trade_info['changeInAmount'] = amount - closed_amount if closed_amount < 0 else closed_amount - amount
|
286 |
amount = closed_amount
|
287 |
closed_trades_dict['trade_info']['i'] = i # Store index 'i' inside 'ClosedTrades'
|
288 |
closed_trades_dict['trade_info']['closed'] = True
|
|
|
346 |
|
347 |
unique_lists =[]
|
348 |
|
349 |
+
elif option2 == "Show Live Positions":
|
350 |
filtered_df2 = df2[df2['U_IDs'] == uid_input]
|
351 |
|
352 |
if not filtered_df2.empty:
|
|
|
383 |
if position_history:
|
384 |
df_history = pd.DataFrame(position_history)
|
385 |
|
386 |
+
if option =="copyLeaderboard":
|
387 |
+
df_history['changeInAmount'] = pd.to_numeric(df_history['changeInAmount'], errors='coerce')
|
388 |
+
df_history['markPrice'] = pd.to_numeric(df_history['markPrice'], errors='coerce')
|
389 |
+
df_history['entryPrice'] = pd.to_numeric(df_history['entryPrice'], errors='coerce')
|
390 |
|
391 |
+
df_history['amount'] = pd.to_numeric(df_history['amount'],errors='coerce')
|
392 |
|
393 |
+
# Replace NaN with 0 or handle as required
|
394 |
+
df_history.fillna(0, inplace=True)
|
395 |
+
|
396 |
|
397 |
# Update the global timestamp with the last update from history
|
398 |
columns_to_check = [
|
|
|
418 |
'pnl in usdt': df_history['pnl'],
|
419 |
'pnl in %': df_history['roe'],
|
420 |
'Leverage': df_history['leverage'],
|
421 |
+
'updatedTime': df_history['updateTime'],
|
422 |
'Trade Type': df_history['tradeType'], # New field
|
423 |
'Stop Loss Price': df_history['stopLossPrice'], # New field
|
424 |
'Take Profit Price': df_history['takeProfitPrice'], # New field
|
425 |
'Weighted Score Ratio': df_history['weightedScoreRatio'], # New field
|
426 |
+
'Transaction Value in USDT': df_history['amount'] * df_history['markPrice'], # New calculation
|
427 |
'Profit/Loss Ratio': (df_history['markPrice'] - df_history['entryPrice']) / df_history['entryPrice'] # New calculation
|
428 |
})
|
429 |
|
|
|
438 |
st.write("No history found for this position.")
|
439 |
|
440 |
def lastUpdated(selected_position):
|
441 |
+
position_history = [pos for pos in tradeHistory_positions if pos['i'] == selected_position]
|
442 |
return position_history[-1]['updateTime']
|
443 |
|
444 |
def isClosed(selected_position):
|
|
|
462 |
df_starting = pd.DataFrame(starting_position)
|
463 |
|
464 |
for index, row in df_starting.iterrows():
|
465 |
+
side = True if row['amount'] > 0 else False
|
466 |
is_closed = isClosed(row['i'])
|
467 |
|
468 |
# Generate a unique key for the button
|
469 |
button_key = f"position_{row['i']}"
|
470 |
|
471 |
# Display a button for each trade position
|
472 |
+
if option == "copyLeaderboard":
|
473 |
+
if st.button(
|
474 |
f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
|
475 |
f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
|
476 |
+
f"Leverage: {row['leverage']}, "
|
477 |
+
f" isClosed: {is_closed}",
|
478 |
key=button_key
|
479 |
+
):
|
480 |
+
show_position_history(row['i'])
|
481 |
+
else:
|
482 |
+
if st.button(
|
483 |
+
f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, "
|
484 |
+
f"Market Price: {row['markPrice']}, Amount: {row['amount']}, "
|
485 |
+
f"Leverage: {row['leverage']}, TradeTakenAt: {row['updateTime']}, "
|
486 |
+
f"lastUpdated: {lastUpdated(row['i'])}, isClosed: {is_closed}",
|
487 |
+
key=button_key
|
488 |
+
):
|
489 |
+
show_position_history(row['i'])
|
490 |
|
491 |
if __name__ == "__main__":
|
492 |
main()
|