示例#1
0
def incoming_sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    print(2)
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    # Determine the right reply for this message
    # if body == 'hello':
    #     resp.message("Hi!")
    # elif body == 'bye':
    #     resp.message("Goodbye")

    args = body.split(',')
    ticker = str(args[0])
    num_shares = args[1]

    print(3)

    order = equity_buy_market(ticker, int(num_shares))
    c.place_order(config.tda_acct_num, order)
    resp.message("Bought " + num_shares + " shares of " + body)
    print("Bought " + num_shares + " shares of " + body)
    return str(resp)
示例#2
0
 def purchaseStockMarket(self, ticker, shares=1, price=0):
     result = Order()
     if (ticker != "" and shares > 0):
         order = equity_buy_market(ticker, shares).build()
         result = self._placeOrder(order)
         print("Purchase Real: " + ticker)
     return result
示例#3
0
    def place_buy_market(self, symbol: str, quantity: int) -> str:
        order = (
            # market order can only be a day order
            equity_buy_market(symbol, quantity)).build()

        r = self.c.place_order(self.account_id, order)
        if not r.ok:
            raise BrokerException(r)

        order_id = Utils(self.c, self.account_id).extract_order_id(r)
        return order_id
示例#4
0
def kill_trade(symbol, qty, price, order_type):
    client = build_client()
    try:
        if order_type == "long":
            client.place_order(account_id=ACCOUNT_ID,
                               order_spec=equity_sell_market(symbol, qty))
            logging.info("Killed trade")
            record_trade(symbol, price)
        else:
            client.place_order(account_id=ACCOUNT_ID,
                               order_spec=equity_buy_market(symbol, qty))
            logging.info("Killed trade")
            record_trade(symbol, price)
    except:
        logging.info(f"Unexpected error killing trade: {sys.exc_info()}")
        pass
示例#5
0
 def _submitBuy(self, event):
     '''
     Takes OrderEvent and submits a BUY order to the TDA account
     '''
     if event.trade_type == 'MARKET':
         self.client.place_order(
             self.ACC_ID,
             equities.equity_buy_market(
                 event.ticker,
                 event.quantity,
             ),
         )
     elif event.trade_type == 'LIMIT' and event.limit:
         self.client.place_order(
             self.ACC_ID,
             equities.equity_buy_limit(event.ticker, event.quantity,
                                       event.limit),
         )
     else:
         raise Exception('Invalid BUY order.')
示例#6
0
tickers = driver.find_elements_by_tag_name("td")

# positions = c.get_account(config.tda_acct_num, c.Account.Fields.POSITIONS)
# print(positions)

# i = 0
# # [0]:Ticker, [1]:Share Price, [2]:Rating, [3]:Score, [4]:Rating Change Date, [5]:Price Change %
# while i < 40:
#     ticker = str(tickers[i].text)
#     print(ticker)

#     share_price = float(tickers[i + 1].text)
#     # How many dollars of each stock to buy:
#     desired_dollar_amount = 1000
#     num_shares = round(desired_dollar_amount / share_price)
#     print(num_shares)

#     order = equity_buy_market(ticker, num_shares)
#     r = c.place_order(config.tda_acct_num, order)
#     time.sleep(2)
#     print(r.status_code)
#     print(r)
#     i += 10

driver.quit()

order = equity_buy_market('SNDL', num_shares)
r = c.place_order(config.tda_acct_num, order)
time.sleep(2)
print(r.status_code)
print(r)
# All this scraping code works
driver.get("https://financhill.com/screen/stock-score")
time.sleep(2)
driver.find_element_by_css_selector(
    'span[data-sort-name="stock_score_normalized"]').click()
time.sleep(2)
tickers = driver.find_elements_by_tag_name("td")

# positions = c.get_account(config.tda_acct_num, c.Account.Fields.POSITIONS)
# print(positions)

i = 0
# [0]:Ticker, [1]:Share Price, [2]:Rating, [3]:Score, [4]:Rating Change Date, [5]:Price Change %
while i < 40:
    ticker = str(tickers[i].text)
    print(ticker)

    share_price = float(tickers[i + 1].text)
    # How many dollars of each stock to buy:
    desired_dollar_amount = 1000
    num_shares = round(desired_dollar_amount / share_price)
    print(num_shares)

    order = equity_buy_market(ticker, numsha)
    r = c.place_order(config.tda_acct_num, order)
    time.sleep(2)
    print(r.status_code)
    print(r)
    i += 10

