def get_price(symbol):
    symbol = symbol.upper()
    robinhood = Robinhood()
    robinhood.login(username=username, password=password)

    current_price = float(robinhood.quote_data(symbol)['last_trade_price'])
    current_price_str = "$%.2f" % current_price

    print(symbol)
    x = robinhood.quote_data(symbol)['last_extended_hours_trade_price']
    if x is None:
        return current_price_str

    extended_price = float(x)
    extended_price_str = "$%.2f" % extended_price

    return current_price_str + "," + extended_price_str
Esempio n. 2
0
def gather(stock,count):

    # import the robinhood api library
    from Robinhood import Robinhood
    import os
    import time
    import datetime
    


    #key setup
    import ast
    keys =[]
    f = open('keys')
    keys = ast.literal_eval(f.read())
    f.close()
    
    # login
    ## log into robinhood
    my_trader = Robinhood();
    my_trader.login(username=keys[0][1], password=keys[1][1])

    # stock selection
    ## the variable 'stock' is a string passed through the function
    #stock = sys.argv[1].upper()
    stock = stock.upper()
    stock_instrument = my_trader.instruments(stock)[0]

    # variable declaration
    last_trade = 0
    bid_price = 0
    ask_price = 0
    #count = 1
    #sell_prices = []
    #sell_price_slope = 0
    #sell_average_prices = []
    #sell_slope_of_averages = 0
    #sell_sd = []
    #sell_sum = 0
    
    # make timestamp
    stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
    #stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%S.%f')
    
    # set up quote data
    quote_data = my_trader.quote_data(stock)
    last_trade = float(quote_data['last_trade_price'])
    bid_price = float(quote_data['bid_price'])
    ask_price = float(quote_data['ask_price'])
    
    payload = [stamp,last_trade,ask_price,bid_price]
   
    # push to redis
    import redis
    r_server = redis.Redis(host='localhost',port=6669)
    r_server.zadd(stock, payload, count)
Esempio n. 3
0
def gather(stock, count):

    # import the robinhood api library
    from Robinhood import Robinhood
    import os
    import time
    import datetime

    #key setup
    import ast
    keys = []
    f = open('keys')
    keys = ast.literal_eval(f.read())
    f.close()

    # login
    ## log into robinhood
    my_trader = Robinhood()
    my_trader.login(username=keys[0][1], password=keys[1][1])

    # stock selection
    ## the variable 'stock' is a string passed through the function
    #stock = sys.argv[1].upper()
    stock = stock.upper()
    stock_instrument = my_trader.instruments(stock)[0]

    # variable declaration
    last_trade = 0
    bid_price = 0
    ask_price = 0
    #count = 1
    #sell_prices = []
    #sell_price_slope = 0
    #sell_average_prices = []
    #sell_slope_of_averages = 0
    #sell_sd = []
    #sell_sum = 0

    # make timestamp
    stamp = datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
    #stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%S.%f')

    # set up quote data
    quote_data = my_trader.quote_data(stock)
    last_trade = float(quote_data['last_trade_price'])
    bid_price = float(quote_data['bid_price'])
    ask_price = float(quote_data['ask_price'])

    payload = [stamp, last_trade, ask_price, bid_price]

    # push to redis
    import redis
    r_server = redis.Redis(host='localhost', port=6669)
    r_server.zadd(stock, payload, count)
Esempio n. 4
0
class RobinhoodSource(object):
    def __init__(self, stock, stock_friendly_name, r_username, r_password):
        self.stock = stock
        self.stock_friendly_name = stock_friendly_name
        self.r_username = r_username
        self.r_password = r_password
        self.my_trader = Robinhood()
        logged_in = self.my_trader.login(username=self.r_username, password=self.r_password)
        if not logged_in:
            raise Exception("Failed to login")
        self.quote = self.my_trader.quote_data(self.stock)


    def set_position(self, avg_price, shares, unvested_shares):
        self.avg_price = avg_price
        self.shares = shares
        self.unvested_shares = unvested_shares


    @property
    def quote(self):
        return self.robinhood_quote


    @quote.setter
    def quote(self, robinhood_quote_dict):
        self.robinhood_quote = RobinhoodQuote(robinhood_quote_dict)


    def get_response(self):
        slugs = {
            'last_trade_price': float(self.quote.last_trade_price),
            'previous_close': float(self.quote.previous_close),
            'stock_friendly_name':  self.stock_friendly_name
        }
        slugs['stock_percent_change'] = 100.0 * ((slugs['last_trade_price'] - slugs['previous_close']) / slugs['previous_close'])
        slugs['stock_percent_change_abs'] = abs(slugs['stock_percent_change'])
        slugs['stock_up_down'] = 'up' if slugs['stock_percent_change'] > 0.0 else 'down'
        ar = AlexaResponse(slugs, preamble='From Robinhood')
        ar.add_blurb("{stock_friendly_name} stock is {stock_up_down} {stock_percent_change_abs:.1f}%, trading at ${last_trade_price:.0f}")
        ar.set_title(ar.get_blurbs()[0])
        if set(['avg_price', 'unvested_shares', 'shares']).intersection(dir(self)):
            slugs['portfolio_percent_change'] = 100 * ((slugs['last_trade_price'] - self.avg_price) / self.avg_price)
            slugs['portfolio_percent_change_abs'] = abs(slugs['portfolio_percent_change'])
            slugs['portfolio_up_down'] = 'up' if slugs['portfolio_percent_change'] > 0.0 else 'down'
            slugs['portfolio_vested_value'] = float(self.shares) * slugs['last_trade_price']
            slugs['portfolio_potential_value'] = (self.shares + self.unvested_shares) * slugs['last_trade_price']
            ar.add_blurb("You are {portfolio_up_down} {portfolio_percent_change_abs:.1f}" +
                " percent with a total value of approximately ${portfolio_vested_value:0.0f}" +
                " and a potential value of ${portfolio_potential_value:0.0f} if all shares vest")
        return ar
Esempio n. 5
0
class RobinhoodAPI:
    def __init__(self):
        logger.info("logging into Robinhood...")
        robinhood_username = os.environ.get('ROBINHOOD_USERNAME')
        robinhood_password = os.environ.get('ROBINHOOD_PASSWORD')
        self._api = Robinhood()
        self._api.login(username=robinhood_username,
                        password=robinhood_password)
        logger.info("logged in to Robinhood.")

    def get_stock_quote(self, stock: Stock) -> RobinHoodStock:
        robinhood_stock = None
        try:
            robinhood_stock = RobinHoodStock(
                last_trade=self._api.quote_data(stock.code))
        except Exception as e:
            logger.info("Error while fetching quote: {}".format(e))
        return robinhood_stock
import schedule
import time
from Robinhood import Robinhood
import pprint
import pika
import json
from os import environ

#Robinhood example
#Setup
my_trader = Robinhood()
#login
my_trader.login(username=environ.get('RH_USER'),
                password=environ.get('RH_PASSWORD'))
#Get a stock's quote
my_trader.print_quote("AAPL")
print(my_trader.quote_data("AAPL"))
Esempio n. 7
0
    if exchange_closed:
        print("Exhange not Open. Passing.")
        pass

    else:
        for key in securities['results']:

            instrument = my_trader.get_url(
                key['instrument'])  #get symbol of stock
            name = instrument['symbol']

            # no get out position info
            quantity_owned = float(key['quantity'])
            price_bought = float(key['pending_average_buy_price'])
            quote = my_trader.quote_data(name)
            #print quote
            last_price = float(quote['last_trade_price'])
            time_of_last_price = quote['updated_at']

            # write to the file
            with open('price_{}.csv'.format(name), 'a') as fd:
                line = str(time_of_last_price) + ', ' + str(last_price) + '\n'
                fd.write(line)

            print "-------"
            print name + ':'
            print('Info  : ' + str(quantity_owned) + ' shares bought for $' +
                  str(price_bought) + ' per share. Now at $' + str(last_price))
            print('Return: $' + str(quantity_owned *
                                    (last_price - price_bought)))
