webull_unofficial 1.1.1

The unofficial Rust interface for the WeBull API
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::error::{Result, WebullError};
use log::{debug, error, info, warn};
use parking_lot::RwLock;
use rumqttc::{AsyncClient, Event, MqttOptions, Packet, QoS};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::time::{sleep, Duration};

/// Callback for handling price updates
pub type PriceCallback = Arc<dyn Fn(Value, Value) + Send + Sync>;

/// Callback for handling order updates  
pub type OrderCallback = Arc<dyn Fn(Value, Value) + Send + Sync>;

/// Stream connection configuration
#[derive(Debug, Clone)]
pub struct StreamConfig {
    pub host: String,
    pub port: u16,
    pub use_ssl: bool,
    pub client_id: String,
    pub keep_alive: Duration,
    pub debug: bool,
}

impl Default for StreamConfig {
    fn default() -> Self {
        Self {
            host: "wss://wspush.webullbroker.com/mqtt".to_string(), // Full WebSocket URL with path
            port: 443,
            use_ssl: true,
            client_id: format!("rust_client_{}", uuid::Uuid::new_v4()),
            keep_alive: Duration::from_secs(30),
            debug: false,
        }
    }
}

/// WebSocket/MQTT streaming connection
pub struct StreamConn {
    config: StreamConfig,
    client: Option<AsyncClient>,
    price_callback: Option<PriceCallback>,
    order_callback: Option<OrderCallback>,
    total_volume: Arc<RwLock<HashMap<String, i64>>>,
    subscriptions: Arc<RwLock<Vec<String>>>,
    is_connected: Arc<RwLock<bool>>,
}

impl StreamConn {
    /// Create a new streaming connection
    pub fn new(config: Option<StreamConfig>) -> Self {
        Self {
            config: config.unwrap_or_default(),
            client: None,
            price_callback: None,
            order_callback: None,
            total_volume: Arc::new(RwLock::new(HashMap::new())),
            subscriptions: Arc::new(RwLock::new(Vec::new())),
            is_connected: Arc::new(RwLock::new(false)),
        }
    }

    /// Set price update callback
    pub fn set_price_callback<F>(&mut self, callback: F)
    where
        F: Fn(Value, Value) + Send + Sync + 'static,
    {
        self.price_callback = Some(Arc::new(callback));
    }

    /// Set order update callback
    pub fn set_order_callback<F>(&mut self, callback: F)
    where
        F: Fn(Value, Value) + Send + Sync + 'static,
    {
        self.order_callback = Some(Arc::new(callback));
    }

    /// Connect to the streaming service
    pub async fn connect(&mut self, access_token: &str, did: &str) -> Result<()> {
        let mut mqtt_options = MqttOptions::new(
            did, // Use did as client_id like Python does
            &self.config.host,
            self.config.port,
        );

        mqtt_options.set_keep_alive(self.config.keep_alive);

        // Set authentication - Python uses hardcoded test/test
        mqtt_options.set_credentials("test", "test");

        // Enable WebSocket transport with TLS like Python uses
        use rumqttc::Transport;
        mqtt_options.set_transport(Transport::Wss(Default::default()));

        // Create MQTT client
        let (client, mut eventloop) = AsyncClient::new(mqtt_options, 10);
        self.client = Some(client.clone());

        // Spawn event loop handler
        let is_connected = Arc::clone(&self.is_connected);
        let price_callback = self.price_callback.clone();
        let order_callback = self.order_callback.clone();
        let debug = self.config.debug;
        let total_volume = Arc::clone(&self.total_volume);

        tokio::spawn(async move {
            loop {
                match eventloop.poll().await {
                    Ok(event) => {
                        if debug {
                            debug!("MQTT Event: {:?}", event);
                        }

                        match event {
                            Event::Incoming(Packet::ConnAck(_)) => {
                                info!("Connected to streaming service");
                                *is_connected.write() = true;
                            }
                            Event::Incoming(Packet::Publish(publish)) => {
                                Self::handle_message(
                                    &publish.topic,
                                    &publish.payload,
                                    &price_callback,
                                    &order_callback,
                                    &total_volume,
                                    debug,
                                );
                            }
                            Event::Incoming(Packet::Disconnect) => {
                                warn!("Disconnected from streaming service");
                                *is_connected.write() = false;
                            }
                            _ => {}
                        }
                    }
                    Err(e) => {
                        error!("MQTT Error: {:?}", e);
                        *is_connected.write() = false;
                        sleep(Duration::from_secs(5)).await;
                    }
                }
            }
        });

        // Wait for connection
        let mut attempts = 0;
        while !*self.is_connected.read() && attempts < 10 {
            sleep(Duration::from_millis(500)).await;
            attempts += 1;
        }

        if *self.is_connected.read() {
            // Send initial hello message like Python does
            let hello_msg = if !access_token.is_empty() {
                serde_json::json!({
                    "header": {
                        "did": did,
                        "hl": "en",
                        "app": "desktop",
                        "os": "web",
                        "osType": "windows",
                        "accessToken": access_token
                    }
                })
            } else {
                serde_json::json!({
                    "header": {
                        "did": did,
                        "hl": "en",
                        "app": "desktop",
                        "os": "web",
                        "osType": "windows"
                    }
                })
            };

            // Subscribe to the hello message
            if let Some(ref client) = self.client {
                client
                    .subscribe(hello_msg.to_string(), QoS::AtMostOnce)
                    .await
                    .map_err(|e| WebullError::MqttError(format!("Failed to send hello: {}", e)))?;
            }

            Ok(())
        } else {
            Err(WebullError::WebSocketError(
                "Failed to connect to streaming service".to_string(),
            ))
        }
    }

