This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners and alerts system.

Overview

Python Trading Bot w/ Thinkorswim

Description

  • This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners and alerts system.

Table Of Contents

How it works (in a nutshell)

Thinkorswim:

1. USER CREATES STRATEGIES IN THINKORSWIM.
2. USER THEN CREATES SCANNERS FOR THOSE STRATEGIES. (SCANNER NAME HAS SPECIFIC FORMAT)
3. USER THEN SETS EMAIL ALERTS TO USER SPECIFIC GMAIL ADDRESS THAT IS SETUP THROUGH THE THINKORSWIM PROGRAM.
4. WHEN NEW SYMBOL IS POPULATED INTO THE SCANNER, AN ALERT IS TRIGGERED, AND AN EMAIL IS SENT.

Trading Bot:

1. BOT CONTINUOUSLY SCANS GMAIL ACCOUNT, LOOKING FOR ALERTS.
2. ONCE ALERTS ARE FOUND, BOT PICKS APART EMAIL INFO TO DETERMINE WHICH STOCKS NEED TO BUY/SELL FOR WHICH STRATEGY.
  • You can only buy a stock once per strategy, but you can buy the same stock on multiple strategies. Unlimited shares, obviously. It's very diversified.

  • MongoDB database stores and keeps track of all of your open and closed positions, along with other data. Completely seperated from TDAmeritrade.

  • This is setup for both EQUITY and OPTIONS trading, but I have not traded OPTIONS on this as of yet.

  • Flow

    1. Alert from Gmail is received.
    2. Data from alert is stripped of needed info.
    3. If buy order, then open positions in Mongo is checked for any open positions with the same symbol and strategy.
    4. If nothing found, a buy order is placed.
    5. Same goes for sell order.
    6. If sell order, then open positions in Mongo is checked for open position with same symbol and strategy.
    7. If found, then sell order is placed.

Dependencies

[dev-packages]

  • pylint
  • bandit
  • pandas
  • tabulate

[packages]

  • google-api-python-client
  • google-auth-httplib2
  • google-auth-oauthlib
  • python-dotenv
  • pymongo
  • dnspython
  • termcolor
  • colorama
  • requests
  • pytz
  • psutil

[venv]

  • pipenv

[requires]

  • python_version = "3.8"

Setup

  • Assuming that you already have a TDAmeritrade account and the Thinkorswim desktop application already downloaded, we will move on to the next step.

MONGODB

  • Create a MongoDB account, create a cluster, and create two databases with the following names:

    1. Live_Trader
    2. Sim_Trader
  • The Live_Trader database will contain all the important data used for actual live trading.

  • The Sim_Trader database will be used for simulated trading, basically buying and selling everything, regardless of buying power. Pretty much paper trading without going through the TDA api.

  • You will need the mongo uri to be able to connect pymongo in the program. Store this uri in a .env file within your mongo package in your code.

  • The images below shows the structure of how the databases and users collection is setup:

Live Trader Database

  • Most of the Live_Trader collections are used to collect long term data for use on my front end web app I have developed, which is not public at this time.

  • The most crucial collections are:

    1. users
    2. queue
    3. open_positions
    4. closed_positions
    5. other
  • The users collection store all users and their individial data, such as name and accounts.

  • The queue stores non-filled orders that are working or queued, until either cancelled or filled.

  • The open_positions stores all open positions and is used to help determine if an order is warranted.

  • The closed_positions stores all closed positions after a trade has completed.

  • The other stores all rejected and cancelled orders. Rejected typically happens if not enough buying power, and I have it set to cancel buy orders that have been sitting in queue for 2 hours or more.

Sim Trader Database

Users Collection

  • The image above shows the structure of how a user is setup. In the Accounts object, the key is the account number, and the value is another object with all of that account info and the tokens. All of this will auto populate into the users collection once you create your API tokens for TDAmeritrade using this repo here.