Esempio n. 8
0
            try_signin = False
            signin = False
            logger.info("Dev Robinhood STOPPED")

if (signin):
    logger.info("Getting histoical data for NIO")
    stock_instrument = my_trader.instruments('NIO')[0]
    week = my_trader.get_historical_quotes('NIO', '5minute', 'week')
    prices = week['results'][0]['historicals']
    result = get_Prices(prices, "NIO")
    print(result)

    #number of peaks per day
    #avegare number of peaks

    currentQuote = my_trader.quote_data("NIO")
    print(currentQuote)
    startingLastTradePrice = float(currentQuote['last_trade_price'])
    allowance = 100
    numStocks = float(allowance / startingLastTradePrice)
    targetBuyPercent = 1
    targetSellPercent = 1
    stocksBought = 0

    startingMedianPrice = float(result['median'])
    allowance2 = 100
    numStocks2 = float(allowance / startingMedianPrice)
    targetBuyPercent2 = 1
    targetSellPercent2 = 1
    stocksBought2 = 0
    while (True):
Esempio n. 9
0
import config
from Robinhood import Robinhood

robinhood = Robinhood()

logged_in = robinhood.login(username=config.username, password=config.password)

stock = robinhood.instruments("SBUX")[0]

print("Printing stock instrument info")
print(stock)

quote = robinhood.quote_data("SBUX")

print("Printing quote data for Starbucks")
print(quote)
Esempio n. 10
0
class RobinhoodShell(cmd.Cmd):
    intro = 'Welcome to the Robinhood shell. Type help or ? to list commands.\n'
    prompt = '> '

    # API Object
    trader = None

    # Cache file used to store instrument cache
    instruments_cache_file = 'instruments.data'

    # Maps Symbol to Instrument URL
    instruments_cache = {}

    # Maps URL to Symbol
    instruments_reverse_cache = {}

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.trader = Robinhood()
        self.trader.login_prompt()

        try:
            data = open('instruments.data').read()
            self.instruments_cache = json.loads(data)
            for k in self.instruments_cache:
                self.instruments_reverse_cache[self.instruments_cache[k]] = k
        except:
            pass

    # ----- basic commands -----
    def do_l(self, arg):
        'Lists current portfolio'
        portfolio = self.trader.portfolios()
        print 'Equity Value:', portfolio['equity']

        account_details = self.trader.get_account()
        if 'margin_balances' in account_details:
            print 'Buying Power:', account_details['margin_balances']['unallocated_margin_cash']

        positions = self.trader.securities_owned()

        symbols = []
        buy_price_data = {}
        for position in positions['results']:
            symbol = self.get_symbol(position['instrument'])
            buy_price_data[symbol] = position['average_buy_price']
            symbols.append(symbol)

        raw_data = self.trader.quote_data(symbols)
        quotes_data = {}
        for quote in raw_data:
            quotes_data[quote['symbol']] = quote['last_trade_price']

        table = BeautifulTable()
        table.column_headers = ["symbol", "current price", "quantity", "total equity", "cost basis", "p/l"]

        for position in positions['results']:
            quantity = int(float(position['quantity']))
            symbol = self.get_symbol(position['instrument'])
            price = quotes_data[symbol]
            total_equity = float(price) * quantity
            buy_price = float(buy_price_data[symbol])
            p_l = total_equity - buy_price * quantity
            table.append_row([symbol, price, quantity, total_equity, buy_price, p_l])

        print(table)

    def do_b(self, arg):
        'Buy stock b <symbol> <quantity> <price>'
        parts = arg.split()
        if len(parts) == 3:
            symbol = parts[0]
            quantity = parts[1]
            price = float(parts[2])

            stock_instrument = self.trader.instruments(symbol)[0]
            res = self.trader.place_buy_order(stock_instrument, quantity, price)

            if not (res.status_code == 200 or res.status_code == 201):
                print "Error executing order"
                try:
                    data = res.json()
                    if 'detail' in data:
                        print data['detail']
                except:
                    pass
            else:
                print "Done"
        else:
            print "Bad Order"

    def do_s(self, arg):
        'Sell stock s <symbol> <quantity> <price>'
        parts = arg.split()
        if len(parts) == 3:
            symbol = parts[0]
            quantity = parts[1]
            price = float(parts[2])

            stock_instrument = self.trader.instruments(symbol)[0]
            res = self.trader.place_sell_order(stock_instrument, quantity, price)

            if not (res.status_code == 200 or res.status_code == 201):
                print "Error executing order"
                try:
                    data = res.json()
                    if 'detail' in data:
                        print data['detail']
                except:
                    pass
            else:
                print "Done"
        else:
            print "Bad Order"

    def do_o(self, arg):
        'List open orders'
        open_orders = self.trader.get_open_orders()
        if open_orders:
            table = BeautifulTable()
            table.column_headers = ["symbol", "price", "quantity", "type", "id"]

            for order in open_orders:
                table.append_row([
                    self.get_symbol(order['instrument']),
                    order['price'],
                    int(float(order['quantity'])),
                    order['side'],
                    order['id'],
                ])

            print(table)
        else:
            print "No Open Orders"

    def do_c(self, arg):
        'Cancel open order c <id>'
        order_id = arg.strip()
        try:
            self.trader.cancel_order(order_id)
            print "Done"
        except Exception as e:
            print "Error executing cancel"
            print e

    def do_q(self, arg):
        'Get quote for stock q <symbol>'
        symbol = arg.strip()
        try:
            self.trader.print_quote(symbol)
        except:
            print "Error getting quote for:", symbol

    def do_bye(self, arg):
        open(self.instruments_cache_file, 'w').write(json.dumps(self.instruments_cache))
        return True

    # ------ utils --------
    def get_symbol(self, url):
        if not url in self.instruments_reverse_cache:
            self.add_instrument_from_url(url)

        return self.instruments_reverse_cache[url]

    def add_instrument_from_url(self, url):
        data = self.trader.get_url(url)
        symbol = data['symbol']
        self.instruments_cache[symbol] = url
        self.instruments_reverse_cache[url] = symbol
Esempio n. 11
0
position = div.find(FEAR_AND_GREED_PHRASE)
position = position + len(FEAR_AND_GREED_PHRASE)

current_fear_and_greed_index = int(div[position:position + 3].strip())

print(current_fear_and_greed_index)
print(type(current_fear_and_greed_index))

others_are_greedy = current_fear_and_greed_index >= GREED_THRESOLD
others_are_fearful = current_fear_and_greed_index <= FEAR_THRESOLD

# robinhood setup
robinhood = Robinhood()
logged_in = robinhood.login(username=config.username, password=config.password)
instrument = robinhood.instruments(INTSTRUMENT_TO_BUY)[0]

print("Printing stock instrument info")
print(stock)

quote = robinhood.quote_data(INTSTRUMENT_TO_BUY)

print("Printing quote data for {}".format(INTSTRUMENT_TO_BUY))
print(quote)

if others_are_greedy:
    # sell
    sell_order = robinhood.place_sell_order(instrument, 1)

if others_are_fearful:
    # buy
    buy_order = robinhood.place_buy_order(instrument, 1)