    /// Handle incoming messages
    fn handle_message(
        topic: &str,
        payload: &[u8],
        price_callback: &Option<PriceCallback>,
        order_callback: &Option<OrderCallback>,
        total_volume: &Arc<RwLock<HashMap<String, i64>>>,
        debug: bool,
    ) {
        // Try to parse the message
        let topic_json = match serde_json::from_str::<Value>(topic) {
            Ok(v) => v,
            Err(e) => {
                if debug {
                    debug!("Failed to parse topic: {}, error: {}", topic, e);
                }
                return;
            }
        };

        let payload_json = match serde_json::from_slice::<Value>(payload) {
            Ok(v) => v,
            Err(e) => {
                if debug {
                    debug!("Failed to parse payload: {:?}, error: {}", payload, e);
                }
                return;
            }
        };

        if debug {
            debug!("Topic: {}, Payload: {}", topic_json, payload_json);
        }

        // Check if it's an order message (from platpush)
        if topic.contains("platpush") {
            if let Some(callback) = order_callback {
                callback(topic_json, payload_json);
            }
        }
        // Check if it's a price message (from wspush)
        else if topic.contains("wspush") || topic.contains("ticker") {
            // Update total volume if applicable
            if let Some(ticker_id) = topic_json.get("tickerId").and_then(|v| v.as_str()) {
                if let Some(volume) = payload_json.get("volume").and_then(|v| v.as_i64()) {
                    total_volume.write().insert(ticker_id.to_string(), volume);
                }
            }

            if let Some(callback) = price_callback {
                callback(topic_json, payload_json);
            }
        }
    }

    /// Subscribe to ticker updates
    pub async fn subscribe_ticker(&mut self, ticker_id: &str, topics: Vec<i32>) -> Result<()> {
        if let Some(client) = &self.client {
            for topic_type in topics {
                let topic = format!("{{\"tickerId\":\"{}\",\"type\":{}}}", ticker_id, topic_type);

                client
                    .subscribe(&topic, QoS::AtLeastOnce)
                    .await
                    .map_err(|e| WebullError::MqttError(e.to_string()))?;

                self.subscriptions.write().push(topic.clone());

                if self.config.debug {
                    debug!("Subscribed to: {}", topic);
                }
            }
            Ok(())
        } else {
            Err(WebullError::WebSocketError("Not connected".to_string()))
        }
    }

