Here are several Python scripts to provide CLI access to your Schwab (formerly TD Ameritrade) brokerage account. The necessary Schwab token management is broken out into re-usable modules you can use in other software.
[schwab_cli.py]
A command-line playground for Python access to Schwab brokerage accounts. Includes commands to:
- Quote equities
- View currently held positions
- Buy/sell equities (either on-demand or when specified price conditions occur)
- Summarize daily transactions
quote [symbol1,symbol2,...]
To get a quote on Apple, type
> quote aapl
{'symbol': 'AAPL', 'last': 229.499, 'ask': 229.55, 'bid': 229.47}
pos [symbol1,symbol2,...]
To see current position on Reddit, type
> pos rddt
RDDT: 30 @ 176.566666666667 (201.09); gain/loss: 735.70
[b | s | bs | ss | ts] [symbol] [num shares] <limit | offset | 'ask' | 'bid'>
To buy 100 shares of Apple at the market price:
> b aapl 100
To buy 100 shares of Apple at $213.50/share:
> b aapl 100 213.50
To buy 100 shares of Apple at the bidding (highest buying offer) price:
> b aapl 100 bid
To sell 100 shares of Apple at the asking (lowest selling offer) price:
> s aapl 100 ask
bs
is "buy stop"
ss
is "sell stop"
ts
is "trailing stop"
TODO: Write more documentation on other commands and in-progress modules orders.py and transactions.py
[schwab_auth.py]
Re-usable module used by schwab_cli.py to provide -- and to re-generate as needed -- the Access token required to call the Schwab API.
The current token state is saved in auth.json.
[gen_refresh_token.py]
Standalone CLI utility that generates a Refresh token, which is then used to create Access Tokens.
The current token state is saved in auth.json.
Your Schwab account must be made available for API access to these scripts (and any other software you develop). See https://developer.schwab.com/user-guides/
Specifically, these scripts require the following data specific to your Schwab account.
[.env.example]
- SCHWAB_APP_KEY=lL5apjgztC82RsFDaoJLeH7FqnHz5rnL
- SCHWAB_APP_SECRET=3gWeqCR7qDPeG1FD
- SCHWAB_CALLBACK_URL=https://dcsoft.com/dev/schwab
Create a file named ".env" like the above example, but change the values to the ones specific to your Schwab account.