Esempio n. 12
0
class RobinhoodShell(cmd.Cmd):
    intro = 'Welcome to the Robinhood shell. Type help or ? to list commands.\n'
    prompt = '> '

    # API Object
    trader = None

    # Cache file used to store instrument cache
    instruments_cache_file = 'instruments.data'

    # Maps Symbol to Instrument URL
    instruments_cache = {}

    # Maps URL to Symbol
    instruments_reverse_cache = {}

    # Cache file used to store instrument cache
    watchlist_file = 'watchlist.data'

    # Auth file
    auth_file = 'auth.data'

    # List of stocks in watchlist
    watchlist = []

    def _save_auth_data(self):
        auth_data = {}
        auth_data['device_token'] = self.trader.device_token
        auth_data['auth_token'] = self.trader.auth_token
        auth_data['refresh_token'] = self.trader.refresh_token
        open(self.auth_file, 'w').write(json.dumps(auth_data))

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.trader = Robinhood()

        # Robinhood now uses 2FA
        # The workflow we use is as follows
        # If we find auth token in auth.data - try to see if it still works
        # If yes, continue
        # If no, try to refresh the token using refresh token
        # If it still fails, we need to relogin with 2FA
        try:
            data = open(self.auth_file).read()
            auth_data = json.loads(data)
            if 'auth_token' in auth_data:
              self.trader.device_token = auth_data['device_token']
              self.trader.auth_token = auth_data['auth_token']
              self.trader.refresh_token = auth_data['refresh_token']
              self.trader.headers['Authorization'] = 'Bearer ' + self.trader.auth_token
              try:
                self.trader.user()
              except:
                del self.trader.headers['Authorization']
                self.trader.relogin_oauth2()
                self._save_auth_data()
        except:
            challenge_type = 'email'
            if CHALLENGE_TYPE == 'sms':
              challenge_type = 'sms'
            self.trader.login(username = USERNAME, password = PASSWORD, challenge_type = challenge_type)
            self._save_auth_data()

        try:
            data = open(self.instruments_cache_file).read()
            self.instruments_cache = json.loads(data)
            for k in self.instruments_cache:
                self.instruments_reverse_cache[self.instruments_cache[k]] = k
        except:
            pass

        try:
            data = open(self.watchlist_file).read()
            self.watchlist = json.loads(data)
        except:
            pass

    # nytime = parser.parse('2018-06-15T23:14:15Z').astimezone(to_zone)
    # from dateutil import parser

    # ----- basic commands -----
    def do_l(self, arg):
        'Lists current portfolio'
        t = Terminal()
        portfolio = self.trader.portfolios()
        if portfolio['extended_hours_equity']:
            equity =  float(portfolio['extended_hours_equity'])
        else:
            equity =  float(portfolio['equity'])

        eq = '%.2f' % equity
        previous_close = float(portfolio['adjusted_equity_previous_close'])
        change = equity - previous_close
        change_pct =  '%.2f' % (change/previous_close * 100.0)

        # format
        change = f"{change:.2f}"

        # colorize
        change_pct = color_data(change_pct)
        change = color_data(change)

        account_details = self.trader.get_account()
        if 'margin_balances' in account_details:
            buying_power = account_details['margin_balances']['unallocated_margin_cash']

        account_table = SingleTable([['Portfolio Value','Change','Buying Power'],[eq, change+' ('+change_pct+'%)', buying_power]],'Account')
        print((account_table.table))

        # Load Stocks
        positions = self.trader.securities_owned()
        instruments = [position['instrument'] for position in positions['results']]
        symbols = [self.get_symbol(position['instrument']) for position in positions['results']]

        market_data = self.trader.get_stock_marketdata(instruments)

        table_data = []
        table_data.append(["Symbol", "Last", "Shares", "Equity", "Avg Cost", "Return" , "Day", "EquityChange", "Day %"])

        i = 0
        for position in positions['results']:
            quantity = int(float(position['quantity']))
            symbol = self.get_symbol(position['instrument'])
            price = market_data[i]['last_trade_price']
            total_equity = float(price) * quantity
            buy_price = float(position['average_buy_price'])
            p_l = f"{total_equity - (buy_price * quantity):.2f}"
            total_equity = f"{total_equity:.2f}"
            buy_price = f"{buy_price:.2f}"
            day_change = f"{float(market_data[i]['last_trade_price']) - float(market_data[i]['previous_close']):.2f}"
            day_change_q_val = f"{float(quantity) * float(day_change):.2f}"
            day_change_pct = f"{float(day_change) / float(market_data[i]['previous_close']) * 100:.2f}"
            price = f"{float(price):.2f}"

            table_data.append([
                symbol,
                price,
                quantity,
                total_equity,
                buy_price,
                color_data(p_l),
                color_data(day_change),
                color_data(day_change_q_val),
                color_data(day_change_pct)
                ])
            i += 1

        table = SingleTable(table_data,'Portfolio')
        table.inner_row_border = True
        table.justify_columns = {0: 'center' }

        print((table.table))

    def do_lo(self, arg):
        'Lists current options portfolio'
        # Load Options
        options_t_data=[]
        option_positions = self.trader.options_owned()
        options_table = SingleTable(options_t_data,'Options')
        options_table.inner_row_border = True
        options_table.justify_columns = {0: 'center' }
        options_t_data.append(["Symbol","Type","Experation","Strike", "Price", "QTY", "Equity", "Cost", "Total Return","Today"])

        for op in option_positions:
            quantity = float(op['quantity'])
            if quantity == 0:
                continue

            cost = float(op['average_price'])
            if op['type'] == 'short':
                quantity = -quantity
                cost = -cost

            instrument = op['option']
            option_data = self.trader.session.get(instrument).json()
            # skip expired  -- verify when it changes state day of or, after market close on expieration
            if option_data['state'] == "expired":
                continue
            expiration_date = option_data['expiration_date']
            strike = float(option_data['strike_price'])
            type = option_data['type']
            symbol = op['chain_symbol']
            option_type = str(type).upper()
            expiration = expiration_date
            strike_price = '$'+str(strike)
            info = self.trader.get_option_marketdata(instrument)
            last_price = float(info['adjusted_mark_price'])
            total_equity = (100 * last_price) * quantity
            change = total_equity - (float(cost) * quantity)
            change_pct = '{:04.2f}'.format(change / float(cost) * 100)
            day_change = float(info['adjusted_mark_price']) - float(info['previous_close_price'])
            day_pct = '{:04.2f}'.format((day_change / float(info['previous_close_price']) ) * 100)
            # format after calc
            day_change = f"{day_change:.3f}"
            options_t_data.append([
                symbol,option_type,
                expiration,
                strike_price ,
                last_price,
                quantity,
                total_equity,
                cost,
                color_data(change) +' ('+ color_data(change_pct) +'%)',
                color_data(day_change) +' ('+ color_data(day_pct) +'%)'
                ])

        print((options_table.table))

    def do_w(self, arg):
        'Show watchlist w \nAdd to watchlist w a <symbol> \nRemove from watchlist w r <symbols>'
        parts = re.split('\W+',arg.upper())

        if len(parts) >= 2:
            if parts[0] == 'A':
                for p in parts[1:]:
                    if p not in self.watchlist:
                        self.watchlist.append(p.strip())
            if parts[0] == 'R':
                self.watchlist = [r for r in self.watchlist if r not in parts[1:]]
            print("Done")
        else:
            watch_t_data=[]
            watch_table = SingleTable(watch_t_data,'Watch List')
            watch_table.inner_row_border = True
            watch_table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3:'center',4: 'center'}
            watch_t_data.append(["Symbol","Ask Price", "Open", "Today", "%"])

            if len(self.watchlist) > 0:
                instruments = [self.get_instrument(s)['url'] for s in
                        self.watchlist]
                raw_data = self.trader.get_stock_marketdata(instruments)
                quotes_data = {}
                for quote in raw_data:
                    day_change = float(quote['last_trade_price']) - float(quote['previous_close'])
                    day_change_pct = '{:05.2f}'.format(( day_change / float(quote['previous_close']) ) * 100)
                    watch_t_data.append([
                        quote['symbol'],
                        '{:05.2f}'.format(float(quote['last_trade_price'])),
                        '{:05.2f}'.format(float(quote['previous_close'])),
                        color_data(day_change),
                        color_data(day_change_pct)
                        ])
                print((watch_table.table))
            else:
                print("Watchlist empty!")

    def do_b(self, arg):
        'Buy stock b <symbol> <quantity> <price>'
        parts = arg.split()
        if len(parts) >= 2 and len(parts) <= 3:
            symbol = parts[0].upper()
            quantity = parts[1]
            if len(parts) == 3:
                price = float(parts[2])
            else:
                price = 0.0

            stock_instrument = self.get_instrument(symbol)
            if not stock_instrument['url']:
                print("Stock not found")
                return

            res = self.trader.place_buy_order(stock_instrument, quantity, price)

            if not (res.status_code == 200 or res.status_code == 201):
                print("Error executing order")
                try:
                    data = res.json()
                    if 'detail' in data:
                        print(data['detail'])
                except:
                    pass
            else:
                print("Done")
        else:
            print("Bad Order")

    def do_s(self, arg):
        'Sell stock s <symbol> <quantity> <?price>'
        parts = arg.split()
        if len(parts) >= 2 and len(parts) <= 3:
            symbol = parts[0].upper()
            quantity = parts[1]
            if len(parts) == 3:
                price = float(parts[2])
            else:
                price = 0.0

            stock_instrument = self.get_instrument(symbol)
            if not stock_instrument['url']:
                print("Stock not found")
                return

            res = self.trader.place_sell_order(stock_instrument, quantity, price)

            if not (res.status_code == 200 or res.status_code == 201):
                print("Error executing order")
                try:
                    data = res.json()
                    if 'detail' in data:
                        print(data['detail'])
                except:
                    pass
            else:
                print("Done")
        else:
            print("Bad Order")

    def do_sl(self, arg):
        'Setup stop loss on stock sl <symbol> <quantity> <price>'
        parts = arg.split()
        if len(parts) == 3:
            symbol = parts[0].upper()
            quantity = parts[1]
            price = float(parts[2])

            stock_instrument = self.trader.instruments(symbol)[0]
            res = self.trader.place_stop_loss_order(stock_instrument, quantity, price)

            if not (res.status_code == 200 or res.status_code == 201):
                print("Error executing order")
                try:
                    data = res.json()
                    if 'detail' in data:
                        print(data['detail'])
                except:
                    pass
            else:
                print("Done")
        else:
            print("Bad Order")

    def do_o(self, arg):
        'List open orders'
        open_orders = self.trader.get_open_orders()
        if open_orders:
            open_t_data=[]
            open_table = SingleTable(open_t_data,'open List')
            open_table.inner_row_border = True
            open_table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3:'center',4: 'center'}
            open_t_data.append( ["index", "symbol", "price", "quantity", "type", "id"])

            index = 1
            for order in open_orders:

                if order['trigger'] == 'stop':
                    order_price = order['stop_price']
                    order_type  = "stop loss"
                else:
                    order_price = order['price']
                    order_type  = order['side']+" "+order['type']

                open_t_data.append([
                    index,
                    self.get_symbol(order['instrument']),
                    order_price,
                    int(float(order['quantity'])),
                    order_type,
                    order['id'],
                ])
                index += 1

            print((open_table.table))
        else:
            print("No Open Orders")

    def do_c(self, arg):
        'Cancel open order c <index> or c <id>'
        order_id = arg.strip()
        order_index = -1
        try:
            order_index = int(order_id)
        except:
            pass

        if order_index > 0:
            order_index = order_index - 1
            open_orders = self.trader.get_open_orders()
            if order_index < len(open_orders):
                order_id = open_orders[order_index]['id']
            else:
                print("Bad index")
                return

        try:
            self.trader.cancel_order(order_id)
            print("Done")
        except Exception as e:
            print("Error executing cancel")
            print(e)

    def do_ca(self, arg):
        'Cancel all open orders'
        open_orders = self.trader.get_open_orders()
        for order in open_orders:
            try:
                self.trader.cancel_order(order['id'])
            except Exception as e:
                pass
        print("Done")

    def do_news(self,arg,show_num=5):
        if len(arg) == 0:
            print("Missing symbol")
        else:
            news_data = self.trader.get_news(arg.upper())

            if news_data['count'] == 0:
                print("No News available")
                return

            for x in range(0,show_num):
                news_box(news_data['results'][x]['source'], news_data['results'][x]['published_at'], news_data['results'][x]['summary'], news_data['results'][x]['title'],news_data['results'][x]['url'])

    def do_mp(self, arg):
        'Buy as many shares possible by defined max dollar amount:  mp <symbol> <max_spend> <?price_limit>'
        parts = arg.split()
        if len(parts) >= 2 and len(parts) <= 3:
            symbol = parts[0].upper()
            #quantity = parts[1]
            spend = parts[1]
            if len(parts) == 3:
                print("Parts: 3")
                price_limit = float(parts[2])
            else:
                price_limit = 0.0

            try:
                cur_data = self.trader.quote_data(symbol)
                last_price = cur_data['last_trade_price']
            except:
                print("Invalid Ticker?")
                pass
                return

            # quote['last_trade_price']
            quantity = int(math.floor(float(spend) / float(last_price)))
            print(("\nBuying %s\n Max Spend: %s\nQTY: %s\n Current Price: %s\nMax Price: %s\n" % (symbol,spend, quantity, last_price, price_limit)))

   #         stock_instrument = self.trader.instruments(symbol)[0]
   #         res = self.trader.place_buy_order(stock_instrument, quantity, price)

   #         if not (res.status_code == 200 or res.status_code == 201):
   #             print "Error executing order"
   #             try:
   #                 data = res.json()
   #                 if 'detail' in data:
   #                     print data['detail']
   #             except:
   #                 pass
   #         else:
   #             print "Done"
   #     else:
   #         print "Bad Order"

    def do_q(self, arg):
        'Get detailed quote for stock: q <symbol(s)>'

        symbols = re.split('\W+',arg.upper())

        if len(arg) == 0:
            print("Missing symbol(s)")
        else:
            instruments = [self.get_instrument(s)['url'] for s in symbols]
            raw_data = self.trader.get_stock_marketdata(instruments)
            quotes_data = {}
            quote_t_data=[]
            quote_table = SingleTable(quote_t_data,'Quote List')
            quote_table.inner_row_border = True
            quote_table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3:'center',4: 'center'}
            quote_t_data.append(["Symbol", "Current Price", "Open","Change", "Ask","Bid"])
            for quote in raw_data:
                if not quote:
                    continue
                day_change = float(quote['last_trade_price']) - float(quote['previous_close'])
                day_change_pct = ( day_change / float(quote['previous_close']) ) * 100
                ask_price = '{:05.2f}'.format(float(quote['ask_price']))
                ask_size = quote['ask_size']
                bid_price = '{:05.2f}'.format(float(quote['bid_price']))
                bid_size  = quote['bid_size']
                quote_t_data.append([
                    quote['symbol'],
                    '{:05.2f}'.format(float(quote['last_trade_price'])),
                    '{:05.2f}'.format(float(quote['previous_close'])),
                    color_data(day_change)+' ('+color_data('{:05.2f}'.format(day_change_pct))+'%)',
                    str(ask_price)+' x '+str(ask_size),
                    str(bid_price)+' x '+str(bid_size)
                    ])
            print((quote_table.table))

    def do_qq(self, arg):
        'Get quote for stock q <symbol> or option q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd>'
        arg = arg.strip().split()
        try:
            symbol = arg[0].upper()
        except:
            print("Please check arguments again. Format: ")
            print("Stock: q <symbol>")
            print("Option: q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd>")
        type = strike = expiry = None
        if len(arg) > 1:
            try:
                type = arg[1]
                strike = arg[2]
            except Exception as e:
                print("Please check arguments again. Format: ")
                print("q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd>")

            try:
                expiry = arg[3]
            except:
                expiry = None

            arg_dict = {'symbol': symbol, 'type': type, 'expiration_dates': expiry, 'strike_price': strike, 'state': 'active', 'tradability': 'tradable'};
            quotes = self.trader.get_option_quote(arg_dict);

            qquote_t_data=[]
            qquote_table = SingleTable(qquote_t_data,'Quote List')
            qquote_table.inner_row_border = True
            qquote_table.justify_columns = {0: 'center', 1: 'center'}
            qquote_t_data.append(['expiry', 'price'])

            for row in quotes:
                qquote_t_data.append(row)

            print((qquote_table.table))
        else:
            try:
                self.trader.print_quote(symbol)
            except:
                print("Error getting quote for:", symbol)

    def do_bye(self, arg):
        open(self.instruments_cache_file, 'w').write(json.dumps(self.instruments_cache))
        open(self.watchlist_file, 'w').write(json.dumps(self.watchlist))
        self._save_auth_data()
        return True

    # ------ utils --------
    def get_symbol(self, url):
        if not url in self.instruments_reverse_cache:
            self.add_instrument_from_url(url)

        return self.instruments_reverse_cache[url]

    def get_instrument(self, symbol):
        if not symbol in self.instruments_cache:
            instruments = self.trader.instruments(symbol)
            for instrument in instruments:
                self.add_instrument(instrument['url'], instrument['symbol'])

        url = ''
        if symbol in self.instruments_cache:
            url = self.instruments_cache[symbol]

        return { 'symbol': symbol, 'url': url }

    def add_instrument_from_url(self, url):
        data = self.trader.get_url(url)
        if 'symbol' in data:
            symbol = data['symbol']
        else:
            types = { 'call': 'C', 'put': 'P'}
            symbol = data['chain_symbol'] + ' ' + data['expiration_date'] + ' ' + ''.join(types[data['type']].split('-')) + ' ' + str(float(data['strike_price']))
        self.add_instrument(url, symbol)

    def add_instrument(self, url, symbol):
        self.instruments_cache[symbol] = url
        self.instruments_reverse_cache[url] = symbol
