Skip to content

Commit

Permalink
Merge pull request #110 from NelsonDane/develop
Browse files Browse the repository at this point in the history
Schwab V2 Fixes
  • Loading branch information
NelsonDane authored Jan 4, 2024
2 parents 06e078f + 160bb3f commit 157dd30
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 65 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,6 @@ Required `.env` variables:

To get your TOTP secret, follow this [guide](guides/schwabSetup.md).

If you are affected by [this issue](https://github.com/itsjafer/schwab-api/issues/16), please set `SCHWAB_BETA=True` in your `.env` file. For more information see [this issue](https://github.com/NelsonDane/auto-rsa/pull/92).

Note: If you are using Windows, you will need to install playwright manually. See [this guide](guides/playwrightWindows.md) for more information.

### Tradier
Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ pyotp==2.9.0
python-dotenv==1.0.0
requests==2.31.0
robin_stocks==3.0.6
schwab-api==0.2.3
schwab-api2==0.2.9
schwab-api==0.3.8
selenium==4.12.0
tastytrade==6.1
webdriver-manager==4.0.0
74 changes: 13 additions & 61 deletions schwabAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,14 @@
# Schwab API

import os
import traceback
from time import sleep

from dotenv import load_dotenv
from schwab_api import Schwab

from helperAPI import Brokerage, printAndDiscord, printHoldings, stockOrder

# Check for Schwab Beta
load_dotenv()
if os.getenv("SCHWAB_BETA", "").lower() == "true":
from schwab_api2 import Schwab

print("Using Schwab2 API")
SCHWAB_BETA = True
else:
from schwab_api import Schwab

SCHWAB_BETA = False


def close_schwab_sessions(schwab_o: Brokerage):
# Kill playwright sessions
count = 0
for key in schwab_o.get_account_numbers():
print(f"Closing session for {key}")
obj: Schwab = schwab_o.get_logged_in_objects(key)
obj.close_session()
count += 1
if count > 0:
print(f"Closed {count} Schwab sessions")


def schwab_init(SCHWAB_EXTERNAL=None):
# Initialize .env file
Expand Down Expand Up @@ -59,7 +37,7 @@ def schwab_init(SCHWAB_EXTERNAL=None):
password=account[1],
totp_secret=None if account[2] == "NA" else account[2],
)
account_info = schwab.get_account_info()
account_info = schwab.get_account_info_v2()
account_list = list(account_info.keys())
print(f"The following Schwab accounts were found: {account_list}")
print("Logged in to Schwab!")
Expand All @@ -70,6 +48,7 @@ def schwab_init(SCHWAB_EXTERNAL=None):
name, account, account_info[account]["account_value"]
)
except Exception as e:
print(traceback.format_exc())
print(f"Error logging in to Schwab: {e}")
return None
return schwab_obj
Expand All @@ -79,9 +58,10 @@ def schwab_holdings(schwab_o: Brokerage, loop=None):
# Get holdings on each account
for key in schwab_o.get_account_numbers():
obj: Schwab = schwab_o.get_logged_in_objects(key)
all_holdings = obj.get_account_info_v2()
for account in schwab_o.get_account_numbers(key):
try:
holdings = obj.get_account_info()[account]["positions"]
holdings = all_holdings[account]["positions"]
for item in holdings:
sym = item["symbol"]
if sym == "":
Expand All @@ -97,8 +77,6 @@ def schwab_holdings(schwab_o: Brokerage, loop=None):
except Exception as e:
printAndDiscord(f"{key} {account}: Error getting holdings: {e}", loop)
printHoldings(schwab_o, loop)
if SCHWAB_BETA:
close_schwab_sessions(schwab_o)


def schwab_transaction(schwab_o: Brokerage, orderObj: stockOrder, loop=None):
Expand All @@ -122,24 +100,13 @@ def schwab_transaction(schwab_o: Brokerage, orderObj: stockOrder, loop=None):
"Running in DRY mode. No transactions will be made.", loop
)
try:
if SCHWAB_BETA:
# Schwab Beta has different parameters
messages, success = obj.trade(
ticker=s,
action=orderObj.get_action().capitalize(),
qty=orderObj.get_amount(),
order_type="Market",
account_id=str(account),
dry_run=orderObj.get_dry(),
)
else:
messages, success = obj.trade(
ticker=s,
side=orderObj.get_action().capitalize(),
qty=orderObj.get_amount(),
account_id=account,
dry_run=orderObj.get_dry(),
)
messages, success = obj.trade_v2(
ticker=s,
side=orderObj.get_action().capitalize(),
qty=orderObj.get_amount(),
account_id=account,
dry_run=orderObj.get_dry(),
)
printAndDiscord(
f"{key} account {account}: The order verification was "
+ "successful"
Expand All @@ -148,18 +115,6 @@ def schwab_transaction(schwab_o: Brokerage, orderObj: stockOrder, loop=None):
loop,
)
if not success:
if SCHWAB_BETA:
messages = messages["order_messages"]
else:
if (
len(messages) > 1
and "security is deficient" in messages[1]
):
printAndDiscord(
f"Error: {messages[1]}. If this persists, please run with SCHWAB_BETA=True in .env",
loop,
)
continue
printAndDiscord(
f"{key} account {account}: The order verification produced the following messages: {messages}",
loop,
Expand All @@ -169,6 +124,3 @@ def schwab_transaction(schwab_o: Brokerage, orderObj: stockOrder, loop=None):
f"{key} {account}: Error submitting order: {e}", loop
)
sleep(1)
# Kill playwright sessions
if SCHWAB_BETA:
close_schwab_sessions(schwab_o)

0 comments on commit 157dd30

Please sign in to comment.