webull api python sample
Webull offers limited support for API access, as it doesn’t have an officially public API. However, a community-maintained **Webull Python API** exists, which is an unofficial wrapper around Webull’s mobile app API endpoints. This allows for actions like retrieving stock data, placing orders, and managing accounts.
Here’s how to get started with **Webull’s Unofficial Python API**:
---
### 1. **Setting Up and Installing the Unofficial Webull API**
- The most popular unofficial Python package for Webull is **webull-api**, available on GitHub.
- Install the Webull Python API wrapper:
```bash
pip install webull
```
### 2. **Authentication and Login**
- Webull requires a **two-factor authentication (2FA)** login process. To use the API, you need to log in and generate a token.
- Webull uses phone numbers or emails for account verification. Make sure to use the correct region code.
#### Example: Logging In
```python
from webull import webull
# Initialize Webull object
wb = webull()
# Log in with phone number (adjust with the appropriate region code if outside the U.S.)
wb.login(phone='YOUR_PHONE_NUMBER', password='YOUR_PASSWORD', device_name='DEVICE_NAME')
```
#### Example: Login with 2FA
After calling `wb.login`, Webull may send a 2FA code to your phone. You can verify this code using:
```python
code = input("Enter the 2FA code sent to your phone: ")
wb.get_mfa(phone='YOUR_PHONE_NUMBER', code=code)
```
### 3. **Retrieving Market Data**
- Once logged in, you can access stock quotes, historical data, and market information.
#### Example: Fetching Stock Quotes
```python
symbol = 'AAPL'
quote = wb.get_quote(symbol=symbol)
print(f"Current price for {symbol}: {quote['close']}")
```
#### Example: Fetching Historical Data
```python
symbol = 'AAPL'
historical_data = wb.get_bars(stock=symbol, interval='1d', count=30) # Last 30 days of daily data
print(historical_data)
```
---
### 4. **Placing Orders**
- The API allows you to place and manage orders for stocks and options.
#### Example: Placing a Market Order
```python
symbol = 'AAPL'
quantity = 1
order = wb.place_order(stock=symbol, action='BUY', orderType='MKT', enforce='GTC', quantity=quantity)
print("Order Response:", order)
```
#### Example: Placing a Limit Order
```python
symbol = 'AAPL'
quantity = 1
limit_price = 150.00 # Set your desired price
order = wb.place_order(stock=symbol, action='BUY', orderType='LMT', enforce='GTC', quantity=quantity, price=limit_price)
print("Limit Order Response:", order)
```
---
### 5. **Managing and Monitoring Orders**
- You can check open orders and cancel orders if needed.
#### Example: Fetching Open Orders
```python
open_orders = wb.get_current_orders()
for order in open_orders:
print("Order ID:", order['orderId'], "Symbol:", order['ticker']['symbol'], "Status:", order['status'])
```
#### Example: Canceling an Order
```python
order_id = 'YOUR_ORDER_ID'
cancel_response = wb.cancel_order(order_id)
print("Cancel Response:", cancel_response)
```
---
### 6. **Retrieving Account Information and Portfolio Data**
- You can check balances, positions, and account status.
#### Example: Fetching Account Balance
```python
account_info = wb.get_account()
print("Cash Balance:", account_info['accountMembers']['cashBalance'])
```
#### Example: Fetching Portfolio Positions
```python
portfolio = wb.get_positions()
for position in portfolio:
print(f"Symbol: {position['ticker']['symbol']}, Quantity: {position['position']}, Market Value: {position['marketValue']}")
```
---
### 7. **Advanced: Streaming Data (WebSocket)**
- The unofficial Webull API wrapper supports streaming data, which is useful for getting real-time updates.
```python
from webull.streamconn import StreamConn
# Initialize streaming connection
stream = StreamConn(debug_flg=True)
# Define a function to process the streaming data
def on_message(message):
print("Stream Message:", message)
# Start streaming data for a specific symbol
stream.start_stream(on_message=on_message, symbols=['AAPL'])
```
---
### 8. **Error Handling and Rate Limiting**
- Webull may enforce rate limits and sometimes may have downtime as it’s unofficial. Wrap your requests in `try-except` blocks for reliability.
### 9. **Logging Out**
- It’s essential to log out to keep your account secure.
```python
wb.logout()
```
---
### Notes and Considerations:
- The unofficial Webull API is community-driven, and Webull may change endpoints at any time, which could disrupt the functionality.
- Since it’s an unofficial wrapper, it lacks the extensive support you’d get with an official API, but it's maintained regularly by contributors.
This setup enables you to automate Webull trading and market data collection in Python.
No Comments have been Posted.