Esempio n. 13
0
         print ('Week Day - Sleep 16 hrs')
         time.sleep(57600)
 #Lets find out if Robinhood has updated yesterday closing data
 conn = sqlite3.connect(path)
 conn.row_factory = sqlite3.Row
 c = conn.cursor()       
 c.execute('''
       SELECT * FROM stocks 
       ORDER BY previous_close_date DESC''')
 row_verify = c.fetchone()
 conn.close()
 #login
 working = False 
 while not working:
     try: 
         quote_data = trader.quote_data(row_verify['symbol'])
         working = True 
     except:
         print ('Failed to Get Quote')    
         try:
             time.sleep(ref_time)
             trader = Robinhood()
             trader.login(username=loginstr[0],password=loginstr[1],qr_code=loginstr[2])
             print ('Login')
         except:
             print ('Cant Login')
             time.sleep(ref_time)
             pass
         pass
 #Load database once daily with current securities and watchlist data
 if quote_data['previous_close_date'] > row_verify['previous_close_date']:
Esempio n. 14
0
class TKshell(cmd.Cmd):
    intro = 'Welcome to the Robinhood shell. Type help or ? to list commands.\n'
    prompt = '> '

    # API Object
    trader = None

    # Cache file used to store instrument cache
    instruments_cache_file = 'instruments.data'

    # Maps Symbol to Instrument URL
    instruments_cache = {}

    # Maps URL to Symbol
    instruments_reverse_cache = {}

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.trader = Robinhood()
        self.trader.login_prompt()

        try:
            data = open('instruments.data').read()
            self.instruments_cache = json.loads(data)
            for k in self.instruments_cache:
                self.instruments_reverse_cache[self.instruments_cache[k]] = k
        except:
            pass

    # ----- basic commands -----
    def do_l(self, arg):
        'Lists current portfolio'
        portfolio = self.trader.portfolios()
        print('Equity Value:', portfolio['equity'])

        account_details = self.trader.get_account()
        if 'margin_balances' in account_details:
            print(
                'Buying Power:',
                account_details['margin_balances']['unallocated_margin_cash'])

        positions = self.trader.securities_owned()

        symbols = ''
        buy_price_data = {}
        for position in positions['results']:
            symbol = self.get_symbol(position['instrument'])
            buy_price_data[symbol] = position['average_buy_price']
            symbols += symbol + ','
        symbols = symbols[:-1]

        raw_data = self.trader.quote_data(symbols)
        quotes_data = {}
        for quote in raw_data:
            quotes_data[quote['symbol']] = quote['last_trade_price']
        d = []
        for position in positions['results']:
            quantity = int(float(position['quantity']))
            symbol = self.get_symbol(position['instrument'])
            price = quotes_data[symbol]
            total_equity = float(price) * quantity
            buy_price = float(buy_price_data[symbol])
            p_l = total_equity - buy_price * quantity
            d.append([symbol, price, quantity, total_equity, buy_price, p_l])

        column_headers = [
            "symbol", "current price", "quantity", "total equity",
            "cost basis", "p/l"
        ]
        table = tabulate(d, headers=column_headers)
        print(table)

    def do_q(self, arg):
        'Get quote for stock q <symbol>'
        symbols = arg.strip()
        headers = [
            'symbol', 'price', 'bid_size', 'bid_price', 'ask_size', 'ask_price'
        ]
        try:
            data = self.trader.get_quote_list(
                symbols,
                'symbol,last_trade_price,bid_size,bid_price,ask_size,ask_price'
            )
            print(tabulate(data, headers=headers))
        except:
            print("Error getting quote for:", symbols)

    def do_b(self, arg):
        'Buy stock b <symbol> <quantity> <price>'
        parts = arg.split()
        if len(parts) == 3:
            symbol = parts[0]
            quantity = parts[1]
            price = round(float(parts[2]), 2)

            stock_instrument = self.trader.instruments(symbol)[0]
            res = self.trader.place_buy_order(stock_instrument, quantity,
                                              price)

            if not (res.status_code == 200 or res.status_code == 201):
                print("Error executing order")
                try:
                    data = res.json()
                    if 'detail' in data:
                        print(data['detail'])
                except:
                    pass
            else:
                print("Done")
        else:
            print("Bad Order")

    def do_qb(self, arg):
        '''
        Quick Buy
        a quick buy is a limit buy which price is set at previous close + 15% * previous candle body
        :param arg: <symbol> <quantity>
        :return: order detail
        '''
        parts = arg.split()
        if len(parts) == 2:
            symbol = parts[0]
            quantity = parts[1]
            d = g_ts.get_intraday(symbol=symbol, interval='5min')[0][-2:-1]
            o = float(d['open'])
            c = float(d['close'])
            price = round(min(o, c) + 0.15 * abs(o - c), 2)

            stock_instrument = self.trader.instruments(symbol)[0]
            res = self.trader.place_buy_order(stock_instrument, quantity,
                                              price)

            if not (res.status_code == 200 or res.status_code == 201):
                print("Error executing order")
                try:
                    data = res.json()
                    if 'detail' in data:
                        print(data['detail'])
                except:
                    pass
            else:
                print("Done")
        else:
            print("Bad Order")

    def do_s(self, arg):
        'Sell stock s <symbol> <quantity> <price>'
        parts = arg.split()
        if len(parts) == 3:
            symbol = parts[0]
            quantity = parts[1]
            price = float(parts[2])

            stock_instrument = self.trader.instruments(symbol)[0]
            res = self.trader.place_sell_order(stock_instrument, quantity,
                                               price)

            if not (res.status_code == 200 or res.status_code == 201):
                print("Error executing order")
                try:
                    data = res.json()
                    if 'detail' in data:
                        print(data['detail'])
                except:
                    pass
            else:
                print("Done")
        else:
            print("Bad Order")

    def do_o(self, arg):
        'List open orders'
        open_orders = self.trader.order_history()['results'][:10]
        if open_orders:
            column_headers = [
                "index", "symbol", "state", "price", "quantity", "type", "id"
            ]
            global g_openorders, g_liststates
            g_openorders = []
            count = 1
            for order in open_orders:
                if order['state'] in g_liststates:
                    g_openorders.append([
                        count,
                        self.get_symbol(order['instrument']), order['state'],
                        order['price'],
                        int(float(order['quantity'])), order['side'],
                        order['id']
                    ])
                    count += 1
            g_openorders.reverse()
            table = tabulate(g_openorders, headers=column_headers)
            print(table)
        else:
            print("No Open Orders")

    def do_c(self, arg):
        '''
        Cancel an open order by index return in list orders
        :param arg:
        :return:
        '''
        order_index = int(arg.strip())
        try:
            self.trader.cancel_order(g_openorders[-order_index][-1])
        except Exception as e:
            print("Error executing cancel\n", e)
        print(g_openorders[-order_index], "has been cancelled.")

    def do_u(self, arg):
        '''
        refresh the watch list, combining positions owned with symbol in wl.json
        :param arg:
        :return:
        '''
        positions = self.trader.securities_owned()
        global g_watchlist
        g_watchlist = []
        for position in positions['results']:
            g_watchlist.append(self.trader.quote_data(position['instrument']))
            # TODO maybe add pre-calculated price level in the json file as well
        with open('wl.json', 'r') as f:
            d = json.load(f)
            for each in d:
                g_watchlist.append(each)

        print("Watchlist updated")
        print(tabulate(d))

    def do_r(self, arg):
        '''
        rate
        :param arg:
        :return:
        '''

    def do_bye(self, arg):
        open(self.instruments_cache_file,
             'w').write(json.dumps(self.instruments_cache))
        return True

    # ------ utils --------
    def get_symbol(self, url):
        if not url in self.instruments_reverse_cache:
            self.add_instrument_from_url(url)

        return self.instruments_reverse_cache[url]

    def add_instrument_from_url(self, url):
        data = self.trader.get_url(url)
        symbol = data['symbol']
        self.instruments_cache[symbol] = url
        self.instruments_reverse_cache[url] = symbol