    /// Subscribe to order updates
    pub async fn subscribe_orders(&mut self, account_id: &str) -> Result<()> {
        if let Some(client) = &self.client {
            let topic = format!("{{\"secAccountId\":\"{}\"}}", account_id);

            client
                .subscribe(&topic, QoS::AtLeastOnce)
                .await
                .map_err(|e| WebullError::MqttError(e.to_string()))?;

            self.subscriptions.write().push(topic.clone());

            if self.config.debug {
                debug!("Subscribed to orders: {}", topic);
            }
            Ok(())
        } else {
            Err(WebullError::WebSocketError("Not connected".to_string()))
        }
    }

    /// Unsubscribe from ticker updates
    pub async fn unsubscribe_ticker(&mut self, ticker_id: &str, topics: Vec<i32>) -> Result<()> {
        if let Some(client) = &self.client {
            for topic_type in topics {
                let topic = format!("{{\"tickerId\":\"{}\",\"type\":{}}}", ticker_id, topic_type);

                client
                    .unsubscribe(&topic)
                    .await
                    .map_err(|e| WebullError::MqttError(e.to_string()))?;

                self.subscriptions.write().retain(|t| t != &topic);

                if self.config.debug {
                    debug!("Unsubscribed from: {}", topic);
                }
            }
            Ok(())
        } else {
            Err(WebullError::WebSocketError("Not connected".to_string()))
        }
    }

    /// Unsubscribe from all topics
    pub async fn unsubscribe_all(&mut self) -> Result<()> {
        if let Some(client) = &self.client {
            let subscriptions = self.subscriptions.read().clone();
            for topic in subscriptions {
                client
                    .unsubscribe(&topic)
                    .await
                    .map_err(|e| WebullError::MqttError(e.to_string()))?;
            }
            self.subscriptions.write().clear();
            Ok(())
        } else {
            Err(WebullError::WebSocketError("Not connected".to_string()))
        }
    }

    /// Disconnect from the streaming service
    pub async fn disconnect(&mut self) -> Result<()> {
        if self.client.is_some() {
            self.unsubscribe_all().await?;
            if let Some(client) = self.client.take() {
                client
                    .disconnect()
                    .await
                    .map_err(|e| WebullError::MqttError(e.to_string()))?;
            }
            *self.is_connected.write() = false;
            Ok(())
        } else {
            Ok(())
        }
    }

    /// Check if connected
    pub fn is_connected(&self) -> bool {
        *self.is_connected.read()
    }

    /// Get current subscriptions
    pub fn get_subscriptions(&self) -> Vec<String> {
        self.subscriptions.read().clone()
    }

    /// Get total volume for a ticker
    pub fn get_total_volume(&self, ticker_id: &str) -> Option<i64> {
        self.total_volume.read().get(ticker_id).copied()
    }
}

/// Topic types for streaming subscriptions
pub struct TopicTypes;

impl TopicTypes {
    pub const TICKER_STATUS: i32 = 101;
    pub const TICKER_QUOTE: i32 = 102;
    pub const TICKER_TRADE: i32 = 103;
    pub const TICKER_BOOK: i32 = 104;
    pub const TICKER_QUOTE_AND_TRADE: i32 = 105;
    pub const TICKER_QUOTE_TRADE_OPTIONAL: i32 = 106;
    pub const TICKER_TRADE_AND_BOOK: i32 = 107;
    pub const TICKER_FULL: i32 = 108;

    /// Get all available topic types
    pub fn all() -> Vec<i32> {
        vec![
            Self::TICKER_STATUS,
            Self::TICKER_QUOTE,
            Self::TICKER_TRADE,
            Self::TICKER_BOOK,
            Self::TICKER_QUOTE_AND_TRADE,
            Self::TICKER_QUOTE_TRADE_OPTIONAL,
            Self::TICKER_TRADE_AND_BOOK,
            Self::TICKER_FULL,
        ]
    }

    /// Get basic subscription topics
    pub fn basic() -> Vec<i32> {
        vec![Self::TICKER_QUOTE, Self::TICKER_TRADE, Self::TICKER_BOOK]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_stream_config_default() {
        let config = StreamConfig::default();
        assert!(config.use_ssl);
        assert_eq!(config.port, 443);
    }

    #[test]
    fn test_topic_types() {
        let all_topics = TopicTypes::all();
        assert_eq!(all_topics.len(), 8);

        let basic_topics = TopicTypes::basic();
        assert_eq!(basic_topics.len(), 3);
    }
}