driver.quit()
# positions = c.get_account(config.tda_acct_num, c.Account.Fields.POSITIONS)
# print(positions)

i = 0
# [0]:Ticker, [1]:Share Price, [2]:Rating, [3]:Score, [4]:Rating Change Date, [5]:Price Change %
while i < 0:
    ticker = str(tickers[i].text)
    print(ticker)

    share_price = float(tickers[i + 1].text)

    desired_dollar_amount = 1000 # How many dollars of each stock to buy
    num_shares = round(desired_dollar_amount / share_price)
    print(num_shares)

    order = equity_buy_market(ticker, num_shares)
    r = c.place_order(config.tda_acct_num, order)
    print(r.status_code)
    print("Bought " + str(num_shares) + " of " + ticker)
    i += 10

order2 = equity_buy_market('ECNS', 150)
r = c.place_order(config.tda_acct_num, order2)
print(r.status_code)
print("Bought 150 shares of ECNS")

driver.quit()


# Better way to write?:
# i = 0
示例#9
0
from tda import auth, client
from tda.orders.equities import equity_buy_market
from tda.orders.common import Duration, Session
import os, sys
import time
from selenium import webdriver
import json

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
import config  # stored in parent directory for security

token_path = 'token'
redirect_uri = "https://localhost"

DRIVER_PATH = "/home/hopper/chromedriver"
driver = webdriver.Chrome(DRIVER_PATH)


try:
    c = auth.client_from_token_file(token_path, config.api_key)
except FileNotFoundError:
    c = auth.client_from_login_flow(
        driver, config.api_key, redirect_uri, token_path
    )


print(c.place_order(config.tda_acct_num, equity_buy_market('SNDL', 1).set_duration(Duration.GOOD_TILL_CANCEL).set_session(Session.SEAMLESS).build()))
time.sleep(2)
driver.quit()
button = driver.find_element_by_css_selector(
    'span[data-sort-name="stock_score_normalized"]')
time.sleep(2)

button.click()

time.sleep(2)

tickers = driver.find_elements_by_tag_name("td")
i = 0
while i < 20:
    print(tickers[i].text)

    c.place_order(
        config.tda_acct_id,  # account_id
        equity_buy_market(ticker, 1, 1250.0).set_duration(
            Duration.GOOD_TILL_CANCEL).set_session(Session.SEAMLESS).build())
    i += 10
# for ticker in tickers:
#     print(ticker.text)
# print(ticker.tag_name)
# print(ticker.parent)
# print(ticker.location)
# print(ticker.size)
# time.sleep(2)

driver.quit()

# [0]: Ticker, [1]: Price, [2]: Rating, [3]: Score, [4]:Rating Change Date, [5]:Price Change %
# SVM
# 6.70
# Buy
示例#11
0
from tda.orders.equities import equity_buy_market
from tda.orders.common import Duration, Session
import os, sys
import time
from selenium import webdriver
import json

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
import config  # stored in parent directory for security

token_path = 'token'
redirect_uri = "https://localhost"

DRIVER_PATH = "/home/hopper/chromedriver"
driver = webdriver.Chrome(DRIVER_PATH)

try:
    c = auth.client_from_token_file(token_path, config.api_key)
except FileNotFoundError:
    c = auth.client_from_login_flow(driver, config.api_key, redirect_uri,
                                    token_path)

print(
    c.place_order(
        config.tda_acct_num,
        equity_buy_market('SNDL', 1).set_duration(
            Duration.GOOD_TILL_CANCEL).set_session(Session.SEAMLESS).build()))