Esempio n. 15
0
class Query:

    # __init__:Void
    # param email:String => Email of the Robinhood user.
    # param password:String => Password for the Robinhood user.
    def __init__(self, email, password):
        self.trader = Robinhood()
        self.trader.login(username=email, password=password)
        self.email = email
        self.password = password

    ##           ##
    #   Getters   #
    ##           ##

    # get_fundamentals_by_criteria:[String]
    # param price_range:(float, float) => High and low prices for the queried fundamentals.
    # returns List of symbols that fit the given criteria.
    def get_fundamentals_by_criteria(self,
                                     price_range=(0.00, sys.maxsize),
                                     tags=None):
        all_symbols = []
        if tags is not None and tags is not []:
            if isinstance(tags, Enum):
                try:
                    all_symbols = self.get_by_tag(tag)
                except Exception as e:
                    pass
            else:
                for tag in tags:
                    try:
                        all_symbols += self.get_by_tag(tag)
                    except Exception as e:
                        pass
        else:
            all_symbols = [
                instrument['symbol']
                for instrument in self.trader.instruments_all()
            ]
        queried_fundamentals = []
        for symbol in all_symbols:
            try:
                fundamentals = self.get_fundamentals(symbol)
                if fundamentals is not None and 'low' in fundamentals and 'high' in fundamentals and float(
                        fundamentals['low'] or -1) >= price_range[0] and float(
                            fundamentals['high']
                            or sys.maxsize + 1) <= price_range[1]:
                    fundamentals['symbol'] = symbol
                    queried_fundamentals.append(fundamentals)
            except Exception as e:
                continue
        return queried_fundamentals

    # get_symbols_by_criteria:[String]
    # param price_range:(float, float) => High and low prices for the queried symbols.
    # returns List of symbols that fit the given criteria.
    def get_symbols_by_criteria(self,
                                price_range=(0.00, sys.maxsize),
                                tags=None):
        queried_fundamentals = self.get_fundamentals_by_criteria(
            price_range, tags)
        queried_symbols = [
            fundamentals['symbol'] for fundamentals in queried_fundamentals
        ]
        return queried_symbols

    # get_current_price:[String:String]
    # param symbol:String => String symbol of the instrument to return.
    # returns Float value of the current price of the stock with the given symbol.
    def get_current_price(self, symbol):
        return float(self.trader.quote_data(symbol)['last_trade_price'])

    # get_quote:[String:String]
    # param symbol:String => String symbol of the instrument to return.
    # returns Quote data for the instrument with the given symbol.
    def get_quote(self, symbol):
        return self.trader.quote_data(symbol)

    # get_quotes:[[String:String]]
    # param symbol:[String] => List of string symbols of the instrument to return.
    # returns Quote data for the instruments with the given symbols.
    def get_quotes(self, symbols):
        return self.trader.quotes_data(symbols)

    # get_instrument:[String:String]
    # param symbol:String => String symbol of the instrument.
    # returns The instrument with the given symbol.
    def get_instrument(self, symbol):
        return self.trader.instruments(symbol)[0] or None

    # stock_from_instrument_url:Dict[String:String]
    # param url:String => URL of instrument.
    # returns Stock dictionary from the url of the instrument.
    def stock_from_instrument_url(self, url):
        return self.trader.stock_from_instrument_url(url)

    # get_history:[[String:String]]
    # param symbol:String => String symbol of the instrument.
    # param interval:Span => Time in between each value. (default: DAY)
    # param span:Span => Range for the data to be returned. (default: YEAR)
    # param bounds:Span => The bounds to be included. (default: REGULAR)
    # returns Historical quote data for the instruments with the given symbols on a 5-minute, weekly interval.
    def get_history(self,
                    symbol,
                    interval=Span.DAY,
                    span=Span.YEAR,
                    bounds=Bounds.REGULAR):
        return self.trader.get_historical_quotes(symbol, interval.value,
                                                 span.value, bounds.value)

    # get_news:[[String:String]]
    # param symbol:String => String symbol of the instrument.
    # returns News for the instrument with the given symbol.
    def get_news(self, symbol):
        return self.trader.get_news(symbol)

    # get_fundamentals:Dict[String:String]
    # param symbol:String => String symbol of the instrument.
    # returns Fundamentals for the instrument with the given symbol.
    def get_fundamentals(self, symbol):
        return self.trader.get_fundamentals(symbol)

    # get_fundamentals:[String:String]
    # param symbol:String => String symbol of the instrument.
    # param dates:Date => List of datetime.date objects.
    # param type:Option => Option.CALL or Option.PUT
    # returns Options for the given symbol within the listed dates for the given type.
    def get_options(self, symbol, dates, type):
        return self.trader.get_options(
            symbol, list(map(lambda date: date.isoFormat(), dates)),
            type.value)

    # get_market_data:[String:String]
    # param optionId:String => Option ID for the option to return.
    # returns Options for the given ID.
    def get_market_data(self, optionId):
        return self.trader.get_option_market_data(optionId)

    # get_by_tag:[String:String]
    # param tag:Tag => Type of tag to return the quotes by.
    # returns Quotes for the given tag.
    def get_by_tag(self, tag):
        return self.trader.get_tickers_by_tag(tag.value)

    # get_current_bid_price:Float
    # param symbol:String => String symbol of the quote.
    # returns The current bid price of the stock, as a float.
    def get_current_bid_price(self, symbol):
        return float(self.trader.get_quote(symbol)['bid_price']) or 0.0

    ##                ##
    #   User Methods   #
    ##                ##

    # user_portfolio:[String:String]
    # returns Portfolio model for the logged in user.
    def user_portfolio(self):
        quotes = []
        user_portfolio = self.user_stock_portfolio()
        for data in user_portfolio:
            symbol = data['symbol']
            count = float(data['quantity'])
            quotes.append(Quote(symbol, count))
        return Portfolio(self, quotes, 'User Portfolio')

    # user_stock_portfolio:[String:String]
    # TODO: Better documentation.
    # returns Stock perfolio for the user.
    def user_stock_portfolio(self):
        positions = self.trader.positions()['results'] or []
        return list(
            map(
                lambda position: Utility.merge_dicts(
                    position,
                    self.trader.session.get(position['instrument'], timeout=15)
                    .json()), positions))

    # user_portfolio:[String:String]
    # returns Positions for the logged in user.
    def user_positions(self):
        return self.trader.positions()

    # user_dividends:[String:String]
    # returns Dividends for the logged in user.
    def user_dividends(self):
        return self.trader.dividends()

    # user_securities:[String:String]
    # returns Securities for the logged in user.
    def user_securities(self):
        return self.trader.securities_owned()

    # user_equity:[String:String]
    # returns Equity for the logged in user.
    def user_equity(self):
        return self.trader.equity()

    # user_equity_prev:[String:String]
    # returns Equity upon the previous close for the logged in user.
    def user_equity_prev(self):
        return self.trader.equity_previous_close()

    # user_equity_adj_prev:[String:String]
    # returns Adjusted equity upon the previous close for the logged in user.
    def user_equity_adj_prev(self):
        return self.trader.adjusted_equity_previous_close()

    # user_equity_ext_hours:[String:String]
    # returns Extended hours equity for the logged in user.
    def user_equity_ext_hours(self):
        return self.trader.extended_hours_equity()

    # user_equity_last_core:[String:String]
    # returns Last core equity for the logged in user.
    def user_equity_last_core(self):
        return self.trader.last_core_equity()

    # user_excess_margin:[String:String]
    # returns Excess margin for the logged in user.
    def user_excess_margin(self):
        return self.trader.excess_margin()

    # user_market_value:[String:String]
    # returns Market value for the logged in user.
    def user_market_value(self):
        return self.trader.market_value()

    # user_market_value_ext_hours:[String:String]
    # returns Extended hours market value for the logged in user.
    def user_market_value_ext_hours(self):
        return self.trader.extended_hours_market_value()

    # user_market_value_last_core:[String:String]
    # returns Last core market value for the logged in user.
    def user_market_value_last_core(self):
        return self.trader.last_core_market_value()

    # user_order_history:[String:String]
    # param orderId:String => The order ID to return the order for.
    # returns A specified order executed by the logged in user.
    def user_order(self, orderId):
        return self.trader.order_history(orderId)

    # user_orders:[[String:String]]
    # returns The order history for the logged in user.
    def user_orders(self):
        return self.trader.order_history(None)

    # user_open_orders:[[String:String]]
    # returns The open orders for the user
    def user_open_orders(self):
        orders = self.trader.order_history(None)['results']
        open_orders = []
        for order in orders:
            if order['state'] == 'queued':
                open_orders.append(order)
        return open_orders

    # user_account:[[String:String]]
    # returns The user's account.
    def user_account(self):
        return self.trader.get_account()

    # user_buying_power:float
    # returns The user's buying power.
    def user_buying_power(self):
        return float(self.trader.get_account()['buying_power'] or 0.0)

    ##                     ##
    #   Execution Methods   #
    ##                     ##

    # exec_buy:[String:String]
    # param symbol:String => String symbol of the instrument.
    # param quantity:Number => Number of shares to execute buy for.
    # param stop:Number? => Sets a stop price on the buy, if not None.
    # param limit:Number? => Sets a limit price on the buy, if not None.
    # param time:GoodFor? => Defines the expiration for a limited buy.
    # returns The order response.
    def exec_buy(self, symbol, quantity, stop=None, limit=None, time=None):
        if time is None:
            time = GoodFor.GOOD_TIL_CANCELED
        if limit is not None:
            if stop is not None:
                return self.trader.place_stop_limit_buy_order(
                    None, symbol, time.value, stop, quantity)
            return self.trader.place_limit_buy_order(None, symbol, time.value,
                                                     limit, quantity)
        elif stop is not None:
            return self.trader.place_stop_loss_buy_order(
                None, symbol, time.value, stop, quantity)
        return self.trader.place_market_buy_order(None, symbol, time.value,
                                                  quantity)

    # exec_sell:[String:String]
    # param symbol:String => String symbol of the instrument.
    # param quantity:Number => Number of shares to execute sell for.
    # param stop:Number? => Sets a stop price on the sell, if not None.
    # param limit:Number? => Sets a limit price on the sell, if not None.
    # param time:GoodFor? => Defines the expiration for a limited buy.
    # returns The order response.
    def exec_sell(self, symbol, quantity, stop=None, limit=None, time=None):
        if time is None:
            time = GoodFor.GOOD_TIL_CANCELED
        if limit is not None:
            if stop is not None:
                return self.trader.place_stop_limit_sell_order(
                    None, symbol, time.value, stop, quantity)
            return self.trader.place_limit_sell_order(None, symbol, time.value,
                                                      limit, quantity)
        elif stop is not None:
            return self.trader.place_stop_loss_sell_order(
                None, symbol, time.value, stop, quantity)
        return self.trader.place_market_sell_order(None, symbol, time.value,
                                                   quantity)

    # exec_cancel:[String:String]
    # param order_id:String => ID of the order to cancel.
    # returns The canceled order response.
    def exec_cancel(self, order_id):
        return self.trader.cancel_order(order_id)

    # exec_cancel_open_orders:[String]
    # returns A list of string IDs for the cancelled orders.
    def exec_cancel_open_orders(self):
        orders = self.trader.order_history(None)['results']
        cancelled_order_ids = []
        for order in orders:
            if order['state'] == 'queued':
                self.trader.cancel_order(order['id'])
                cancelled_order_ids.append(order['id'])
        return cancelled_order_ids
