Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,30 +3,39 @@ import streamlit as st
|
|
3 |
import gspread
|
4 |
from google.oauth2.service_account import Credentials
|
5 |
import ast
|
6 |
-
|
|
|
|
|
7 |
# Define the scope
|
|
|
|
|
|
|
|
|
|
|
8 |
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
9 |
|
10 |
# Service account credentials as a dictionary
|
11 |
service_account_info = {
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
|
25 |
|
26 |
|
27 |
# Add your service account credentials here
|
28 |
}
|
29 |
-
|
|
|
|
|
30 |
# Authenticate using the service account info
|
31 |
creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
|
32 |
client = gspread.authorize(creds)
|
@@ -42,7 +51,6 @@ sheet = workbook.worksheet("LeaderBoardHistory")
|
|
42 |
sheet2 = workbook.worksheet("LeaderBoard")
|
43 |
|
44 |
|
45 |
-
|
46 |
# Extract the data from the Google Sheet into a pandas DataFrame
|
47 |
data = sheet.get_all_values()
|
48 |
data2 = sheet2.get_all_values()
|
@@ -51,7 +59,7 @@ headers2 = data2.pop(0)
|
|
51 |
df = pd.DataFrame(data, columns=headers)
|
52 |
df2 = pd.DataFrame(data2,columns=headers2)
|
53 |
|
54 |
-
|
55 |
|
56 |
def combine_chunks(df):
|
57 |
combined_rows = []
|
@@ -61,6 +69,7 @@ def combine_chunks(df):
|
|
61 |
|
62 |
for uid, group in grouped:
|
63 |
# Combine chunks for each UID
|
|
|
64 |
trade_history_combined = ''.join(group['trade_history'].tolist())
|
65 |
|
66 |
# Create a DataFrame for the combined row
|
@@ -76,37 +85,15 @@ def combine_chunks(df):
|
|
76 |
|
77 |
return combined_df
|
78 |
|
79 |
-
# Sample usage
|
80 |
-
# Assuming df is already defined as your input DataFrame
|
81 |
-
df= combine_chunks(df)
|
82 |
-
|
83 |
-
|
84 |
-
# Ensure data types are correctly set
|
85 |
-
df["U_IDs"] = df["U_IDs"].astype(str)
|
86 |
-
df["trade_history"] = df["trade_history"].astype(str)
|
87 |
-
|
88 |
-
df2["U_IDs"] = df2["U_IDs"].astype(str)
|
89 |
-
df2['Positions'] = df2['Positions'].astype(str)
|
90 |
-
# Fill NaN values with None
|
91 |
df = df.fillna(value=pd.NA)
|
92 |
df = df.where(pd.notnull(df), None)
|
93 |
-
|
94 |
df2 = df2.fillna(value=pd.NA)
|
95 |
df2 = df2.where(pd.notnull(df2), None)
|
96 |
-
# Replace empty lists with None
|
97 |
-
def replace_empty_list(lst):
|
98 |
-
if isinstance(lst, list) and len(lst) == 0:
|
99 |
-
return None
|
100 |
-
else:
|
101 |
-
return lst
|
102 |
|
103 |
-
for col in df.columns:
|
104 |
-
df[col] = df[col].map(replace_empty_list)
|
105 |
|
106 |
-
|
107 |
-
|
108 |
|
109 |
-
# Convert string representations of lists to actual lists
|
110 |
def convert_str_to_list_or_keep(value):
|
111 |
if isinstance(value, str):
|
112 |
try:
|
@@ -117,116 +104,352 @@ def convert_str_to_list_or_keep(value):
|
|
117 |
return value
|
118 |
|
119 |
df = df.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
120 |
-
df2 =df2.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
121 |
|
122 |
uid_input = st.text_input("Enter U_IDs to filter")
|
123 |
|
124 |
-
# Ensure `option` is defined before checking data
|
125 |
option = st.radio("Choose an option:", ["Show Position History", "Show Live Positions"])
|
126 |
|
127 |
if df is not None and uid_input:
|
128 |
-
# Filter DataFrame based on U_IDs
|
129 |
-
filtered_df = df[df['U_IDs'] == uid_input].copy() # Use .copy() to avoid modifying a view
|
130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
def convert_to_list(value):
|
135 |
-
if isinstance(value, str):
|
136 |
-
try:
|
137 |
-
return ast.literal_eval(value)
|
138 |
-
except (ValueError, SyntaxError):
|
139 |
-
# Handle cases where literal_eval fails
|
140 |
-
return value
|
141 |
-
return value
|
142 |
|
143 |
-
#
|
144 |
-
|
145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
-
|
148 |
-
|
149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
|
153 |
-
# Flatten nested lists in 'trade_history'
|
154 |
-
|
155 |
|
156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
|
158 |
-
if not filtered_df.empty:
|
159 |
-
if option == "Show Position History":
|
160 |
-
st.subheader("Position History")
|
161 |
-
# Similar code for displaying position history
|
162 |
-
modified_positions = []
|
163 |
-
new_positions = []
|
164 |
-
sell_positions = []
|
165 |
-
|
166 |
|
167 |
-
|
168 |
-
trade_history = row['trade_history']
|
169 |
|
|
|
170 |
|
171 |
-
|
|
|
172 |
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
if isinstance(record, dict):
|
178 |
-
if 'symbol' in record:
|
179 |
-
new_positions.append(record)
|
180 |
-
if 'positions' in record:
|
181 |
-
positions = record['positions']
|
182 |
-
if isinstance(positions, list):
|
183 |
-
for pos in positions:
|
184 |
-
if 'Modified' in pos:
|
185 |
-
modified_positions.extend(pos['Modified'])
|
186 |
-
if 'NewPosition' in pos:
|
187 |
-
new_positions.extend(pos['NewPosition'])
|
188 |
-
if 'ClosedTrades' in pos:
|
189 |
-
sell_positions.extend(pos['ClosedTrades'])
|
190 |
-
|
191 |
-
if new_positions:
|
192 |
-
new_positions_df = pd.DataFrame(new_positions)
|
193 |
-
st.subheader("New Positions")
|
194 |
-
st.dataframe(new_positions_df)
|
195 |
-
else:
|
196 |
-
st.subheader("New Positions")
|
197 |
-
st.write("No data available")
|
198 |
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
st.
|
|
|
203 |
else:
|
204 |
-
st.
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
|
207 |
-
|
208 |
-
sell_positions_df = pd.DataFrame(sell_positions)
|
209 |
-
st.subheader("Sell Positions")
|
210 |
-
st.dataframe(sell_positions_df)
|
211 |
else:
|
212 |
-
st.
|
213 |
-
|
|
|
|
|
214 |
|
215 |
-
elif option == "Show Live Positions":
|
216 |
-
filtered_df2 = df2[df2['U_IDs'] == uid_input]
|
217 |
-
|
218 |
-
if not filtered_df2.empty:
|
219 |
-
# Assuming 'Positions' contains the list of dictionaries
|
220 |
-
positions_list = filtered_df2['Positions'].iloc[0] # Extracting the first match
|
221 |
-
|
222 |
-
# Convert the list of dictionaries to a DataFrame
|
223 |
-
if isinstance(positions_list, list) and positions_list:
|
224 |
-
positions_df = pd.DataFrame(positions_list)
|
225 |
-
st.subheader("Live Positions")
|
226 |
-
st.dataframe(positions_df)
|
227 |
-
else:
|
228 |
-
st.write("No live positions data available for the given U_ID.")
|
229 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
230 |
|
231 |
-
|
232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import gspread
|
4 |
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 |
+
start_time =datetime.now
|
12 |
+
end_time =datetime.now
|
13 |
+
starting_position = []
|
14 |
+
tradeHistory_positions = []
|
15 |
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
16 |
|
17 |
# Service account credentials as a dictionary
|
18 |
service_account_info = {
|
19 |
|
20 |
+
"type": "service_account",
|
21 |
+
"project_id": "primetrade-433011",
|
22 |
+
"private_key_id": "8bdab2f373343c045c8712c27e34f858132675df",
|
23 |
+
"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",
|
24 |
+
"client_email": "[email protected]",
|
25 |
+
"client_id": "104595139129046465243",
|
26 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
27 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
28 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
29 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myapi-994%40primetrade-433011.iam.gserviceaccount.com",
|
30 |
+
"universe_domain": "googleapis.com"
|
31 |
|
32 |
|
33 |
|
34 |
# Add your service account credentials here
|
35 |
}
|
36 |
+
cookie_str = "p20t=web.740861259.532251DB15AFA4E2C9D5A7A4AA7EB97E" #cookie_str get by logging into binance
|
37 |
+
csrft = "4f341a1a0b78bfb7ddb0bfc9b093ec06" #csrf_token get by logging into binance
|
38 |
+
trade_type= "PERPETUAL" # perpetual or delivery
|
39 |
# Authenticate using the service account info
|
40 |
creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
|
41 |
client = gspread.authorize(creds)
|
|
|
51 |
sheet2 = workbook.worksheet("LeaderBoard")
|
52 |
|
53 |
|
|
|
54 |
# Extract the data from the Google Sheet into a pandas DataFrame
|
55 |
data = sheet.get_all_values()
|
56 |
data2 = sheet2.get_all_values()
|
|
|
59 |
df = pd.DataFrame(data, columns=headers)
|
60 |
df2 = pd.DataFrame(data2,columns=headers2)
|
61 |
|
62 |
+
print("df2",df2.head())
|
63 |
|
64 |
def combine_chunks(df):
|
65 |
combined_rows = []
|
|
|
69 |
|
70 |
for uid, group in grouped:
|
71 |
# Combine chunks for each UID
|
72 |
+
|
73 |
trade_history_combined = ''.join(group['trade_history'].tolist())
|
74 |
|
75 |
# Create a DataFrame for the combined row
|
|
|
85 |
|
86 |
return combined_df
|
87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
df = df.fillna(value=pd.NA)
|
89 |
df = df.where(pd.notnull(df), None)
|
|
|
90 |
df2 = df2.fillna(value=pd.NA)
|
91 |
df2 = df2.where(pd.notnull(df2), None)
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
|
|
|
|
93 |
|
94 |
+
df = combine_chunks(df)
|
95 |
+
# df2 = combine_chunks(df2)
|
96 |
|
|
|
97 |
def convert_str_to_list_or_keep(value):
|
98 |
if isinstance(value, str):
|
99 |
try:
|
|
|
104 |
return value
|
105 |
|
106 |
df = df.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
107 |
+
df2 = df2.apply(lambda col: col.map(convert_str_to_list_or_keep))
|
108 |
|
109 |
uid_input = st.text_input("Enter U_IDs to filter")
|
110 |
|
|
|
111 |
option = st.radio("Choose an option:", ["Show Position History", "Show Live Positions"])
|
112 |
|
113 |
if df is not None and uid_input:
|
|
|
|
|
114 |
|
115 |
+
if option == "Show Position History":
|
116 |
+
st.title("Position History Viewer")
|
117 |
+
# Display starting positions with clickable rows
|
118 |
+
st.header("Starting Positions")
|
119 |
+
|
120 |
+
filtered_df = df[df['U_IDs'] == uid_input].copy()
|
121 |
+
|
122 |
+
if not filtered_df.empty:
|
123 |
+
trade_list = filtered_df['trade_history'].iloc[0]
|
124 |
+
else:
|
125 |
+
st.write("No data found for the provided U_ID.")
|
126 |
+
|
127 |
+
|
128 |
+
unique_lists = []
|
129 |
+
|
130 |
+
def get_amounts_from_positions_and_closed_trades(data):
|
131 |
+
|
132 |
+
|
133 |
+
# Check if 'Modified' key exists and extract amounts
|
134 |
+
if 'Modified' in data:
|
135 |
+
modified_positions = data['Modified']
|
136 |
+
# modified_positions = modified_positions[0]
|
137 |
+
if isinstance(modified_positions, dict) and 'amount' in modified_positions:
|
138 |
+
amount = modified_positions.get('amount')
|
139 |
+
if isinstance(amount, (int, float)): # Check if amount is a number
|
140 |
+
amounts =amount
|
141 |
+
# Check if 'ClosedTrades' key exists and extract amounts
|
142 |
+
if 'ClosedTrades' in data:
|
143 |
+
closed_trades = data['ClosedTrades']
|
144 |
+
closed_trades =closed_trades[0]
|
145 |
+
if isinstance(closed_trades, dict) and 'amount' in closed_trades:
|
146 |
+
amount = closed_trades.get('amount')
|
147 |
+
if isinstance(amount, (int, float)): # Check if amount is a number
|
148 |
+
amounts = amount
|
149 |
+
|
150 |
+
return amounts
|
151 |
|
152 |
+
def get_symbols_from_positions_and_closed_trades(data):
|
153 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
|
155 |
+
# Check if 'Modified' key exists and extract symbols
|
156 |
+
if 'Modified' in data:
|
157 |
+
modified_positions = data['Modified']
|
158 |
+
# modified_positions =modified_positions
|
159 |
+
if isinstance(modified_positions, dict) and 'symbol' in modified_positions:
|
160 |
+
symbol = modified_positions['symbol']
|
161 |
+
|
162 |
+
# Check if 'ClosedTrades' key exists and extract symbols
|
163 |
+
if 'ClosedTrades' in data:
|
164 |
+
closed_trades = data['ClosedTrades']
|
165 |
+
closed_trades =closed_trades[0]
|
166 |
+
if isinstance(closed_trades, dict) and 'symbol' in closed_trades:
|
167 |
+
symbol = closed_trades['symbol']
|
168 |
+
|
169 |
+
return symbol
|
170 |
+
|
171 |
+
for i in range(len(trade_list)):
|
172 |
+
|
173 |
+
if trade_list[i]=="none":
|
174 |
+
continue
|
175 |
+
|
176 |
+
foundCLosed = False
|
177 |
+
changeInAmount = 0
|
178 |
+
|
179 |
+
if 'symbol' in trade_list[i]:
|
180 |
+
symbol = trade_list[i]['symbol']
|
181 |
+
side ="buy" if trade_list[i]['amount']>0 else "sell"
|
182 |
+
amount = trade_list[i]['amount']
|
183 |
+
symbol = trade_list[i]['symbol']
|
184 |
+
if start==False:
|
185 |
+
start_time = trade_list[i]['updateTime']
|
186 |
+
start =True
|
187 |
+
|
188 |
+
trade_list[i]['side'] =side
|
189 |
+
trade_list[i]['changeInAmount'] = changeInAmount
|
190 |
+
trade_list[i]['i'] = i
|
191 |
+
unique_lists.append({"position":trade_list[i]})
|
192 |
+
trade_list[i] = "none"
|
193 |
+
|
194 |
|
195 |
+
else:
|
196 |
+
if 'positions' in trade_list[i]:
|
197 |
+
reached = False
|
198 |
+
# Collect necessary data first before modifying the dictionary
|
199 |
+
for k, v in list(trade_list[i].items()): # Convert to a list to avoid modifying during iteration
|
200 |
+
for entry in v:
|
201 |
+
if 'NewPosition' in entry:
|
202 |
+
new_position = entry.get('NewPosition', {})
|
203 |
+
# Extract symbol and amount
|
204 |
+
symbol = new_position.get('symbol')
|
205 |
+
amount = new_position.get('amount')
|
206 |
+
if start==False:
|
207 |
+
start_time = new_position.get('updateTime')
|
208 |
+
start =True
|
209 |
+
side = "buy" if amount > 0 else "sell"
|
210 |
+
new_position['side'] = side
|
211 |
+
new_position['changeInAmount'] = changeInAmount
|
212 |
+
new_position['i'] = i
|
213 |
+
# Update the entry with the modified 'NewPosition'
|
214 |
+
entry['NewPosition'] = new_position
|
215 |
+
|
216 |
+
# Append the updated trade_list[i] to unique_lists
|
217 |
+
unique_lists.append(trade_list[i])
|
218 |
+
|
219 |
+
reached = True
|
220 |
+
|
221 |
+
# Now safely modify the dictionary after iteration is complete
|
222 |
+
if reached:
|
223 |
+
trade_list[i] = "none"
|
224 |
+
|
225 |
+
# Now safely modify the dictionary after iteration is complete
|
226 |
+
|
227 |
+
|
228 |
+
for j in range(i+1, len(trade_list)):
|
229 |
+
if trade_list[j] == "none":
|
230 |
+
continue
|
231 |
+
|
232 |
+
if 'positions' in trade_list[j] and isinstance(trade_list[j]['positions'], list):
|
233 |
+
for position in trade_list[j]['positions']:
|
234 |
+
# Check if 'Modified' is in the position and is a dict
|
235 |
+
if 'Modified' in position and isinstance(position['Modified'], dict):
|
236 |
+
if start==False:
|
237 |
+
start_time = datetime.now()
|
238 |
+
start =True
|
239 |
+
modified_amount = get_amounts_from_positions_and_closed_trades(position)
|
240 |
+
modified_symbol = get_symbols_from_positions_and_closed_trades(position)
|
241 |
+
|
242 |
+
if modified_amount > 0:
|
243 |
+
modified_side = "buy"
|
244 |
+
else:
|
245 |
+
modified_side = "sell"
|
246 |
+
|
247 |
+
if symbol == modified_symbol and side == modified_side:
|
248 |
+
position['Modified']['side'] = modified_side
|
249 |
+
position['Modified']['changeInAmount'] = amount - modified_amount if modified_amount < 0 else modified_amount - amount
|
250 |
+
position['Modified']['i'] = i
|
251 |
+
amount = modified_amount
|
252 |
+
unique_lists.append(trade_list[j])
|
253 |
+
trade_list[j] = "none"
|
254 |
+
|
255 |
+
# Check if 'ClosedTrades' is in the position and is a tuple
|
256 |
+
if 'ClosedTrades' in position and isinstance(position['ClosedTrades'], tuple):
|
257 |
+
if start==False:
|
258 |
+
start_time = datetime.now()
|
259 |
+
start =True
|
260 |
+
foundCLosed = False
|
261 |
+
closed_trades_tuple = position['ClosedTrades']
|
262 |
+
closed_trades_dict = {
|
263 |
+
'trade_info': closed_trades_tuple[0],
|
264 |
+
'side': closed_trades_tuple[1]
|
265 |
+
}
|
266 |
+
|
267 |
+
closed_amount = get_amounts_from_positions_and_closed_trades(position)
|
268 |
+
closed_symbol = get_symbols_from_positions_and_closed_trades(position)
|
269 |
+
|
270 |
+
if closed_amount > 0:
|
271 |
+
closed_side = "buy"
|
272 |
+
else:
|
273 |
+
closed_side = "sell"
|
274 |
+
|
275 |
+
if symbol == closed_symbol and side == closed_side:
|
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 |
+
print("Reached closed trade")
|
281 |
+
closed_trades_dict['trade_info']['i'] = i # Store index 'i' inside 'ClosedTrades'
|
282 |
+
closed_trades_dict['trade_info']['closed'] = True
|
283 |
+
|
284 |
+
# Update the position with the new dictionary
|
285 |
+
position['ClosedTrades'] = (closed_trades_dict['trade_info'], closed_trades_dict['side'])
|
286 |
+
|
287 |
+
# Append the updated trade_list[j] to unique_lists
|
288 |
+
unique_lists.append(trade_list[j])
|
289 |
+
trade_list[j] = "none"
|
290 |
+
foundCLosed = True
|
291 |
+
break
|
292 |
+
|
293 |
+
# Break the inner loop if a closed trade was found
|
294 |
+
if foundCLosed:
|
295 |
+
break
|
296 |
+
|
297 |
+
|
298 |
+
|
299 |
+
|
300 |
+
for k in range(len(unique_lists)):
|
301 |
+
data = unique_lists[k]
|
302 |
+
|
303 |
+
|
304 |
+
if k ==0:
|
305 |
+
|
306 |
+
|
307 |
+
if 'positions' in data:
|
308 |
+
if isinstance(data['positions'], list):
|
309 |
+
for a in data['positions']:
|
310 |
+
if 'NewPosition' in a:
|
311 |
+
|
312 |
+
position_data = a['NewPosition']
|
313 |
+
starting_position.append(position_data)
|
314 |
+
tradeHistory_positions.append(position_data)
|
315 |
+
|
316 |
+
|
317 |
+
else:
|
318 |
+
if 'position' in data:
|
319 |
+
position_data =data['position']
|
320 |
+
starting_position.append(position_data)
|
321 |
+
tradeHistory_positions.append(position_data)
|
322 |
|
323 |
+
|
324 |
+
|
325 |
+
if 'positions' in data:
|
326 |
+
if isinstance(data['positions'],list):
|
327 |
+
for a in data['positions']:
|
328 |
+
if 'ClosedTrades' in a:
|
329 |
+
position_data = a['ClosedTrades'][0]
|
330 |
+
tradeHistory_positions.append(position_data)
|
331 |
|
|
|
|
|
332 |
|
333 |
|
334 |
+
if 'positions' in data:
|
335 |
+
if isinstance(data['positions'],list):
|
336 |
+
for a in data['positions']:
|
337 |
+
if 'Modified' in a:
|
338 |
+
position_data = a['Modified']
|
339 |
+
tradeHistory_positions.append(position_data)
|
340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
341 |
|
342 |
+
|
|
|
343 |
|
344 |
+
unique_lists =[]
|
345 |
|
346 |
+
elif option == "Show Live Positions":
|
347 |
+
filtered_df2 = df2[df2['U_IDs'] == uid_input]
|
348 |
|
349 |
+
if not filtered_df2.empty:
|
350 |
+
print("Filtered DataFrame for UID:", filtered_df2)
|
351 |
+
|
352 |
+
positions_list = filtered_df2['Positions'].iloc[0] # Extract the first match
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
353 |
|
354 |
+
# Convert the list of dictionaries to a DataFrame
|
355 |
+
if isinstance(positions_list, list) and positions_list:
|
356 |
+
positions_df = pd.DataFrame(positions_list)
|
357 |
+
st.subheader("Live Positions")
|
358 |
+
st.dataframe(positions_df)
|
359 |
else:
|
360 |
+
st.write("No live positions data available for the given U_ID.")
|
361 |
+
|
362 |
+
url = "https://www.binance.com/bapi/futures/v2/public/future/leaderboard/getOtherPerformance"
|
363 |
+
|
364 |
+
def performance_request(uid):
|
365 |
+
heading = {
|
366 |
+
'Clienttype': 'web',
|
367 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
|
368 |
+
'Csrftoken': csrft,
|
369 |
+
'Cookie': cookie_str
|
370 |
+
}
|
371 |
+
payload = {"encryptedUid": uid, "tradeType": trade_type}
|
372 |
+
response = requests.post(url, headers=heading, json=payload)
|
373 |
+
|
374 |
+
if response.status_code == 200:
|
375 |
+
response_data = response.json()
|
376 |
+
if response_data['data'] is not None:
|
377 |
+
other_performance_list = response_data['data']['performanceRetList']
|
378 |
+
if other_performance_list:
|
379 |
+
return other_performance_list
|
380 |
+
else:
|
381 |
+
return None
|
382 |
+
else:
|
383 |
+
return None
|
384 |
+
else:
|
385 |
+
return None
|
386 |
+
|
387 |
+
def check_request(uid):
|
388 |
+
heading = {
|
389 |
+
'Clienttype': 'web',
|
390 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
|
391 |
+
'Csrftoken': csrft,
|
392 |
+
'Cookie': cookie_str
|
393 |
+
}
|
394 |
+
payload = {"encryptedUid": uid, "tradeType": trade_type}
|
395 |
+
|
396 |
+
response = requests.post(url, headers=heading, json=payload)
|
397 |
+
return response.status_code == 200
|
398 |
+
|
399 |
+
# Check if we are logged in
|
400 |
+
if check_request(uid_input):
|
401 |
+
print(f"We are logged in! Fetching performance for UID: {uid_input}")
|
402 |
+
|
403 |
+
# Fetch performance for the specific uid_input
|
404 |
+
performance_data = performance_request(uid_input)
|
405 |
+
if performance_data:
|
406 |
+
print(f"Performance data for UID {uid_input}: {performance_data}")
|
407 |
+
|
408 |
+
# Display performance data as a DataFrame in the UI
|
409 |
+
performance_df = pd.DataFrame(performance_data)
|
410 |
+
st.subheader("Performance Data")
|
411 |
+
st.dataframe(performance_df) # Show the performance data as a table in the UI
|
412 |
|
413 |
+
|
|
|
|
|
|
|
414 |
else:
|
415 |
+
st.write(f"No performance data available for UID {uid_input}")
|
416 |
+
else:
|
417 |
+
st.write("We are logged out, please update cookie_str and csrft!")
|
418 |
+
|
419 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
420 |
|
421 |
+
|
422 |
+
|
423 |
+
def main():
|
424 |
+
|
425 |
+
df_starting = pd.DataFrame(starting_position)
|
426 |
+
|
427 |
+
for index, row in df_starting.iterrows():
|
428 |
+
if row['amount']>0:
|
429 |
+
side =True
|
430 |
+
else:
|
431 |
+
side = False
|
432 |
+
if st.button(f"{row['symbol']} : Long: {side}, Entry Price: {row['entryPrice']}, Market Price :{row['markPrice']} Amount: {row['amount']}, leverage: {row['leverage']}, Time: {row['updateTimeStamp']}"):
|
433 |
+
show_position_history(row['i'])
|
434 |
+
|
435 |
+
def show_position_history(selected_position):
|
436 |
+
st.header(f"History for {selected_position}")
|
437 |
|
438 |
+
# Filter trade history for the selected position
|
439 |
+
position_history = [pos for pos in tradeHistory_positions if pos['i'] == selected_position]
|
440 |
+
|
441 |
+
if position_history:
|
442 |
+
df_history = pd.DataFrame(position_history)
|
443 |
+
st.dataframe(df_history)
|
444 |
+
else:
|
445 |
+
st.write("No history found for this position.")
|
446 |
+
|
447 |
+
if __name__ == "__main__":
|
448 |
+
main()
|
449 |
+
|
450 |
+
|
451 |
+
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
|