Gmail

  • First off, it is best to create an additional and seperate Gmail account and not your personal account.

  • Make sure that you are in the account that will be used to receive alerts from Thinkorswim.

  • You will need to create and turn on Google Docs API. https://developers.google.com/docs/api/quickstart/python

  • Once created, save the credentials.json file to the creds directory within your gmail package in the program. This will be converted to token.json. After that, you can delete the credentials.json file.

  • Run the program to see if you connect to Gmail. You will be prompted to sign in to your account. Make sure you sign in with the account you will be using with Thinkorswim for the program. You may be given an Unverified Apps screen. If so, follow this:

    1. Click the advanced button bottom left.
    2. Click the Go to Quickstart (unsafe) button.
    3. Click Allow.
    4. Click Allow again.
    5. You then will be redirected to a callback of localhost with the message "The authentication flow has completed. You may close this window."
    6. Exit out, and you should be connected.
  • Once verified, you may have to go to your Google Developers Portal to enable your app.

  • Now you should be able to fully connect. If the token.json gets removed, you will not be able to connect.

  • Let me know via email if you have issues, and I can help guide you through the process.

Pushsafer

  • Pushsafer allows you to send and receive push notifications to your phone from the program.

  • This is handy for knowing in real time when trades are placed.

  • You can also receive error notifications, but I stopped that for now.

  • The first thing you will need to do is register: https://www.pushsafer.com/

  • Once registered, read the docs on how to register and connect to devices. There is an Android and IOS app for this.

  • You will also need to pay for API calls, which is about $1 for 1,000 calls.

  • You will also need to store your api key in your code in a .env file that is stored in your push_notification package.

TDAmeritrade API Tokens

  • You will need an access token and refresh token for each account you wish to use.
  • Here is my repo to help you to get these tokens and save them to your mongo database, in your users collection.

Thinkorswim

  • If you are familiar with creating strategies and setting up scanners, then this part should be easy.
  • There are some things that we need to make sure are done correctly, such as the following:
    1. Make sure the scanner names are formatted correctly so the program can use them.
    2. Make sure the scanner logic is setup correctly so the alerts trigger at the correct time.
    3. Make sure your alerts are set up correctly.

Scanner Names

  • The format for the scanner name should look like this: STRATEGY, SIDE, AGGREGATION, ASSET TYPE, ACCOUNT TYPE

  • Example: Scanner Name Format

    1. REVA is the strategy name.
    2. SELL is the side. Can be BUY, SELL, BUY_TO_OPEN, SELL_TO_CLOSE
    3. 4h is the aggregation. ex. 30m, 1h, 4h, D
    4. EQUITY is the asset type. Can be EQUITY OR OPTION
    5. PRIMARY is the account type. Can be PRIMARY, SECONDARY, ect.... (Subject to change to Day, Swing)
  • Must be in this exact order and spelled correctly for this to work properly.

Scanner logic offset

  • The scanners need to be offset by one in order to send a non-premature alert. It needs to look at the previous bar for whatever aggregation you have set for it. This will look at the last bar to see if it met criteria, and if so, triggers an alert. The reason for this is that if we used the current candle, and this is based on experience, the symbols will populate and then be removed constantly throughout that aggregation, and may not actually meet criteria by the end.

  • This is how an entry strategy in the charts may look.

Chart Strategy Example

  • This is how the scanner should look for the exact same entry strategy.

Scanner Strategy Example

  • The only thing that changed was that [1] was added to offset the scanner by one and to look at the previous candle.

Setting up Alerts

  • When setting up alerts, make sure you select to send an alert everytime a symbol is added, or this will not work.
  • Also, make sure that the email box is checked to allow the alerts to be sent to your gmail.

Results

  • I have been using this since October 2020, and without giving to much detail, I can vouch that it is profitable. That being said, everyone's experience will be different, and not everyone will share the same results.

  • Obviously, results are based off of how good your strategies that are developed in Thinkorswim are.

Simulated Results

  • These results are simulated, which means they bought and sold everytime an alert came through from the emails. This is basically paper trading, but through the program. It would represent what it would be like with no buying power limit. This is based off of 1 share trades. Most of these strategies have been running since October 2020. As you can see, the program is affective, but obviously results may vary depending on how good your strategies are and also how much money you have to trade with.

Simulated Results