Esempio n. 16
0
from Robinhood import Robinhood
import getpass, time, sys

USERNAME = sys.argv[1]
STOCK_NAME = sys.argv[2]

trader = Robinhood()
logged_in = trader.login(username=USERNAME, password=getpass.getpass())

stock_instrument = None
while True:
    quote_info = trader.quote_data(STOCK_NAME)
    stock_instrument = trader.instruments(STOCK_NAME)[0]
    print("################################")
    print("Time:        {}".format(time.ctime()))
    print("################################")
    print("Name:        {}".format(stock_instrument['name']))
    print("Symbol:      {}".format(STOCK_NAME))
    print("Price:       ${}".format(quote_info['last_trade_price']))
    instrument_url = stock_instrument['url']
    owned = trader.securities_owned()['results']
    print("################################")
    for sec in owned:
        if sec['instrument'] == instrument_url:
            price = sec['average_buy_price']
            quantity = sec['quantity']
            print("Ave. Price:  ${}".format(price))
            print("Shares:      {}".format(quantity))
            print("Total Value: ${}".format(
                round(float(price) * float(quantity)), 2))
    print("################################\n")
Esempio n. 17
0
from Robinhood import Robinhood

# https://github.com/Jamonek/Robinhood
my_trader = Robinhood()
logged_in = my_trader.login(username="******", password="******")

