44"""
55
66import asyncio
7+ from datetime import datetime
78import logging
89import os
9- from datetime import datetime
10+
1011from dotenv import load_dotenv
1112
1213from deltadefi import ApiClient
1516load_dotenv ()
1617
1718# Set up logging
18- logging .basicConfig (level = logging .INFO , format = '%(asctime)s - %(levelname)s - %(message)s' )
19+ logging .basicConfig (
20+ level = logging .INFO , format = "%(asctime)s - %(levelname)s - %(message)s"
21+ )
1922api_key = os .getenv ("DELTADEFI_API_KEY" )
2023
2124# ============================================================================
2225# DATA PARSING HANDLERS FOR EACH WEBSOCKET ENDPOINT
2326# ============================================================================
2427
28+
2529async def handle_trade_message (data ):
2630 """
2731 Handle recent trades WebSocket messages.
28-
32+
2933 Data format: Array of trade objects
30- Example: [{"timestamp": "2025-08-21T03:43:00.204624Z", "symbol": "ADAUSDM",
34+ Example: [{"timestamp": "2025-08-21T03:43:00.204624Z", "symbol": "ADAUSDM",
3135 "side": "sell", "price": 0.7803, "amount": 4.6}, ...]
3236 """
3337 print ("\n 🔄 TRADE STREAM DATA:" )
@@ -37,52 +41,54 @@ async def handle_trade_message(data):
3741 side = trade .get ("side" , "unknown" )
3842 price = trade .get ("price" , 0 )
3943 amount = trade .get ("amount" , 0 )
40-
44+
4145 # Convert timestamp to readable format
4246 try :
43- dt = datetime .fromisoformat (timestamp .replace ('Z' , ' +00:00' ))
47+ dt = datetime .fromisoformat (timestamp .replace ("Z" , " +00:00" ))
4448 readable_time = dt .strftime ("%H:%M:%S" )
45- except :
49+ except Exception :
4650 readable_time = timestamp
47-
51+
4852 side_emoji = "🟢" if side .lower () == "buy" else "🔴"
49- print (f" { i } . { side_emoji } { symbol } : { side .upper ()} { amount } @ ${ price :.4f} at { readable_time } " )
53+ print (
54+ f" { i } . { side_emoji } { symbol } : { side .upper ()} { amount } @ ${ price :.4f} at { readable_time } "
55+ )
5056
5157
5258async def handle_depth_message (data ):
5359 """
5460 Handle market depth WebSocket messages.
55-
56- Data format: {"timestamp": 1755747950587, "bids": [{"price": 0.195, "quantity": 30}],
61+
62+ Data format: {"timestamp": 1755747950587, "bids": [{"price": 0.195, "quantity": 30}],
5763 "asks": [{"price": 0.3495, "quantity": 50.65}]}
5864 """
5965 print ("\n 📊 MARKET DEPTH DATA:" )
6066 timestamp = data .get ("timestamp" , 0 )
6167 bids = data .get ("bids" , [])
6268 asks = data .get ("asks" , [])
63-
69+
6470 # Convert timestamp
6571 try :
6672 dt = datetime .fromtimestamp (timestamp / 1000 ) # Assuming milliseconds
6773 readable_time = dt .strftime ("%H:%M:%S" )
68- except :
74+ except Exception :
6975 readable_time = str (timestamp )
70-
76+
7177 print (f" 📅 Time: { readable_time } " )
72-
78+
7379 # Show top 5 bids and asks
7480 print (" 🟢 BIDS (Buy Orders):" )
7581 for i , bid in enumerate (bids [:5 ], 1 ):
7682 price = bid .get ("price" , 0 )
7783 quantity = bid .get ("quantity" , 0 )
78- print (f" { i } . ${ price :.4f} × { quantity } " )
79-
80- print (" 🔴 ASKS (Sell Orders):" )
84+ print (f" { i } . ${ price :.4f} x { quantity } " )
85+
86+ print (" 🔴 ASKS (Sell Orders):" )
8187 for i , ask in enumerate (asks [:5 ], 1 ):
8288 price = ask .get ("price" , 0 )
8389 quantity = ask .get ("quantity" , 0 )
84- print (f" { i } . ${ price :.4f} × { quantity } " )
85-
90+ print (f" { i } . ${ price :.4f} x { quantity } " )
91+
8692 if bids and asks :
8793 spread = asks [0 ]["price" ] - bids [0 ]["price" ]
8894 spread_pct = (spread / bids [0 ]["price" ]) * 100 if bids [0 ]["price" ] > 0 else 0
@@ -92,31 +98,31 @@ async def handle_depth_message(data):
9298async def handle_price_message (data ):
9399 """
94100 Handle market price WebSocket messages.
95-
101+
96102 Data format: {"type": "Market", "sub_type": "market_price", "price": 0.75}
97103 """
98104 print ("\n 💰 PRICE UPDATE:" )
99105 msg_type = data .get ("type" , "Unknown" )
100- sub_type = data .get ("sub_type" , "unknown" )
106+ sub_type = data .get ("sub_type" , "unknown" )
101107 price = data .get ("price" , 0 )
102-
108+
103109 print (f" 📊 Type: { msg_type } /{ sub_type } " )
104110 print (f" 💵 Current Price: ${ price :.4f} " )
105111
106112
107113async def handle_account_message (data ):
108114 """
109115 Handle account streams WebSocket messages.
110-
116+
111117 Data formats:
112118 - Balance: {"type": "Account", "sub_type": "balance", "balance": [...]}
113119 - Orders: {"type": "Account", "sub_type": "open_orders", "data": [...]}
114120 """
115121 msg_type = data .get ("type" , "Unknown" )
116122 sub_type = data .get ("sub_type" , "unknown" )
117-
123+
118124 print (f"\n 👤 ACCOUNT UPDATE ({ msg_type } /{ sub_type } ):" )
119-
125+
120126 if sub_type == "balance" :
121127 balances = data .get ("balance" , [])
122128 print (" 💰 Account Balances:" )
@@ -125,12 +131,12 @@ async def handle_account_message(data):
125131 free = balance .get ("free" , 0 )
126132 locked = balance .get ("locked" , 0 )
127133 total = free + locked
128-
134+
129135 print (f" { asset .upper ()} : " )
130136 print (f" Free: { free :.6f} " )
131- print (f" Locked: { locked :.6f} " )
137+ print (f" Locked: { locked :.6f} " )
132138 print (f" Total: { total :.6f} " )
133-
139+
134140 elif sub_type == "open_orders" :
135141 orders_data = data .get ("data" , [])
136142 print (" 📋 Open Orders:" )
@@ -141,23 +147,25 @@ async def handle_account_message(data):
141147 order_count += 1
142148 order_id = order .get ("order_id" , "unknown" )
143149 status = order .get ("status" , "unknown" )
144- symbol = order .get ("symbol" , "unknown" )
150+ symbol = order .get ("symbol" , "unknown" )
145151 side = order .get ("side" , "unknown" )
146-
152+
147153 side_emoji = "🟢" if side .lower () == "buy" else "🔴"
148- print (f" { order_count } . { side_emoji } { order_id [:8 ]} ... - { symbol } { side .upper ()} ({ status } )" )
149-
154+ print (
155+ f" { order_count } . { side_emoji } { order_id [:8 ]} ... - { symbol } { side .upper ()} ({ status } )"
156+ )
157+
150158 if order_count == 0 :
151159 print (" No open orders" )
152-
160+
153161 elif sub_type == "trading_history" :
154162 print (" 📈 Trading History Update" )
155163 print (f" Data: { data } " )
156-
164+
157165 elif sub_type == "orders_history" :
158- print (" 📜 Orders History Update" )
166+ print (" 📜 Orders History Update" )
159167 print (f" Data: { data } " )
160-
168+
161169 else :
162170 print (f" ❓ Unknown sub_type: { sub_type } " )
163171 print (f" Raw data: { data } " )
@@ -167,11 +175,12 @@ async def handle_account_message(data):
167175# INDIVIDUAL ENDPOINT EXAMPLES
168176# ============================================================================
169177
178+
170179async def example_trades_stream (symbol = "ADAUSDM" , duration = 30 ):
171180 """Example: Subscribe to recent trades stream."""
172181 print (f"\n 🚀 Starting TRADES stream for { symbol } (running for { duration } s)" )
173182 print ("=" * 60 )
174-
183+
175184 client = ApiClient (api_key = api_key )
176185 ws_client = client .websocket
177186 ws_client .register_handler ("trade" , handle_trade_message )
@@ -190,7 +199,7 @@ async def example_depth_stream(symbol="ADAUSDM", duration=30):
190199 """Example: Subscribe to market depth stream."""
191200 print (f"\n 🚀 Starting DEPTH stream for { symbol } (running for { duration } s)" )
192201 print ("=" * 60 )
193-
202+
194203 client = ApiClient (api_key = api_key )
195204 ws_client = client .websocket
196205 ws_client .register_handler ("depth" , handle_depth_message )
@@ -209,7 +218,7 @@ async def example_price_stream(symbol="ADAUSDM", duration=30):
209218 """Example: Subscribe to market price stream."""
210219 print (f"\n 🚀 Starting PRICE stream for { symbol } (running for { duration } s)" )
211220 print ("=" * 60 )
212-
221+
213222 client = ApiClient (api_key = api_key )
214223 ws_client = client .websocket
215224 ws_client .register_handler ("price" , handle_price_message )
@@ -228,7 +237,7 @@ async def example_account_stream(duration=30):
228237 """Example: Subscribe to account streams."""
229238 print (f"\n 🚀 Starting ACCOUNT stream (running for { duration } s)" )
230239 print ("=" * 60 )
231-
240+
232241 client = ApiClient (api_key = api_key )
233242 ws_client = client .websocket
234243 ws_client .register_handler ("account" , handle_account_message )
@@ -247,26 +256,27 @@ async def example_account_stream(duration=30):
247256# MAIN FUNCTION WITH ENDPOINT SELECTION
248257# ============================================================================
249258
259+
250260async def main ():
251261 """Main function with endpoint selection menu."""
252262 if not api_key :
253263 print ("❌ Error: DELTADEFI_API_KEY not found in environment variables" )
254264 print ("Please set your API key in the .env file" )
255265 return
256-
266+
257267 print ("🔗 DeltaDeFi WebSocket Examples" )
258268 print ("=" * 50 )
259269 print ("Available endpoints:" )
260270 print ("1. Recent Trades Stream" )
261- print ("2. Market Depth Stream" )
271+ print ("2. Market Depth Stream" )
262272 print ("3. Market Price Stream" )
263273 print ("4. Account Streams" )
264274 print ("5. Run All Endpoints (Sequential)" )
265275 print ("0. Quick Trades Test (10 seconds)" )
266-
276+
267277 try :
268278 choice = input ("\n Select endpoint (0-5): " ).strip ()
269-
279+
270280 if choice == "1" :
271281 await example_trades_stream ()
272282 elif choice == "2" :
@@ -288,7 +298,7 @@ async def main():
288298 await example_trades_stream (duration = 10 )
289299 else :
290300 print ("❌ Invalid choice" )
291-
301+
292302 except KeyboardInterrupt :
293303 print ("\n 👋 Exiting..." )
294304 except Exception as e :
0 commit comments