-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot_ui.py
More file actions
327 lines (258 loc) Β· 10.6 KB
/
bot_ui.py
File metadata and controls
327 lines (258 loc) Β· 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python3
"""
Binance Futures Trading Bot - Streamlit Web UI
User-friendly web interface for trading operations
"""
import streamlit as st
import pandas as pd
import json
import time
from datetime import datetime
import threading
from advanced_binance_futures_bot import BinanceFuturesREST, BinanceFuturesWS, TWAPOrder
# Page configuration
st.set_page_config(
page_title="Binance Futures Trading Bot",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
# Initialize session state
if 'orders_history' not in st.session_state:
st.session_state.orders_history = []
if 'ticker_data' not in st.session_state:
st.session_state.ticker_data = {}
if 'rest_client' not in st.session_state:
st.session_state.rest_client = None
if 'ws_client' not in st.session_state:
st.session_state.ws_client = None
def initialize_clients(api_key, secret_key):
"""Initialize REST and WebSocket clients"""
try:
rest_client = BinanceFuturesREST(api_key, secret_key)
ws_client = BinanceFuturesWS(api_key, secret_key)
# Test connection
rest_client._get_server_time()
st.session_state.rest_client = rest_client
st.session_state.ws_client = ws_client
return True, "β
Connected successfully!"
except Exception as e:
return False, f"β Connection failed: {str(e)}"
def place_order_ui():
"""Order placement interface"""
st.subheader("π Place Orders")
if not st.session_state.rest_client:
st.error("Please configure API credentials first!")
return
col1, col2, col3 = st.columns(3)
with col1:
symbol = st.text_input("Symbol", value="BTCUSDT", help="Trading pair (e.g., BTCUSDT)")
side = st.selectbox("Side", ["BUY", "SELL"])
with col2:
order_type = st.selectbox("Order Type", ["MARKET", "LIMIT", "STOP_MARKET"])
quantity = st.number_input("Quantity", min_value=0.0, step=0.001, format="%.6f")
with col3:
price = None
stop_price = None
if order_type in ["LIMIT", "STOP_MARKET"]:
price = st.number_input("Price", min_value=0.0, step=0.01, format="%.6f")
if order_type == "STOP_MARKET":
stop_price = st.number_input("Stop Price", min_value=0.0, step=0.01, format="%.6f")
# Order placement buttons
col1, col2, col3 = st.columns(3)
with col1:
if st.button("π Place Order", type="primary"):
try:
with st.spinner("Placing order..."):
result = st.session_state.rest_client.place_order(
symbol=symbol,
side=side,
order_type=order_type,
quantity=quantity,
price=price,
stop_price=stop_price
)
# Add to history
st.session_state.orders_history.insert(0, {
'timestamp': datetime.now(),
'order_data': result
})
st.success(f"β
Order placed successfully! ID: {result.get('orderId')}")
st.rerun()
except Exception as e:
st.error(f"β Order failed: {str(e)}")
def twap_order_ui():
"""TWAP order interface"""
st.subheader("β±οΈ TWAP Orders")
if not st.session_state.rest_client:
st.error("Please configure API credentials first!")
return
col1, col2 = st.columns(2)
with col1:
twap_symbol = st.text_input("TWAP Symbol", value="BTCUSDT")
twap_side = st.selectbox("TWAP Side", ["BUY", "SELL"])
with col2:
twap_quantity = st.number_input("Total Quantity", min_value=0.0, step=0.001, format="%.6f")
twap_slices = st.number_input("Number of Slices", min_value=1, value=5)
twap_interval = st.number_input("Interval (seconds)", min_value=1, value=30)
if st.button("π― Execute TWAP Order"):
try:
with st.spinner("Executing TWAP order..."):
twap_executor = TWAPOrder(st.session_state.rest_client)
# Create a progress bar
progress_bar = st.progress(0)
status_text = st.empty()
def update_progress(current_slice, total_slices):
progress = current_slice / total_slices
progress_bar.progress(progress)
status_text.text(f"Executing slice {current_slice}/{total_slices}")
# Execute TWAP with progress updates
results = []
slice_quantity = twap_quantity / twap_slices
for i in range(twap_slices):
update_progress(i + 1, twap_slices)
result = st.session_state.rest_client.place_order(
symbol=twap_symbol,
side=twap_side,
order_type='MARKET',
quantity=slice_quantity
)
results.append(result)
# Add to history
st.session_state.orders_history.insert(0, {
'timestamp': datetime.now(),
'order_data': result
})
if i < twap_slices - 1:
time.sleep(twap_interval)
progress_bar.progress(1.0)
status_text.text("TWAP order completed!")
st.success(f"β
TWAP order completed! {len(results)} slices executed")
st.rerun()
except Exception as e:
st.error(f"β TWAP order failed: {str(e)}")
def display_order_history():
"""Display order history"""
st.subheader("π Order History")
if not st.session_state.orders_history:
st.info("No orders placed yet")
return
# Convert to DataFrame for display
display_data = []
for entry in st.session_state.orders_history[:20]: # Show last 20 orders
order = entry['order_data']
display_data.append({
'Time': entry['timestamp'].strftime('%H:%M:%S'),
'Order ID': order.get('orderId', 'N/A'),
'Symbol': order.get('symbol', 'N/A'),
'Side': order.get('side', 'N/A'),
'Type': order.get('type', 'N/A'),
'Quantity': order.get('origQty', 'N/A'),
'Price': order.get('price', 'MARKET'),
'Status': order.get('status', 'N/A')
})
df = pd.DataFrame(display_data)
st.dataframe(df, use_container_width=True)
def display_market_data():
"""Display live market data"""
st.subheader("π Market Data")
# This would be populated by WebSocket in a real implementation
if st.session_state.ticker_data:
col1, col2, col3, col4 = st.columns(4)
for i, (symbol, data) in enumerate(st.session_state.ticker_data.items()):
col = [col1, col2, col3, col4][i % 4]
with col:
price_change = float(data.get('priceChangePercent', 0))
color = "green" if price_change >= 0 else "red"
st.metric(
label=symbol,
value=f"${float(data.get('lastPrice', 0)):.2f}",
delta=f"{price_change:.2f}%",
delta_color=color
)
else:
st.info("Market data will appear here when WebSocket is connected")
def main():
"""Main Streamlit application"""
# Header
st.title("π Binance Futures Trading Bot")
st.markdown("*Advanced trading interface for Binance Futures Testnet*")
# Sidebar for API configuration
with st.sidebar:
st.header("π API Configuration")
api_key = st.text_input("API Key", type="password", help="Your Binance API Key")
secret_key = st.text_input("Secret Key", type="password", help="Your Binance Secret Key")
if st.button("π Connect to Binance"):
if api_key and secret_key:
success, message = initialize_clients(api_key, secret_key)
if success:
st.success(message)
else:
st.error(message)
else:
st.error("Please provide both API key and secret key")
# Connection status
if st.session_state.rest_client:
st.success("π’ Connected")
# Server time
try:
server_time = st.session_state.rest_client._get_server_time()
st.write(f"**Server Time:** {datetime.fromtimestamp(server_time / 1000).strftime('%H:%M:%S')}")
except:
pass
else:
st.error("π΄ Disconnected")
st.markdown("---")
st.markdown("### π Quick Guide")
st.markdown("""
1. **Enter API credentials** and connect
2. **Place orders** using the main interface
3. **Monitor execution** in real-time
4. **View history** of all orders
""")
# Main content area
if st.session_state.rest_client:
# Create tabs for different sections
tab1, tab2, tab3, tab4 = st.tabs(["π Trading", "β±οΈ TWAP", "π History", "π Market"])
with tab1:
place_order_ui()
with tab2:
twap_order_ui()
with tab3:
display_order_history()
with tab4:
display_market_data()
else:
st.warning("β οΈ Please configure your API credentials in the sidebar to start trading")
# Show demo information
st.markdown("### π― Features")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
**Order Types**
- Market Orders
- Limit Orders
- Stop-Market Orders
- TWAP Orders
""")
with col2:
st.markdown("""
**Real-time Features**
- WebSocket integration
- Live order updates
- Market data streams
- Account balance updates
""")
with col3:
st.markdown("""
**Safety Features**
- Precision validation
- Exchange filters
- Error handling
- Comprehensive logging
""")
# Footer
st.markdown("---")
st.markdown("*π Testnet Environment - No real money involved*")
if __name__ == '__main__':
main()