driver.quit()
示例#12
0
 def place_orders(symbol):
     # Gets current date and time
     now = datetime.now().strftime('%d-%m-%y %I:%M:%S %p')
     # Finds the total deltas for options to be hedged on a particular underlying
     total_deltas_for_options_on_underlying = option_positions_to_hedge.loc[
         option_positions_to_hedge['underlyingSymbol'] ==
         symbol]['totalDelta'].sum()
     # Finds the total quantity for a particular underlying
     underlying_quantity = option_positions_to_hedge.loc[
         option_positions_to_hedge['underlyingSymbol'] ==
         symbol]['underlyingQuantity']
     # If the stock underlying an option to be hedged
     # is not owned, then the underlying quantity is set to 0.
     # If it is owned, then the quantity is set from the series as an integer
     if underlying_quantity.empty:
         underlying_quantity = 0
     else:
         underlying_quantity = int(underlying_quantity.iloc[0])
     # Determines the number of shares needed to be bought/sold to be delta neutral.
     # This is done by multiplying the total number of deltas for an option by -1,
     # then subtracting the quantity of the underlying for the options.
     shares_needed_to_hedge = int(total_deltas_for_options_on_underlying *
                                  -1 - underlying_quantity)
     # Place Orders, due to shorts and longs having seperate functions, it
     # complicates the order process, and it can be hard to follow.
     # The process itself is fairly straightforward, the number of shares
     # owned should be equal to the inverse of the total deltas on a particular
     # underlying.  So shares will either be purchased or sold to reach
     # this condition.  Adjustment is made when the total deltas
     # for the options on an underlying move past the previously set threshold,
     # either above or below.
     if shares_needed_to_hedge > threshold:
         if underlying_quantity < 0 and underlying_quantity + shares_needed_to_hedge < 0:
             #Buy to cover shares_needed_to_hedge
             order_specs = equities.equity_buy_to_cover_market(
                 symbol=symbol,
                 quantity=shares_needed_to_hedge).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order = c.place_order(account_id, order_specs)
             pprint(
                 pd.DataFrame(order_specs['orderLegCollection'],
                              index=[now]))
         elif underlying_quantity < 0 and underlying_quantity + shares_needed_to_hedge > 0:
             #Buy to cover abs(underlying_quantity)
             order1_specs = equities.equity_buy_to_cover_market(
                 symbol=symbol,
                 quantity=abs(underlying_quantity)).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order1 = c.place_order(account_id, order1_specs)
             pprint(
                 pd.DataFrame(order1_specs['orderLegCollection'],
                              index=[now]))
             #Buy shares_needed_to_hedge - abs(underlying_quantity)
             order2_specs = equities.equity_buy_market(
                 symbol=symbol,
                 quantity=shares_needed_to_hedge -
                 abs(underlying_quantity)).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order2 = c.place_order(account_id, order2_specs)
             pprint(
                 pd.DataFrame(order2_specs['orderLegCollection'],
                              index=[now]))
         elif underlying_quantity > 0:
             #Buy shares_needed_to_hedge
             order_specs = equities.equity_buy_market(
                 symbol=symbol,
                 quantity=shares_needed_to_hedge).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order = c.place_order(account_id, order_specs)
             pprint(
                 pd.DataFrame(order_specs['orderLegCollection'],
                              index=[now]))
     elif shares_needed_to_hedge < -threshold:
         if underlying_quantity > 0 and underlying_quantity + shares_needed_to_hedge > 0:
             #Sell abs(shares_needed_to_hedge)
             order_specs = equities.equity_sell_market(
                 symbol=symbol,
                 quantity=abs(shares_needed_to_hedge)).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order = c.place_order(account_id, order_specs)
             pprint(
                 pd.DataFrame(order_specs['orderLegCollection'],
                              index=[now]))
         elif underlying_quantity > 0 and underlying_quantity + shares_needed_to_hedge < 0:
             #Sell underlying_quantity
             order1_specs = equities.equity_sell_market(
                 symbol=symbol, quantity=underlying_quantity).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order1 = c.place_order(account_id, order1_specs)
             pprint(
                 pd.DataFrame(order1_specs['orderLegCollection'],
                              index=[now]))
             #Sell short abs(underlying_quantity + shares_needed_to_hedge)
             order2_specs = equities.equity_sell_short_market(
                 symbol=symbol,
                 quantity=abs(underlying_quantity +
                              shares_needed_to_hedge)).set_duration(
                                  Duration.DAY).set_session(
                                      Session.SEAMLESS).build()
             order2 = c.place_order(account_id, order2_specs)
             pprint(
                 pd.DataFrame(order2_specs['orderLegCollection'],
                              index=[now]))
         elif underlying_quantity < 0:
             #Sell to open abs(shares_needed_to_hedge)
             order_specs = equities.equity_sell_short_market(
                 symbol=symbol,
                 quantity=abs(shares_needed_to_hedge)).set_duration(
                     Duration.DAY).set_session(Session.SEAMLESS).build()
             order = c.place_order(account_id, order_specs)
             pprint(
                 pd.DataFrame(order_specs['orderLegCollection'],
                              index=[now]))
