0
# Trading Operations
1
2
Comprehensive trading functionality for placing, modifying, and cancelling orders across stocks, options, and cryptocurrencies. Supports various order types, time-in-force options, and advanced trading strategies.
3
4
## Prerequisites
5
6
All trading operations require:
7
1. Successful login with valid session
8
2. Trading token obtained via `get_trade_token()`
9
10
## Capabilities
11
12
### Stock Order Placement
13
14
Place buy and sell orders for stocks with various order types and execution options.
15
16
```python { .api }
17
def place_order(self, stock=None, tId=None, price=0, action='BUY', orderType='LMT', enforce='GTC', quant=0, outsideRegularTradingHour=True, stpPrice=None, trial_value=0, trial_type='DOLLAR'):
18
"""
19
Place a stock order.
20
21
Parameters:
22
- stock (str, optional): Stock symbol (e.g., 'AAPL')
23
- tId (int, optional): Ticker ID (alternative to stock symbol)
24
- price (float): Order price for limit orders
25
- action (str): Order action - 'BUY' or 'SELL'
26
- orderType (str): Order type - 'LMT', 'MKT', 'STP', 'STP_LMT'
27
- enforce (str): Time in force - 'GTC', 'DAY', 'IOC', 'FOK'
28
- quant (int): Quantity of shares to trade
29
- outsideRegularTradingHour (bool): Allow extended hours trading
30
- stpPrice (float, optional): Stop price for stop orders
31
- trial_value (float, optional): Trial order value for testing
32
- trial_type (str): Trial type - 'DOLLAR' or 'PERCENTAGE'
33
34
Returns:
35
dict: Order placement result with order ID and status
36
37
Raises:
38
ValueError: If required parameters are missing or invalid
39
"""
40
```
41
42
Usage examples:
43
44
```python
45
# Market buy order
46
result = wb.place_order(
47
stock='AAPL',
48
action='BUY',
49
orderType='MKT',
50
quant=100
51
)
52
53
# Limit sell order
54
result = wb.place_order(
55
stock='TSLA',
56
price=250.00,
57
action='SELL',
58
orderType='LMT',
59
enforce='DAY',
60
quant=50
61
)
62
63
# Stop-loss order
64
result = wb.place_order(
65
stock='MSFT',
66
action='SELL',
67
orderType='STP',
68
stpPrice=300.00,
69
quant=25
70
)
71
```
72
73
### Order Modification
74
75
Modify existing orders by changing price, quantity, or other parameters.
76
77
```python { .api }
78
def modify_order(self, order=None, order_id=0, stock=None, tId=None, price=0, action=None, orderType=None, enforce=None, quant=0, outsideRegularTradingHour=None):
79
"""
80
Modify an existing order.
81
82
Parameters:
83
- order (dict, optional): Complete order object to modify
84
- order_id (int): Order ID to modify
85
- stock (str, optional): Stock symbol
86
- tId (int, optional): Ticker ID
87
- price (float): New order price
88
- action (str, optional): New order action if changing
89
- orderType (str, optional): New order type if changing
90
- enforce (str, optional): New time in force if changing
91
- quant (int): New quantity
92
- outsideRegularTradingHour (bool, optional): New extended hours setting
93
94
Returns:
95
dict: Modification result
96
"""
97
```
98
99
Usage example:
100
101
```python
102
# Get current orders to find order to modify
103
orders = wb.get_current_orders()
104
order_to_modify = orders[0] # First order
105
106
# Modify price and quantity
107
result = wb.modify_order(
108
order_id=order_to_modify['orderId'],
109
price=155.00,
110
quant=75
111
)
112
```
113
114
### Order Cancellation
115
116
Cancel individual orders or all pending orders.
117
118
```python { .api }
119
def cancel_order(self, order_id=''):
120
"""
121
Cancel a specific order.
122
123
Parameters:
124
- order_id (str): ID of order to cancel
125
126
Returns:
127
dict: Cancellation result
128
"""
129
130
def cancel_all_orders(self):
131
"""
132
Cancel all pending orders.
133
134
Returns:
135
dict: Bulk cancellation result
136
"""
137
```
138
139
Usage examples:
140
141
```python
142
# Cancel specific order
143
result = wb.cancel_order('12345678')
144
145
# Cancel all pending orders
146
result = wb.cancel_all_orders()
147
```
148
149
### Advanced Order Types - OTOCO
150
151
One-Triggers-Other-Cancels orders for automated profit-taking and stop-loss strategies.
152
153
```python { .api }
154
def place_order_otoco(self, stock='', price='', stop_loss_price='', limit_profit_price='', time_in_force='DAY', quant=0):
155
"""
156
Place One-Triggers-Other-Cancels bracket order.
157
158
Parameters:
159
- stock (str): Stock symbol
160
- price (str): Entry order price
161
- stop_loss_price (str): Stop loss price
162
- limit_profit_price (str): Take profit price
163
- time_in_force (str): Time in force - 'DAY' or 'GTC'
164
- quant (int): Order quantity
165
166
Returns:
167
dict: OTOCO order placement result with multiple order IDs
168
"""
169
170
def modify_order_otoco(self, order_id1='', order_id2='', order_id3='', stock='', price='', stop_loss_price='', limit_profit_price='', time_in_force='DAY', quant=0):
171
"""
172
Modify existing OTOCO order.
173
174
Parameters:
175
- order_id1 (str): Primary order ID
176
- order_id2 (str): Stop loss order ID
177
- order_id3 (str): Take profit order ID
178
- stock (str): Stock symbol
179
- price (str): New entry price
180
- stop_loss_price (str): New stop loss price
181
- limit_profit_price (str): New take profit price
182
- time_in_force (str): New time in force
183
- quant (int): New quantity
184
185
Returns:
186
dict: Modification result
187
"""
188
189
def cancel_order_otoco(self, combo_id=''):
190
"""
191
Cancel entire OTOCO order bracket.
192
193
Parameters:
194
- combo_id (str): OTOCO combination ID
195
196
Returns:
197
dict: Cancellation result
198
"""
199
```
200
201
Usage example:
202
203
```python
204
# Place bracket order with stop loss and take profit
205
result = wb.place_order_otoco(
206
stock='AAPL',
207
price='150.00',
208
stop_loss_price='145.00',
209
limit_profit_price='160.00',
210
time_in_force='GTC',
211
quant=100
212
)
213
```
214
215
### Cryptocurrency Trading
216
217
Trade cryptocurrencies with specialized order handling.
218
219
```python { .api }
220
def place_order_crypto(self, stock=None, tId=None, price=0, action='BUY', orderType='LMT', enforce='DAY', entrust_type='QTY', quant=0, outsideRegularTradingHour=False):
221
"""
222
Place cryptocurrency order.
223
224
Parameters:
225
- stock (str, optional): Crypto symbol (e.g., 'BTCUSD')
226
- tId (int, optional): Ticker ID for cryptocurrency
227
- price (float): Order price
228
- action (str): 'BUY' or 'SELL'
229
- orderType (str): Order type - 'LMT', 'MKT'
230
- enforce (str): Time in force - 'DAY', 'GTC', 'IOC', 'FOK'
231
- entrust_type (str): 'QTY' for quantity-based or 'AMT' for amount-based
232
- quant (float): Quantity or amount to trade
233
- outsideRegularTradingHour (bool): Extended hours (always available for crypto)
234
235
Returns:
236
dict: Crypto order placement result
237
"""
238
```
239
240
Usage example:
241
242
```python
243
# Buy Bitcoin with limit order
244
result = wb.place_order_crypto(
245
stock='BTCUSD',
246
price=45000.00,
247
action='BUY',
248
orderType='LMT',
249
entrust_type='QTY',
250
quant=0.1
251
)
252
```
253
254
### Options Trading
255
256
Place, modify, and cancel options orders with specialized options handling.
257
258
```python { .api }
259
def place_order_option(self, optionId=None, lmtPrice=None, stpPrice=None, action=None, orderType='LMT', enforce='DAY', quant=0):
260
"""
261
Place options order.
262
263
Parameters:
264
- optionId (int): Options contract ID
265
- lmtPrice (float, optional): Limit price for limit orders
266
- stpPrice (float, optional): Stop price for stop orders
267
- action (str): 'BUY' or 'SELL'
268
- orderType (str): 'LMT', 'MKT', 'STP', 'STP_LMT'
269
- enforce (str): Time in force - 'DAY', 'GTC', 'IOC', 'FOK'
270
- quant (int): Number of option contracts
271
272
Returns:
273
dict: Options order placement result
274
"""
275
276
def modify_order_option(self, order=None, lmtPrice=None, stpPrice=None, enforce=None, quant=0):
277
"""
278
Modify existing options order.
279
280
Parameters:
281
- order (dict): Existing options order to modify
282
- lmtPrice (float, optional): New limit price
283
- stpPrice (float, optional): New stop price
284
- enforce (str, optional): New time in force
285
- quant (int): New quantity
286
287
Returns:
288
dict: Modification result
289
"""
290
```
291
292
Usage example:
293
294
```python
295
# First get options chain to find option ID
296
options = wb.get_options(stock='AAPL', expireDate='2024-12-20')
297
call_option = options[0] # First call option
298
299
# Buy call option
300
result = wb.place_order_option(
301
optionId=call_option['derivativeId'],
302
lmtPrice=5.50,
303
action='BUY',
304
orderType='LMT',
305
quant=1
306
)
307
```
308
309
### Trading Validation
310
311
Check if a stock is tradable before placing orders.
312
313
```python { .api }
314
def get_tradable(self, stock=''):
315
"""
316
Check if a stock is tradable on Webull.
317
318
Parameters:
319
- stock (str): Stock symbol to check
320
321
Returns:
322
dict: Trading availability information
323
"""
324
```
325
326
Usage example:
327
328
```python
329
# Check if stock is tradable
330
tradable_info = wb.get_tradable('AAPL')
331
if tradable_info['tradable']:
332
# Proceed with order placement
333
wb.place_order(stock='AAPL', price=150.00, action='BUY', quant=10)
334
```
335
336
## Order Types Reference
337
338
### Supported Order Types
339
340
- **LMT (Limit)**: Order executes at specified price or better
341
- **MKT (Market)**: Order executes immediately at current market price
342
- **STP (Stop)**: Stop order becomes market order when stop price reached
343
- **STP_LMT (Stop Limit)**: Stop order becomes limit order when stop price reached
344
345
### Time in Force Options
346
347
- **GTC (Good Till Cancelled)**: Order remains active until executed or cancelled
348
- **DAY**: Order expires at end of trading day
349
- **IOC (Immediate or Cancel)**: Execute immediately, cancel unfilled portion
350
- **FOK (Fill or Kill)**: Execute entire order immediately or cancel
351
352
### Trading Actions
353
354
- **BUY**: Purchase securities
355
- **SELL**: Sell securities (must own shares or have approved short selling)
356
357
## Error Handling
358
359
Common trading errors and handling:
360
361
```python
362
try:
363
result = wb.place_order(
364
stock='AAPL',
365
price=150.00,
366
action='BUY',
367
quant=100
368
)
369
print(f"Order placed successfully: {result['orderId']}")
370
371
except ValueError as e:
372
if "trade token" in str(e).lower():
373
print("Need to get trade token first")
374
wb.get_trade_token('your_trading_password')
375
elif "insufficient" in str(e).lower():
376
print("Insufficient buying power")
377
else:
378
print(f"Order failed: {e}")
379
```
380
381
## Complete Trading Example
382
383
```python
384
from webull import webull
385
386
wb = webull()
387
388
# Login and authenticate
389
wb.login('your_email@example.com', 'your_password')
390
wb.get_trade_token('your_trading_password')
391
392
try:
393
# Check if stock is tradable
394
tradable = wb.get_tradable('AAPL')
395
if not tradable['tradable']:
396
print("AAPL is not tradable")
397
exit()
398
399
# Place initial buy order
400
buy_result = wb.place_order(
401
stock='AAPL',
402
price=150.00,
403
action='BUY',
404
orderType='LMT',
405
enforce='GTC',
406
quant=100
407
)
408
409
print(f"Buy order placed: {buy_result['orderId']}")
410
411
# Check order status
412
orders = wb.get_current_orders()
413
for order in orders:
414
if order['orderId'] == buy_result['orderId']:
415
print(f"Order status: {order['status']}")
416
417
# Place bracket order for risk management
418
bracket_result = wb.place_order_otoco(
419
stock='TSLA',
420
price='250.00',
421
stop_loss_price='240.00',
422
limit_profit_price='270.00',
423
quant=50
424
)
425
426
print(f"Bracket order placed: {bracket_result}")
427
428
except ValueError as e:
429
print(f"Trading error: {e}")
430
```