DISCREPENCIES

  • This program is not perfect. I am not liable for any profits or losses.

  • There are several factors that could play into the program not working correctly. Some examples below:

    1. TDAmeritrades API is buggy at times, and you may lose connection, or not get correct responses after making requests.
    2. Thinkorswim scanners update every 3-5 minutes, and sometimes symbols wont populate at a timely rate. I've seen some to where it took 20-30 minutes to finally send an alert.
    3. Gmail servers could go down aswell. That has happened in the past, but not very common.
    4. And depending on who you have hosting your server for the program, that is also subject to go down sometimes, either for maintenance or for other reasons.
    5. As for refreshing the refresh token, I have been running into issues when renewing it. The TDA API site says the refresh token will expire after 90 days, but for some reason It won't allow you to always renew it and may give you an "invalid grant" error, so you may have to play around with it or even recreate everything using this repo. Just make sure you set it to existing user in the script so it can update your account.
  • The program is very indirect, and lots of factors play into how well it performs. For the most part, it does a great job.

What I use and costs

SERVER FOR HOSTING PROGRAM

  • PythonAnywhere -- $7 / month

DATABASE

  • MongoDB Atlas -- Approx. $25 / month
  • I currently use the M5 tier.

Mongo Tiers

NOTIFICATION SYSTEM

  • PushSafer -- Less than $5 / month

FINAL THOUGHTS

  • This is in continous development, with hopes to make this program as good as it can possibly get. I know this README might not do it justice with giving you all the information you may need, and you most likely will have questions. Therefore, don't hesitate to contact me either via Github or email. As for you all, I would like your input on how to improve this, and I also heavily encourage you to fork the code and send me your improvements. I appreciate all the support! Thanks, Trey.

  • If you like backtesting with Thinkorswim, here's a repo of mine that may help you export strategy reports alot faster.

  • Also, If you like what I have to offer, please support me here!

You might also like...
Download videos from Youtube and other platforms through a Telegram Bot
Download videos from Youtube and other platforms through a Telegram Bot

ytdl-bot Download videos from YouTube and other platforms through a Telegram Bot Usage: https://t.me/benny_ytdlbot Send link from YouTube directly to

Automated crypto trading bot as adapted from Algovibes.

crypto-trading-bot Automated crypto trading bot as adapted from Algovibes. Pre-requisites Ensure that you have created a Binance API key before procee

IDCARD-VERIFYING-SYSTEM - The Utilizing the freqtrade high-frequency cryptocurrency trading framework to build and optimize trading strategies. The bot runs nonstop on a Rasberry Pi.
Utilizing the freqtrade high-frequency cryptocurrency trading framework to build and optimize trading strategies. The bot runs nonstop on a Rasberry Pi.

Freqtrade Strategy Repository Please test all scripts and dry run them before using them in live mode Contact me on discord if you have any questions!

Tracker to check the covid shot slot availability in India and send mobile alerts via Twilio Messaging Service.

Cowin-Slot-Tracker Tracker to check the covid vaccine slot availability in India and send mobile notifications through Twilio Messaging Service. Requi

And now, for the first time, you can send alerts via action from ArcSight ESM Console to the TheHive when Correlation Rules are triggered.

ArcSight Integration with TheHive And now, for the first time, you can send alerts via action from ArcSight ESM Console to the TheHive when Correlatio

A project that alerts me when there's a dog outside so I can go look at it.

Dog Detector A project that alerts me when there's a dog outside so I can go look at it. Tech Specs This script uses the YOLOv3 object detection model

This automation protect against subdomain takeover on AWS env which also send alerts on slack.

AWS_Subdomain_Takeover_Detector Purpose The purpose of this automation is to detect misconfigured Route53 entries which are vulnerable to subdomain ta

A chatbot that helps you set price alerts for your amazon products.
A chatbot that helps you set price alerts for your amazon products.

Amazon Price Alert Bot Description A Telegram chatbot that helps you set price alerts for amazon products. The bot checks the price of your watchliste