# Get stock information
stock_instrument = my_trader.instruments("AAPL")[0]
print(stock_instrument)

# Get a stock's quote
quote_info = my_trader.quote_data("AAPL")
print(quote_info)

# buy_order = my_trader.place_buy_order(stock_instrument, 1)
# sell_order = my_trader.place_sell_order(stock_instrument, 1)
Esempio n. 18
0
    print(text, end='\r', flush=True)


t = Robinhood()
t.login(use_cookies=False)
runs = 0
lines = 0
options = import_json('../data/options_watch.json',
                      path=os.path.abspath(__file__))

try:
    while True:
        try:
            cur_time = int(datetime.now().strftime('%H%M'))
            time_stamp = datetime.now().strftime('%H:%M:%S')
            spy = t.quote_data('SPY')
            spy_price = float(spy['last_trade_price']).round(
                3) if cur_time >= 930 else float(
                    spy['last_extended_hours_trade_price']).round(3)
            print_str = f'{time_stamp} - SPY ({spy_price})\n'
            lines = 1
            for i, option in enumerate(options):
                opt = t.find_option_by_strike(option['ticker'], option['date'],
                                              option['strike'], option['type'])
                opt_data = t.get_option_market_data(opt['id'])
                opt_type = 'C' if option['type'] == 'call' else 'P'
                opt_text = f"{option['ticker']}-{option['strike']}-{opt_type}-{option['date'].replace('-', '')}"
                quote_data = t.quote_data(option['ticker'])
                quote = float(quote_data['last_trade_price']).round(
                    3) if cur_time >= 930 else float(
                        quote_data['last_extended_hours_trade_price']).round(3)