示例#13
0
def cancel_all(str_):
    """ Pass 'all', 'trades', or 'orders' depending on what needs to be canceled. """
    errors = []
    client = build_client()
    # cancel all open orders
    if str_ == "all" or str_ == "orders":
        try:
            orders = client.get_orders_by_path(account_id=ACCOUNT_ID, max_results=None, from_entered_datetime=None, to_entered_datetime=None, status=client.Order.Status.QUEUED, statuses=None).json()
            print("Canceling orders...")
            # orders = orders.json()
            for order in orders:
                order_id = order["orderId"]
                print(f"Order ID: {order_id}")
                client.cancel_order(order_id=order_id, account_id=ACCOUNT_ID)

            print("Orders canceled.")
        except:
            print("Unexpected error canceling orders:", sys.exc_info())
            errors.append(sys.exc_info())
            pass

    # close all trades   
    if str_ == "all" or str_ == "trades":
        try:
            account_with_positions = client.get_account(account_id=ACCOUNT_ID, fields=client.Account.Fields.POSITIONS).json()["securitiesAccount"]
            try:
                positions = account_with_positions["positions"]
            except:
                positions = {}
            print("Closing positions...")
            if positions == {}:
                print("No positions to close.")
            else:
                for trade in positions:
                    print(positions)
                    # submit sell order for the position
                    symbol = trade["instrument"]["symbol"]
                    short_quantity = trade["shortQuantity"]
                    long_quantity = trade["longQuantity"]
                    try:
                        if long_quantity > 0:
                            client.place_order(
                                account_id=ACCOUNT_ID,
                                order_spec=equities.equity_sell_market(symbol, long_quantity)
                            )
                    # it might be a short position, so try a buy order
                        elif short_quantity > 0:
                            client.place_order(
                                account_id=ACCOUNT_ID,
                                order_spec=equities.equity_buy_market(symbol, short_quantity)
                            )
                        else:
                            print("No trades to close.")
                            return
                    except:
                        print("Unexpected error closing trades:", sys.exc_info())
                        errors.append(sys.exc_info())
                        pass
        except:
            print("Unexpected error closing trades:", sys.exc_info())
            errors.append(sys.exc_info())
            pass

    if len(errors) > 0:
        print("errors with closing orders and positions:")
        print(errors)
    else:
        print("All orders canceled and positions closed.")
示例#14
0
tickers = driver.find_elements_by_tag_name("td")

# positions = c.get_account(config.tda_acct_num, c.Account.Fields.POSITIONS)
# print(positions)

# i = 0
# # [0]:Ticker, [1]:Share Price, [2]:Rating, [3]:Score, [4]:Rating Change Date, [5]:Price Change %
# while i < 40:
#     ticker = str(tickers[i].text)
#     print(ticker)

#     share_price = float(tickers[i + 1].text)
#     # How many dollars of each stock to buy:
#     desired_dollar_amount = 1000
#     num_shares = round(desired_dollar_amount / share_price)
#     print(num_shares)

#     order = equity_buy_market(ticker, num_shares)
#     r = c.place_order(config.tda_acct_num, order)
#     time.sleep(2)
#     print(r.status_code)
#     print(r)
#     i += 10

driver.quit()

order = equity_buy_market('SNDL', 1)
r = c.place_order(config.tda_acct_num, order)
time.sleep(2)
print(r.status_code)
print(r)
示例#15
0
i = 0
while i < 10:
    ticker = tickers[i].text
    print(ticker)
    # url = (
    #     "https://api.tdameritrade.com/v1/accounts/"
    #     + str(config.tda_acct_num)
    #     + "/orders"
    # )
    # headerArg = {"Authorization": "Bearer theEntireTokenHere"}

    c.place_order(
        config.tda_acct_num,  # account_id
        equity_buy_market(str(ticker), 1)
        .set_duration(Duration.GOOD_TILL_CANCEL)
        .set_session(Session.SEAMLESS)
        .build()
    )

    # requests.post(url, data, headers=headerArg)
    time.sleep(2)

    print(data)
    print(data.status_code)

    i += 10

    # order = {
    #     "orderType": "MARKET",
    #     "session": "NORMAL",
    #     "duration": "DAY",
tickers = driver.find_elements_by_tag_name("td")

# positions = c.get_account(config.tda_acct_num, c.Account.Fields.POSITIONS)
# print(positions)