Comments
  • Different

    Different "Order =" Entries

    I've hard coded 3 separate possible orders into this code (Standard, Trailing_Stop, and OCO). Line 74 has to be hard coded to what type of order you want to work with when the bot is running. Depending on order is selected, different childOrders get completed.

    OCO orders are defaulted for 11% stop loss and a 25% take profit. If it's OCO and multiple shares have been purchased, line 285 leaves 1 runner after the target profit has been hit. All shares are sold if it hits the stop loss.

    Trailing_Stop orders are defaulted for a 7% trailing stop based on the AskPrice. Since this order is entered as a Trailing_Stop when the initial order goes through, streaming is not required.

    Also changed is line 270... if asset_type == "Equity", shares will equal the position_size/price. If it's an "option", then shares equal the ((position_size)/100)/price. This avoids buying $20,000 of a position size on new studies.

    opened by mogden16 1
  • Patch Versions for Vulnerabilities

    Patch Versions for Vulnerabilities

    Potential DoS (Denial of Service) Package Affected versions Patched version protobuf (pip)

    = 3.19.0, < 3.19.5 3.19.5 Summary

    A message parsing and memory management vulnerability in ProtocolBuffer’s C++ and Python implementations can trigger an out of memory (OOM) failure when processing a specially crafted message, which could lead to a denial of service (DoS) on services using the libraries.

    Reporter: ClusterFuzz

    Affected versions: All versions of C++ Protobufs (including Python) prior to the versions listed below. Severity & Impact

    Medium 5.7 - CVSS:3.1/AV:A/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H

    A small (~500 KB) malicious payload can be constructed which causes the running service to allocate more than 3GB of RAM. Proof of Concept

    For reproduction details, please refer to the unit test that identifies the specific inputs that exercise this parsing weakness. Mitigation / Patching

    Please update to the latest available versions of the following packages:

    protobuf-cpp (3.18.3, 3.19.5, 3.20.2, 3.21.6)
    protobuf-python (3.18.3, 3.19.5, 3.20.2, 4.21.6)
    
    opened by diveyez 0
Owner
Trey Thomas
Full stack web developer with skills in HTML5, CSS3, JQuery, Vanilla JS, Flask, Python, MySQL,NodeJS/Express, MongoDB, VueJS
Trey Thomas
Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI

Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI. Used REST and WebSocket API to connect to two of the most popular crypto exchanges in the world.

Francis 8 Sep 15, 2022
Sunflower-farmers-automated-bot - Sunflower Farmers NFT Game automated bot.IT IS NOT a cheat or hack bot

Sunflower-farmers-auto-bot Sunflower Farmers NFT Game automated bot.IT IS NOT a

Arthur Alves 17 Nov 9, 2022
Faster Twitch Alerts is a highly customizable, lightning-fast alternative to Twitch's slow mobile notification system

Faster Twitch Alerts What is "Faster Twitch Alerts"? Faster Twitch Alerts is a highly customizable, lightning-fast alternative to Twitch's slow mobile

null 6 Dec 22, 2022
Trading bot - A Trading bot With Python

Trading_bot Trading bot intended for 1) Tracking current prices of tokens 2) Set

Tymur Kotkov 29 Dec 1, 2022
Acid's Utilities is a bot for my Discord server that alerts when I go live, welcomes new users, has some awesome games and so much more!

Acid's Utilities Acid's Utilities is a bot for my Discord server that alerts when I go live, welcomes new users, has some awesome games and so much mo

AcidFilms (Fin Stuart) 3 Nov 19, 2021
An open-source Discord bot that alerts your server when it's Funky Monkey Friday!

Funky-Monkey-Friday-Bot An open-source Discord bot that alerts your server when it's Funky Monkey Friday! Add it to your server here! https://discord.

Cole Swinford 0 Nov 10, 2022
🤖 Automated follow/unfollow bot for GitHub. Uses GitHub API. Written in python.

GitHub Follow Bot Table of Contents Disclaimer How to Use Install requirements Authenticate Get a GitHub Personal Access Token Add your GitHub usernam

João Correia 37 Dec 27, 2022
Telegram Group Calls Streaming bot with some useful features, written in Python with Pyrogram and Py-Tgcalls. Supporting platforms like Youtube, Spotify, Resso, AppleMusic, Soundcloud and M3u8 Links.

Yukki Music Bot Yukki Music Bot is a Powerful Telegram Music+Video Bot written in Python using Pyrogram and Py-Tgcalls by which you can stream songs,

Team Yukki 996 Dec 28, 2022
Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Alexandr Savinov 326 Jan 3, 2023
Trading bot that uses Elon Musk`s tweets to know when to buy cryptocurrency.

Elonbot Trading bot that uses Elon Musk`s tweets to know when to buy cryptocurrency. Here is how it works: Subscribes to someone's (elonmusk?) tweets

null 153 Dec 23, 2022