mogden16 / TradierTDA_Trader

Options Trading Program that integrates TDA & Tradier. It gets it's alerts from Gmail & Discord
17 stars 6 forks source link

Python Trading Bot w/ Thinkorswim

Description

How it works (in its simplest terms)

Thinkorswim can be used as a broker for LiveTrading or Papertrading OR it can just be used to send your bot buy signals. The Papertrading feature of this bot WILL NOT show up in your papertrading account in ToS, but MongoDB can be set up to visually show your paper trading. ToS is better than Traider with papertrading because Tradier data is DELAYED for 15m when not live trading.

  1. IN ORDER TO TRADE THINKORSWIM, IN CONFIG.PY --> RUN_TRADIER = False
  2. IN ORDER TO TRADE PAPERTRADER, IN CONFIG.PY --> RUN_LIVE_TRADER = FALSE
  3. If you want alerts coming from ThinkorSwim, you can set up an OptionHacker alert to send emails to an email you created.
  4. Create a scanner for your strategy. (Scanner name will have specific format needed)
  5. Set your scanner to send alerts to your non-personal gmail.
  6. When a symbol is populated into the scanner with "buy" or "buy_to_open", an alert is triggered and sent to gmail.
  7. If you're unfamilar with Trey's repo, please check this out. This is what the repo this code has been modeled after: https://github.com/TreyThomas93/python-trading-bot-with-thinkorswim

Discord

  1. I personally use https://www.teklutrades.com/FlowAnalysis, I couldn't recommend his work enough.
  2. It's $40/month but the alerts are formatted well.
  3. If you have your own discord that you'd like to track alerts with, you'll have to format your own discord scanner and throw it in the discord folder. You can replace discord_scanner.py with your own. If you don't have a discord_scanner, you can set RUN_DISCORD = False

Trading Bot (Python)

  1. Continuously scrapes email inbox/discord looking for alerts.
  2. Once found, bot will extract needed information and will run TA (if you have RUN_TA set to True in your config.py).

