-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebullAPI.py
More file actions
executable file
·280 lines (259 loc) · 12.6 KB
/
Copy pathwebullAPI.py
File metadata and controls
executable file
·280 lines (259 loc) · 12.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
# Nelson Dane
# Webull API
import os
import traceback
from time import sleep
from dotenv import load_dotenv
from webull import webull # type: ignore
from helperAPI import Brokerage, maskString, printAndDiscord, printHoldings, stockOrder
MAX_WB_RETRIES = 3 # Number of times to retry logging in if not successful
MAX_WB_ACCOUNTS = 11 # Different account types
def place_order(obj: webull, account: str, orderObj: stockOrder, s: str):
obj.set_account_id(account)
order = obj.place_order(
stock=s,
action=orderObj.get_action().upper(),
orderType=orderObj.get_price().upper(),
quant=orderObj.get_amount(),
enforce=orderObj.get_time().upper(),
)
if order.get("success") is not None and not order["success"]:
print(f"{order['msg']} Code {order['code']}")
return False
return True
# Initialize Webull
def webull_init(WEBULL_EXTERNAL=None):
printAndDiscord("WARNING")
printAndDiscord("WEBULL IS CURRENTLY NOT SUPPORTED DUE TO API ISSUES.")
printAndDiscord("PLEASE PUT # INFRONT OF YOUR WEBULL CREDENTIALS IN THE .ENV FILE TO DISABLE WEBULL FOR NOW.")
printAndDiscord("CURRENLTY ONLY HOLDINGS ARE SUPPORTED, WHEN PROPER .ENV VARIABLES ARE SET.")
# Initialize .env file
load_dotenv()
# Import Webull account
wb_obj = Brokerage("Webull")
if not os.getenv("WEBULL") and WEBULL_EXTERNAL is None:
print("Webull not found, skipping...")
return None
accounts = (
os.environ["WEBULL"].strip().split(",")
if WEBULL_EXTERNAL is None
else WEBULL_EXTERNAL.strip().split(",")
)
access_token = os.getenv("WB_ACCESS_TOKEN")
refresh_token = os.getenv("WB_REFRESH_TOKEN")
uuid_val = os.getenv("WB_UUID")
account_id = os.getenv("WB_ACCOUNT_ID")
# Apply account index offset for multi-account round-robin support
account_offset = int(os.environ.get("ACCOUNT_INDEX_OFFSET", "0"))
for index, account in enumerate(accounts):
print("Logging in to Webull...")
name = f"Webull {index + 1 + account_offset}"
account = account.split(":")
if len(account) != 4:
print(
f"Invalid number of parameters for {name}, got {len(account)}, expected 4"
)
print("Expected format: username:password:device_id:trading_pin")
return None
try:
for i in range(MAX_WB_RETRIES):
print(f" [{name}] Attempt {i+1}/{MAX_WB_RETRIES}...")
print(f" [{name}] Step 1: Creating webull instance...")
wb = webull()
print(f" [{name}] Step 2: Setting device ID...")
wb.set_did(account[2])
print(f" [{name}] Step 3: Logging in (username: {account[0][:3]}***)...")
if access_token:
print(f" [{name}] Using stored tokens (access_token present)")
else:
print(f" [{name}] No stored tokens, using password login")
login_result = wb.login(
username=account[0],
password=account[1],
accessToken=access_token,
refreshToken=refresh_token,
uuidVal=uuid_val,
accountId=account_id
)
print(f" [{name}] Step 3 result: {login_result}")
print(f" [{name}] Step 4: Getting trade token...")
trade_token_result = wb.get_trade_token(account[3])
print(f" [{name}] Step 4 result: {trade_token_result}")
print(f" [{name}] Step 5: Testing account access...")
id_test = wb.get_account_id(0)
print(f" [{name}] Step 5 result (account_id): {id_test}")
if id_test is not None:
print(f" [{name}] Login successful!")
break
print(f" [{name}] Login failed, account_id was None")
if i == MAX_WB_RETRIES - 1:
raise Exception(
f"Unable to log in to {name} after {i+1} tries. Check credentials."
)
wb_obj.set_logged_in_object(name, wb, "wb")
wb_obj.set_logged_in_object(name, account[3], "trading_pin")
# Get all accounts
print(f" [{name}] Step 6: Fetching account details...")
for i in range(MAX_WB_ACCOUNTS):
id = wb.get_account_id(i)
if id is None:
break
# Webull uses a different internal account ID than displayed in app
ac = wb.get_account(v2=True)
if ac is None:
print(f" [{name}] Warning: get_account(v2=True) returned None")
continue
if "accountSummaryVO" not in ac:
print(f" [{name}] Warning: accountSummaryVO not in response. Keys: {list(ac.keys())}")
continue
ac = ac["accountSummaryVO"]
wb_obj.set_account_number(name, ac["accountNumber"])
print(f" [{name}] Found account: {maskString(ac['accountNumber'])} ({ac.get('accountTypeName', 'Unknown')})")
wb_obj.set_logged_in_object(name, id, ac["accountNumber"])
wb_obj.set_account_type(
name, ac["accountNumber"], ac["accountTypeName"]
)
wb_obj.set_account_totals(
name, ac["accountNumber"], ac["netLiquidationValue"]
)
except Exception as e:
print(traceback.format_exc())
print(f"Error: Unable to log in to Webull: {e}")
return None
print("Logged in to Webull!")
return wb_obj
def webull_holdings(wbo: Brokerage, loop=None):
for key in wbo.get_account_numbers():
for account in wbo.get_account_numbers(key):
obj: webull = wbo.get_logged_in_objects(key, "wb")
internal_account = wbo.get_logged_in_objects(key, account)
try:
# Get account holdings
obj.set_account_id(internal_account)
positions = obj.get_positions()
if positions is None:
positions = obj.get_positions(v2=True)
# List of holdings dictionaries
if positions is not None and positions != []:
for item in positions:
if item.get("items") is not None:
item = item["items"][0]
sym = item["ticker"]["symbol"]
if sym == "":
sym = "Unknown"
if item.get("quantity") is not None:
qty = item["quantity"]
else:
qty = item["position"]
if float(qty) == 0:
continue
mv = round(float(item["marketValue"]) / float(qty), 2)
wbo.set_holdings(key, account, sym, qty, mv)
except Exception as e:
printAndDiscord(f"{key}: Error getting holdings: {e}", loop)
traceback.print_exc()
continue
printHoldings(wbo, loop=loop)
def webull_transaction(wbo: Brokerage, orderObj: stockOrder, loop=None):
print()
print("==============================")
print("Webull")
print("==============================")
print()
for s in orderObj.get_stocks():
for key in wbo.get_account_numbers():
for account in wbo.get_account_numbers(key):
print_account = maskString(account)
obj: webull = wbo.get_logged_in_objects(key, "wb")
internal_account = wbo.get_logged_in_objects(key, account)
# Determine quantity - check for sell_all
if orderObj.get_sell_all():
holdings = wbo.get_holdings(key, account)
if s not in holdings or holdings[s]["quantity"] <= 0:
printAndDiscord(f"{key}: No holdings of {s} to sell in {print_account}, skipping...", loop)
continue
quantity = holdings[s]["quantity"]
printAndDiscord(f"{key}: Selling ALL {quantity} shares of {s} in {print_account}", loop)
else:
quantity = orderObj.get_amount()
printAndDiscord(
f"{key}: {orderObj.get_action()}ing {quantity} of {s}",
loop,
)
if not orderObj.get_dry():
old_amount = quantity
original_action = orderObj.get_action()
# Temporarily set amount for the order logic
orderObj.set_amount(quantity)
try:
if orderObj.get_price() == "market":
orderObj.set_price("MKT")
# If buy stock price < $1 or $0.10,
# buy 100/1000 shares and sell 100/1000 - amount
quote = obj.get_quote(s)
askList = quote.get("askList", [])
bidList = quote.get("bidList", [])
if askList == [] and bidList == []:
printAndDiscord(
f"{key}: {s} is not available for trading", loop
)
raise Exception(f"{s} is not available for trading")
askPrice = float(askList[0]["price"]) if askList != [] else 0
bidPrice = float(bidList[0]["price"]) if bidList != [] else 0
should_dance = False
# Dance if:
# amount < 100 and price < $1
# amount < 1000 and price < $0.10
if (
(askPrice < 1 or bidPrice < 1)
and orderObj.get_amount() < 100
) or (
(askPrice < 0.1 or bidPrice < 0.1)
and orderObj.get_amount() < 1000
):
should_dance = True
if should_dance and orderObj.get_action() == "buy":
# 100 shares if < $1, 1000 shares if < $0.10
big_amount = (
1000 if (askPrice < 0.1 or bidPrice < 0.1) else 100
)
print(
f"Buying {big_amount} then selling {big_amount - orderObj.get_amount()} of {s}"
)
orderObj.set_amount(big_amount)
buy_success = place_order(
obj, internal_account, orderObj, s
)
if not buy_success:
raise Exception(f"Error buying {big_amount} of {s}")
orderObj.set_amount(big_amount - old_amount)
orderObj.set_action("sell")
sleep(1)
order = place_order(obj, internal_account, orderObj, s)
if not order:
raise Exception(
f"Error selling {big_amount - old_amount} of {s}"
)
else:
# Place normal order
order = place_order(obj, internal_account, orderObj, s)
if order:
printAndDiscord(
f"{key}: {orderObj.get_action()} {orderObj.get_amount()} of {s} in {print_account}: Success",
loop,
)
except Exception as e:
printAndDiscord(
f"{key} {print_account}: Error placing order: {e}", loop
)
print(traceback.format_exc())
continue
finally:
# Restore orderObj
orderObj.set_amount(old_amount)
orderObj.set_action(original_action)
else:
printAndDiscord(
f"{key} {print_account}: Running in DRY mode. Transaction would've been: {orderObj.get_action()} {quantity} of {s}",
loop,
)