Esempio n. 19
0
import config
from Robinhood import Robinhood

robinhood = Robinhood()
logged_in = robinhood.login(username=config.USERNAME, password=config.PASSWORD)

stock = robinhood.instruments("AAPL")[0]
print("printing stock")
print(stock)

quote = robinhood.quote_data("AAPL")
print("printing quote")
print(quote)

info = robinhood.portfolios
print("my portfolio")
print(info)
Esempio n. 20
0
            order.get('state'),
            'symbol':
            my_trader.symbol(
                order.get('instrument').replace(
                    "https://api.robinhood.com/instruments/",
                    "").replace("/", ""))[0][0]
        })

d = {}

for order in order_list:
    symbol = order.get('symbol')
    if not d.get(symbol):
        d[symbol] = {'quantity': 0, 'revenue': 0}

    if order.get('side') == 'buy':
        d[symbol]['quantity'] += (float)(order.get('quantity'))
        d[symbol]['revenue'] -= (float)(order.get('quantity')) * (float)(
            order.get('price'))
    else:
        d[symbol]['quantity'] -= (float)(order.get('quantity'))
        d[symbol]['revenue'] += (float)(order.get('quantity')) * (float)(
            order.get('price'))

for k, v in d.items():
    v['revenue'] += (float)(my_trader.quote_data(k).get('previous_close')) * (
        float)(v.get('quantity'))
    v['quantity'] = 0

for k, v in d.items():
    print(k + ":  " + str(v.get('revenue')))
Esempio n. 21
0
if __name__ == '__main__':
    if len(sys.argv) > 1:
        quantity_to_buy = float(sys.argv[1])
        sell_below_delta = float(sys.argv[2])
        sell_above_value = float(sys.argv[3])
        buy_below_value = float(sys.argv[4])

        print('Monitoring BTCUSD')

        last_alive_hour = -1
        action_filled = False
        while True:
            if action_filled:
                break

            quote = trader.quote_data('BTCUSD')
            mark_price, bid_price, ask_price = float(quote['mark_price']), float(quote['bid_price']), float(
                quote['ask_price'])

            now = datetime.now()
            if now.hour != last_alive_hour:
                print('{}: Alive, mark_price: {}'.format(datetime.now(), mark_price))
                last_alive_hour = now.hour

            # raise Exception('Test error')

            # handle actions
            quantity, per_cost = get_holding_quantity()
            if quantity == 0 and check_buy_lock():
                print('No BTC hold and buy lock activated. Quit.')
                break
Esempio n. 22
0
# Get real-time market price for stocks
from Robinhood import Robinhood
import csv
import sys
import time


day_data_root = 'static/data/real_time/' #Root path of the data
ticker = sys.argv[1]
	


if __name__ == '__main__':
	#Login to Robinhood Account
	username = '******'
	password = '******'
	trader = Robinhood()
	f =  open(day_data_root+ticker+".csv",'w')
	quote = trader.quote_data(ticker)
	timestamp = quote['updated_at']
	price = quote['last_trade_price']

	
	writer = csv.writer(f)
	writer.writerow(['time','price']) 
	writer.writerow([timestamp,price]) 
	f.close()
Esempio n. 23
0
from Robinhood import Robinhood
my_trader = Robinhood(username="******", password="******")

#get stock information about a stock
# Note: for some stock names, more than one instrument
#       may be returned for a given stock symbol
stock_instrument = my_trader.instruments("GEVO")[0]

#You can stock information about current bid_price, etc
quote_info = my_trader.quote_data("GEVO")

#place a buy order (uses market bid price)
buy_order = my_trader.place_buy_order(stock_instrument, 1)

#place a sell order
sell_order = my_trader.place_sell_order(stock_instrument, 1)


Esempio n. 24
0
from Robinhood import Robinhood

#Setup
my_trader = Robinhood()
#login
my_trader.login(username="******", password="******")

#Get stock information
    #Note: Sometimes more than one instrument may be returned for a given stock symbol
stock_instrument = my_trader.instruments("GEVO")[0]

#Get a stock's quote
my_trader.print_quote("AAPL")

#Prompt for a symbol
my_trader.print_quote()

#Print multiple symbols
my_trader.print_quotes(stocks=["BBRY", "FB", "MSFT"])

#View all data for a given stock ie. Ask price and size, bid price and size, previous close, adjusted previous close, etc.
quote_info = my_trader.quote_data("GEVO")
print(quote_info)

#Place a buy order (uses market bid price)
buy_order = my_trader.place_buy_order(stock_instrument, 1)

#Place a sell order
sell_order = my_trader.place_sell_order(stock_instrument, 1)
Esempio n. 25
0
import config
from Robinhood import Robinhood

watchlist = ["TSLA", "AMD"]

my_trader = Robinhood()
logged_in = False
logged_in = my_trader.login(username=config.USERNAME,
                            password=config.PASSWORD,
                            qr_code=config.QR)

i = 0
while i < 6:
    for ticker in watchlist:
        ticker_last_price = my_trader.quote_data(ticker)['last_trade_price']
        print(str(ticker) + " : " + str(ticker_last_price))
    time.sleep(10)
    i = i + 1

my_trader.logout()