HOW TO SET UP config.py

  1. Create a copy of config.py.example and save it as config.py. Place it in the root of this folder (next to config.py.example)
  2. RUN_LIVE_TRADER: change to True if you want to trade using real money (True, False)
  3. RUN_TRADIER: change to True if you want to trade using Tradier as your broker (True, False) - the websocket is still ToS based, so you will still need to have ToS set up if you'd like to runWebsocket with Tradier
  4. IS_TESTING: this might not work... it's intended to provide prices when the market is closed to make sure everything is still working in Mongo (True, False)
  5. TRADE_HEDGES: only changes the alerts from my discord_scanner (True, False). TekluTrades indicates when it thinks a flow might be a hedge. If you aren't using this flow, it won't affect your trading. If you are using this flow and would like to trade when there's a Hedge Alert flow, set to True
  6. MONGO_URI: your Mongo_URI (string) - (see Trey's repo if necessary)
  7. RUN_GMAIL & RUN_DISCORD: how do you want to get your alerts? Set to True for the alerts you'd like (True, False)
  8. PUSH_API_KEY: I use a free discord webhook to a personal discord channel, but this is possible too (string) [commented out]
  9. TIMEZONE: use a pytz timezone (string) https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568
  10. RUN_TASKS: this runs on a totally separate python thread. I suggest having it set to True (True, False). Functions can be found in assets -> tasks.py
  11. RUN_WEBSOCKET: this will actively stream all open_posiitons in mongo with pricing and update it to mongo (True, False) - personal preference, I have it on
  12. TURN_ON_TIME, TURN_OFF_TRADES, SELL_ALL_POSITIONS, SHUTDOWN_TIME: ('HH:MM:SS')
    • TURN_ON_TIME - not set up currently, when you'd like to start the mongo connection and boot up the bot
    • TURN_OFF_TRADES - at what time would you like to stop accepting trades ('15:50:00') (ie. 10mins before close)
    • SELL_ALL_POSITIONS - at what time would you like to start selling all positions?
    • SHUTDOWN_TIME - at what time would you like to disconnect from Mongo? *MONGO CHARGES BASED OFF THE HOUR, NOT NUMBER OF CONNECTIONS, SO IT'S BEST TO SHUT THE CONNECTION ONCE MARKET IS CLOSED

TRADING CRITERIA

  1. MIN_OPTIONPRICE: (Float) as you're scanning discord alerts, what's the minimum option price you'd like to potentially trade?
  2. MAX_OPTIONPRICE: (Float) what's the maximum price you'd like to trade? NOTE: THE POSITION SIZE MUST BE SET IN MONGO IN STRATEGIES
  3. MIN_VOLUME: (Float) as you get alerts, python will send a request to TD API to get the price & volume of the option. What's the minimum volume you want to trade? You want to ensure that the contract is liquid
  4. MIN_DELTA: (Float) what's the minimum delta you'd like to trade? It takes absolute value
  5. GET_PRICE_FROM_TD: personal preference. Do you want to get your price quotes from TD or Tradier? Tradier is delayed for papertrading, so I always get price data from TD (True, False)
  6. BUY_PRICE: do you want to buy on the bidPrice, askPrice, lastPrice, mark? (string) I prefer to buy on bid, sell on ask
  7. SELL_PRICE: do you want to sell on the bidPrice, askPrice, lastPrice, mark? (string)
  8. MAX_QUEUE_LENGTH: (Float) a tasks has a KillQueueOrder function. If an order is queued for longer than MAX_QUEUE_LENGTH, then it's cancelled
  9. TAKE_PROFIT_PERCENTAGE: (Float) If trading OCO or Custom, what would you like your Take_Profit set as?
    • Entry_Price * (1+Take_Profit_Percentage) = Take_Profit_Price
  10. STOP_LOSS_PERCENTAGE: (Float) If trading OCO or Custom, what would you like your Stop_Loss set as?
    • Entry_Price * (1-Stop_Loss_Percentage) = Stop_Loss_Price
  11. TRAIL_STOP_PERCENTAGE: (Float) If trading Trail, it will set your trailing stop.
    • Entry_Price * TRAIL_STOP_PERCENTAGE = Trail_Stop_Value
    • Entry_Price - Trail_Stop_Value = Trail_Stop_Price
    • Please note that this trail stop is not 100% developed yet (Traider does NOT have a trailing stop order, so the websocket will constantly update a closing order)
  12. RUNNER_FACTOR: (Float) this is currently not being used. It used to enter a new order of RUNNER_FACTOR * position_size after an order hits take_profit_price
  13. TRADE_MULTI_STRIKES: do you want to trade multiple strikes of the same options? TD sometimes sends gmails of 3 separate strikes in one email. If you don't want to trade these, it should be False (True, False)

TECHNICAL ANALYSIS

  1. RUN_TA: runs QQE & HULL_MOVING_AVG for alerts in the 10m timeframe (True, False)
  2. RUN_30M_TA: Runs QQE & HULL_MOVING_AVG for alerts in the 30m timeframe (True, False)
    • If both are true, then the 10m and 30m timeframes are in agreement with your indicators (puts & calls have separate criteria)

TD STREAMING

  1. API_KEY, REDIRECT_URI, TOKEN_PATH: (string) please watch Part Time Larry's video to get a separate API_KEY for your account. You will need to create a new TD Developer account for this
  2. ACCOUNT_ID: (float) This is the TD account you'd like to trade with
  3. HEARTBEAT_SETTING: (float) in seconds, how often would you like a "heartbeat signal" from the websocket task incase you don't have any open positions, it will show that your streamer is still working
  4. STREAMPRICE_LINK: (string) in streamprice.py, would you like to trade out of a signal based on 'bid', 'ask', 'last'? I prefer ask price

DISCORD

  1. CHANNELID: (string) channel ID for discord alert channel
  2. DISCORD_AUTH: (string) authorization for discord alert channel
  3. DISCORD_USER: (string) username of discord alert bot
  4. STRATEGY: (string) what do you want to name your strategy coming from discord alerts
  5. DISCORD_WEBHOOK: (string) personal discord webhook (this is how I get alerts instead of Pushsafer)

    TRADIER


Getting Started

DEPENDENCIES


[dev-packages]

[packages]

[venv]

[requires]

THINKORSWIM


  1. Create a strategy that you want to use in the bot.
  2. Create a scanner and name it using the format below:

    • STRATEGY, SIDE
    1. REVA is the strategy name example.
    2. BUY is the side. Can be BUY, BUY_TO_OPEN, BUY_TO_CLOSE, SELL, SELL_TO_CLOSE, SELL_TO_OPEN

    • ATTENTION - Your scanner names must have the same strategy names for the buy and sell scanners, or the bot will not be able to trade correctly.
    • Example:

      • MyRSIStrategy, BUY
      • MyRSIStrategy, SELL

  1. You will need to offset the scanner logic to prevent premature alerts from firing. This is due to the fact of the current candle constantly repainting and meeting/not meeting criteria.

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

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

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


  1. Set up the alert for the scanner. View images below:

    • Set Event dropdown to "A symbol is added"

    • Check the box that says "Send an e-mail to all specified e-mail addresses"

    • Check the radio button thats says "A message for every change"


  1. You should now start to receive alerts to your specified gmail account.

TDAMERITRADE API TOKENS

GMAIL

  1. https://developers.google.com/gmail/api/quickstart/python
  2. https://developers.google.com/workspace/guides/create-project
  3. https://developers.google.com/workspace/guides/create-credentials
  4. After you obtain your credentials file, make sure you rename it to credentials.json and store it in the creds folding within the gmail package in the program.
  5. Run the program and you will go through the OAuth process. Once complete, a token.json file will be stored in your creds folder.
  6. If you get an access_denied during the OAuth process, try this: https://stackoverflow.com/questions/65184355/error-403-access-denied-from-google-authentication-web-api-despite-google-acc

MONGODB


ApiTrader

  1. analysis (THIS IS WHERE THE DISCORD ALERTS GO AFTER THEY'RE SCANNED TO AVOID RE-TRADING)
  2. users
  3. queue
  4. open_positions
  5. closed_positions
  6. rejected
  7. canceled
  8. strategies

PUSHSAFER


DISCREPENCIES


WHAT I USED AND COSTS

SERVER FOR HOSTING PROGRAM

DATABASE

NOTIFICATION SYSTEM

DISCORD NOTIFICATIONS

FINAL THOUGHTS


Venmo - @Matt-Ogden