i = 60
# [0]:Ticker, [1]:Share Price, [2]:Rating, [3]:Score, [4]:Rating Change Date, [5]:Price Change %
while i < 100:
    # Get ticker and price of stock
    ticker = str(tickers[i].text)
    share_price = float(tickers[i + 1].text)

    # Calculate how many shares to buy in order to equal about $1000
    desired_dollar_amount = 1000  # How many dollars of each stock to buy
    num_shares = round(desired_dollar_amount / share_price)

    #Build and place order
    order = equity_buy_market(ticker, num_shares)
    r = c.place_order(config.tda_acct_num, order)

    print("Bought " + str(num_shares) + " shares of " + ticker)
    i += 10

driver.quit()

# Better way to write?:
# i = 0
# while i < 6:
#     ticker = str(tickers[i*10].text)
#     share_price = float(tickers[i*10 + 1].text)
#     i+=1
示例#17
0
token_path = 'token'

DRIVER_PATH = "/home/hopper/chromedriver"
driver = webdriver.Chrome(DRIVER_PATH)

redirect_uri = "https://localhost"

try:
    c = auth.client_from_token_file(token_path, config.api_key)
except FileNotFoundError:
    c = auth.client_from_login_flow(driver, config.api_key, redirect_uri,
                                    token_path)
#All this scraping code works
driver.get("https://financhill.com/screen/stock-score")
time.sleep(2)
driver.find_element_by_css_selector(
    'span[data-sort-name="stock_score_normalized"]').click()
time.sleep(2)
tickers = driver.find_elements_by_tag_name("td")

i = 0
# this will only loop once as a test
while i < 0:
    ticker = str(tickers[i].text)
    print(ticker)
    order = equity_buy_market(ticker, 1)
    r = c.place_order(config.tda_acct_num, order)
    time.sleep(2)
    print(r.status_code)
    i += 10
driver.quit()
示例#18
0
tickers = driver.find_elements_by_tag_name("td")

# positions = c.get_account(config.tda_acct_num, c.Account.Fields.POSITIONS)
# print(positions)

# i = 0
# # [0]:Ticker, [1]:Share Price, [2]:Rating, [3]:Score, [4]:Rating Change Date, [5]:Price Change %
# while i < 40:
#     ticker = str(tickers[i].text)
#     print(ticker)

#     share_price = float(tickers[i + 1].text)
#     # How many dollars of each stock to buy:
#     desired_dollar_amount = 1000
#     num_shares = round(desired_dollar_amount / share_price)
#     print(num_shares)

#     order = equity_buy_market(ticker, num_shares)
#     r = c.place_order(config.tda_acct_num, order)
#     time.sleep(2)
#     print(r.status_code)
#     print(r)
#     i += 10

driver.quit()

order = equity_buy_market('ticker', num_shares)
r = c.place_order(config.tda_acct_num, order)
time.sleep(2)
print(r.status_code)
print(r)
示例#19
0
time.sleep(2)

button.click()

time.sleep(2)

tickers = driver.find_elements_by_tag_name("td")
i = 0
while i < 10:
    print(tickers[i].text)

    c.place_order(
        config.tda_acct_num,  # account_id
        print(
            equity_buy_market(
                (tickers[i].text),
                1).set_duration(Duration.GOOD_TILL_CANCEL).set_session(
                    Session.SEAMLESS).build()))
    i += 10
# for ticker in tickers:
#     print(ticker.text)
# print(ticker.tag_name)
# print(ticker.parent)
# print(ticker.location)
# print(ticker.size)
# time.sleep(2)

driver.quit()

# [0]: Ticker, [1]: Price, [2]: Rating, [3]: Score, [4]:Rating Change Date, [5]:Price Change %
# SVM
# 6.70
示例#20
0
button = driver.find_element_by_css_selector(
    'span[data-sort-name="stock_score_normalized"]'
)
time.sleep(2)

button.click()

time.sleep(2)

tickers = driver.find_elements_by_tag_name("td")
i = 0
while i < 20:
    print(tickers[i].text)

    client.place_order( 1000, equity_buy_market(tickers[i].text, 1) .set_duration(Duration.GOOD_TILL_CANCEL).set_session(Session.SEAMLESS).build())
            i+=10
# for ticker in tickers:
#     print(ticker.text)
    # print(ticker.tag_name)
    # print(ticker.parent)
    # print(ticker.location)
    # print(ticker.size)
# time.sleep(2)

driver.quit()

# [0]: Ticker, [1]: Price, [2]: Rating, [3]: Score, [4]:Rating Change Date, [5]:Price Change %
# SVM
# 6.70
# Buy