예제 #1
0
파일: simulation.py 프로젝트: bsmiller25/rh
    def load_prices(self, interval='day'):

        trader = Robinhood()

        # get prices
        # note: api takes 75 or fewer tickers
        self.ticker_prices = []
        segments = list(range(0, len(self.tickers), 75))
        if segments[-1] != len(self.tickers):
            segments.append(len(self.tickers))

        for i in list(range(1, len(segments))):
            tp = trader.get_historical_quotes(
                self.tickers[segments[i - 1]:segments[i]],
                interval='day',
                span='year')['results']
            self.ticker_prices = self.ticker_prices + tp

        self.full_market = np.zeros((
            len(self.ticker_prices[0]['historicals']),  # day dim
            len(self.tickers),  # ticker dim
            2))  # var dim (open, close)
        self.len_hist = self.full_market.shape[0]

        # for each day
        for day in list(range((self.len_hist - 1))):
            for ticker in list(range(len(self.tickers))):
                if self.ticker_prices[ticker]['historicals']:
                    day_ticker_p = self.ticker_prices[ticker]['historicals']\
                                   [self.len_hist - 1 - day]
                    p_open = day_ticker_p['open_price']
                    p_close = day_ticker_p['close_price']
                    self.full_market[day][ticker] = [p_open, p_close]
                else:
                    self.full_market[day][ticker] = [None, None]
예제 #2
0
    def __init__(self):
        self.home_path = os.path.abspath(os.getcwd())
        if 'ec2-user' in self.home_path:
            self.home_path = '/home/ec2-user/takaomattcom'
            self.par_path = '/home/ec2-user/'
        else:
            self.par_path = os.path.dirname(self.home_path) + '/'
        self.home_path += '/'

        with open(self.par_path + '/auth/robinhood.txt') as f:
            data = f.read().split('\n')
            RH_username = data[0]
            RH_password = data[1]

        with open(self.par_path + '/auth/alphavantage.txt') as f:
            self.av_API = f.read().split('\n')[0]

        self.my_trader = Robinhood()
        self.my_trader.login(username=RH_username, password=RH_password)
        self.equity = self.my_trader.equity()

        conn_users = sqlite3.connect(self.home_path + 'users.db')
        cursor_users = conn_users.cursor()
        self.users = cursor_users.execute("SELECT * FROM user;").fetchall()
        associate = {
            '*****@*****.**': 'Matt',
            '*****@*****.**': 'Tim',
            '*****@*****.**': 'Mazy',
            '*****@*****.**': 'Andrew'
        }
        self.users = {
            str(x[2]): [associate[x[2]], x[4],
                        str(x[5])]
            for x in self.users
        }
예제 #3
0
    def __init__(self, title='', num_stocks=15, mailing_list=[], debug=False):

        self.title = title
        self.num_stocks = num_stocks
        self.home_path = os.path.abspath(os.getcwd())
        if 'ec2-user' in self.home_path:
            self.home_path = '/home/ec2-user/capit-vita'
        self.file_path = self.home_path + '/data/'
        self.par_path = os.path.dirname(self.home_path) + '/'
        self.home_path = self.home_path + '/'
        if os.path.exists(self.par_path + '/takaomattcom/static/img/stocks/'):
            self.alt_file_path = self.par_path + '/takaomattcom/static/img/stocks/'
        else:
            self.alt_file_path = None
        #print('capit', self.home_path, self.file_path, self.par_path, self.alt_file_path)
        self.mailing_list = mailing_list
        self.debug = debug
        self.batchSize = 50

        with open(self.par_path + '/auth/alphavantage.txt') as f:
            self.av_API = f.read().split('\n')[0]

        with open(self.par_path + '/auth/robinhood.txt') as f:
            data = f.read().split('\n')
            robinhood_username = data[0]
            robinhood_password = data[1]
        self.trader = Robinhood()
        self.trader.login(username=robinhood_username,
                          password=robinhood_password)
예제 #4
0
def _get_stock_assets_value(rh: Robinhood) -> float:
    """Returns the total value held in stocks"""
    positions = rh.positions()["results"]
    stock_assets = 0
    for position in positions:
        num_stocks = float(position["quantity"])

        if num_stocks == 0:
            # Sometimes RH returns stocks that have never been bought by
            # the account
            continue

        instrument = rh.get_url(position["instrument"])
        if instrument["state"] == "inactive":
            # This symbol may have been discontinued and changed into a
            # different symbol. Calling get_quote() will result in an
            # InvalidTickerSymbol exception
            continue

        symbol = instrument["symbol"]
        quote = rh.get_quote(symbol)
        price_str = quote["last_extended_hours_trade_price"]
        if price_str is None:
            price_str = quote["last_trade_price"]

        stock_assets += float(price_str) * num_stocks
    return stock_assets
예제 #5
0
class RobinhoodExporter:
    """
  Exports metadata about a Robinhood user's held securities and portfolio.
  """
    def __init__(self, mfa_code, username=None, password=None):
        username = os.environ['rh_user'] if not username else username
        password = os.environ['rh_pass'] if not password else password

        try:
            self.rh = Robinhood()
            if not self.rh.login(username, password, mfa_code):
                raise LoginException("Invalid login credentials.")
        except:
            raise LoginException("Invalid login credentials.")

    def _securities_to_quotes(self, securities):
        return self.rh.get_url(quote_endpoint(securities))['results']

    def _stocks_from_securities(self, securities):
        for security, quote in zip(securities,
                                   self._securities_to_quotes(securities)):
            yield Stock.from_security_and_quote(security, quote)

    def export_portfolio(self, export_func=None):
        securities = self.rh.securities_owned()

        stocks = list(self._stocks_from_securities(securities['results']))

        total_equity = self.rh.equity()
        portfolio = Portfolio(total_equity, stocks)

        if export_func:
            export_func(portfolio)
        return portfolio
예제 #6
0
 def __init__(self):
     self.start_time = datetime.now()
     self.my_trader = Robinhood()
     self.my_trader.login(username=usrnm, password=pssw)
     self.equity = self.my_trader.equity()
     self.owned_securities = self.my_trader.securities_owned()
     self.available_funds = self.my_trader.equity() - sum([x[1]*x[4] for x in self.my_trader.securities_owned()])
     self.buy_limit = 120
     self.stocks = []
     self.ld = 10  ## sell no matter what
     self.sd = 5  ## sell if positive
     self.file_path = home_path
     self.conn = sqlite3.connect(self.file_path+'log.db')
     self.conn.execute('drop table if exists history')
     self.conn.execute('''create table history
             (id int primary key     not null,
             date            text    not null,
             activity        text    not null,
             stock           text    not null,
             gain            text    not null);''')
     self.idCount = 1
     print('Deleting old files...')
     # delete old files
     os.chdir(self.file_path)
     for f in glob.glob("*.png"):
         os.remove(f)
예제 #7
0
    def get_stock_info(self):

        print("Getting stock data from Robinhood")

        trader = Robinhood()
        quotes = zip(self.stock_list, trader.quotes_data(self.stock_list))
        return quotes
예제 #8
0
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.trader = Robinhood()

        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.relogin_oauth2()
              self._save_auth_data()
              self.trader.headers['Authorization'] = 'Bearer ' + self.trader.auth_token
        except:
            challenge_type = 'email'
            if CHALLENGE_TYPE == 'sms':
              challenge_type = 'sms'
            self.trader.login(username=USERNAME, password=PASSWORD, challenge_type = challenge_type)

        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
예제 #9
0
    def api(self):
        '''
        Sets up the API to RH if able, otherwise warns

        Args:
            None

        Returns:
            None
        '''
        api = Api(self)
        if api.exec_():
            self.rUser = api.user
            self.rPass = api.password
            data = {'Queue': [], 'API': {'Password': self.rPass, 'User': self.rUser}}
            logging.info('Successfully Created Keys and Config')
            self.autosave()
            self.trader = Robinhood()
            try:
                self.trader.login(username = self.rUser, password = self.rPass)
                logging.info('Successfully Logged Into Robinhood')
                if not self.qModel:
                    self.startup(data)
                self.update()
            except requests.exceptions.HTTPError:
                logging.error('Unsuccessful Login For Robinhood')
                self.warn('Login Fail')
                self.api()
예제 #10
0
 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.")
예제 #11
0
 def __init__(self):
     cfg = self.get_config()
     self.user_name = cfg.get('robinhood').get('user')
     self.password = cfg.get('robinhood').get('password')
     self.client = Robinhood()
     self.client.login(username=self.user_name, password=self.password)
     self.stock_list = self.get_stock_list(cfg.get('stock'))
     self.stock_owned()
예제 #12
0
def login():
    username = raw_input('Login: '******'Password: '******'Error: Wrong Email or Password'
        sys.exit(0)
    return trader
예제 #13
0
 def _login(self, username, password):
     self.client = Robinhood()
     # try import the module with passwords
     try:
         _temp = __import__('auth')
         self.client.login(_temp.local_user, _temp.local_password)
     except:
         self.client.login(username=username, password=password)
     return self
예제 #14
0
def test_bad_logout():
    """logout without logging in"""
    if not LOGIN_OK:
        pytest.xfail('cannot test without valid user/passwd')
    rh_obj = Robinhood()
    with pytest.warns(UserWarning):
        req = rh_obj.logout()

    assert req.status_code != 200
예제 #15
0
파일: gather.py 프로젝트: fordham-css/ptp
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)
예제 #16
0
    def __init__(self, mfa_code, username=None, password=None):
        username = os.environ['rh_user'] if not username else username
        password = os.environ['rh_pass'] if not password else password

        try:
            self.rh = Robinhood()
            if not self.rh.login(username, password, mfa_code):
                raise LoginException("Invalid login credentials.")
        except:
            raise LoginException("Invalid login credentials.")
예제 #17
0
 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)
예제 #18
0
    def __init__(self, username, password):
        self.username = username

        self.password = password

        self.robinhood = Robinhood()

        self.loggedin = self.robinhood.login(username=username,
                                             password=password)

        self.trades = self.prep_data()
예제 #19
0
def get_robinhood_portfolio_value(username, password):
    my_trader = Robinhood()
    try:
        my_trader.login(username=username, password=password)
        portfolio = my_trader.portfolios()
        if portfolio['extended_hours_equity']:
            return float(portfolio['extended_hours_equity'])
        else:
            return float(portfolio['equity'])
    except exceptions.LoginFailed:  # This started happening even with valid creds due to robinhood update, expected token response
        return "BADLOGIN"
예제 #20
0
def test_logout(config=CONFIG):
    """make sure logout works"""
    if not LOGIN_OK:
        pytest.xfail('cannot test without valid user/passwd')
    rh_obj = Robinhood()
    assert rh_obj.login(username=config.get('LOGIN', 'username'),
                        password=config.get('LOGIN', 'password'))
    assert rh_obj.auth_token is not None
    req = rh_obj.logout()

    assert req.status_code == 200
예제 #21
0
def buy(stock, ask_gap, r):
    from utils import *

    import redis

    r = redis.Redis(host='localhost', port=6669)
    r.set_response_callback('SMEMBERS', list)

    # 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])

    # config robinhood to trade on that stock
    stock_instrument = my_trader.instruments(stock)[0]

    ############################
    # BUY LOOP
    ############################

    # average and slope declaration
    count = 1
    buy_prices = []
    buy_price_slope = 0
    buy_average_prices = []
    buy_slope_of_averages = 0
    buy_sum = 0

    ## begin buy loop
    buy = False
    bought_at = 0.0
    while buy == False:
        if (last_bid(stock, r) - last_ask(stock, r)) > ask_gap:

            # buy a single share of the stock at the ask price
            #buy_order = my_trader.place_buy_order(stock_instrument, 1, ask_price)

            # break the buy loop
            buy = True
            bought_at = last_ask(stock, r)
            return buy, bought_at
예제 #22
0
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.trader = Robinhood()
        self.trader.login(username=USERNAME, password=PASSWORD)

        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
예제 #23
0
    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
예제 #24
0
def test_intstruments(config=CONFIG):
    """test `instruments` endpoint"""
    #TODO: this test is bad, just repeat of code inside endpoint
    params = {'query': CONFIG.get('FETCH', 'test_ticker')}
    headers = {'User-Agent': CONFIG.get('FETCH', 'user_agent')}
    address = Robinhood().endpoints['instruments']
    res = requests.get(address, headers=headers, params=params)
    res.raise_for_status()
    hard_data = res.json()['results']

    data = Robinhood().instruments(CONFIG.get('FETCH', 'test_ticker'))

    assert data == hard_data
예제 #25
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
예제 #26
0
def init():
	global driver
	global page_date
	global my_trader
	global logged_in

	my_trader = Robinhood()
	username_input = input("Robinhood Username:")
	password_input = getpass.getpass()

	logged_in = my_trader.login(username=username_input,password=password_input)
	
	page_date = 'NULL'
	driver = webdriver.Chrome(r'C:\Users\migue\Desktop\StockBot\chromedriver.exe')
	print('driver initialized')
예제 #27
0
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)

        self.setupUi(self)

        try:
            from resources.NASDAQ import tickCurrents

            nTest = tickCurrents('NVDA')
            if nTest:
                if nTest['LTP']:
                    self.setStates(self.nState, True)
                else:
                    self.setStates(self.nState, False)
            else:
                self.setStates(self.nState)
        except ImportError:
            self.setStates(self.nState)

        try:
            from Robinhood import Robinhood
            rTest = Robinhood()
            self.setStates(self.rState, True)
        except:
            self.setStates(self.rState)
예제 #28
0
def test_get_news(config=CONFIG):
    """test `get_news` endpoint"""
    test_ticker = CONFIG.get('FETCH', 'test_ticker')
    raw_news = helpers.fetch_REST_directly('news', test_ticker, config)
    get_news = Robinhood().get_news(test_ticker)

    assert get_news == raw_news
예제 #29
0
def _get_crypto_assets_value(rh: Robinhood) -> float:
    """Returns the total value held in crypto"""
    # print(rh.crypto_orders())
    crypto_assets = 0
    crypto_holdings_data = rh.crypto_holdings()["results"]

    for crypto_holding in crypto_holdings_data:
        quantity_available = float(crypto_holding["quantity_available"])
        if quantity_available == 0:
            continue

        code = crypto_holding["currency"]["code"]
        market_price_str = rh.crypto_quote(rh.CRYPTO_PAIRS[code])["mark_price"]

        crypto_assets += quantity_available * float(market_price_str)
    return crypto_assets
예제 #30
0
    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
예제 #31
0
def test_login_badpass(config=CONFIG):
    """try to login with bad creds"""
    if not LOGIN_OK:
        pytest.xfail('cannot test without valid user/passwd')
    bad_pass = '******'
    with pytest.raises(RH_exception.LoginFailed):
        Robinhood().login(username=config.get('LOGIN', 'username'),
                          password=bad_pass)
예제 #32
0
class RobinhoodUtility:
    __robinhood = Robinhood()
    __sell_book_path = 'configs/robinhood_sell_book.csv'

    @staticmethod
    def is_order_open(order: dict) -> bool:
        return order['state'] == 'queued' or order[
            'state'] == 'unconfirmed' or order['state'] == 'confirmed'

    @staticmethod
    def instrument_2_symbol(instrument: str) -> str:
        return RobinhoodUtility.__robinhood.get_url(instrument)['symbol']

    @staticmethod
    def symbol_2_instrument(symbol: str) -> str:
        return RobinhoodUtility.__robinhood.get_url(
            'https://api.robinhood.com/quotes/%s/' % symbol)['instrument']

    @staticmethod
    def is_market_open():
        current_time_est = datetime.datetime.now(pytz.timezone('US/Eastern'))
        return datetime.time(
            hour=9, minute=30) <= current_time_est.time() <= datetime.time(
                hour=16, minute=00)

    @staticmethod
    def get_max_trade_price(symbol: str,
                            bid_price: bool = True,
                            ask_price: bool = False) -> float:
        trade_prices = RobinhoodUtility.__robinhood.last_trade_price(symbol)
        if bid_price:
            trade_prices += RobinhoodUtility.__robinhood.bid_price(symbol)
        if ask_price:
            trade_prices += RobinhoodUtility.__robinhood.ask_price(symbol)
        return float(max(max(trade_prices)))

    @staticmethod
    def load_sell_book() -> pd.DataFrame:
        return pd.read_csv(RobinhoodUtility.__sell_book_path,
                           index_col=0).astype('float')

    @staticmethod
    def save_sell_book(sell_book: pd.DataFrame):
        sell_book.to_csv(RobinhoodUtility.__sell_book_path)

    @staticmethod
    def upload_sell_book(sell_book: pd.DataFrame, github_token: str) -> bool:
        repo = github.Github(github_token).get_user().get_repo('finance')
        remote_path = '/%s' % RobinhoodUtility.__sell_book_path
        remote_file = repo.get_file_contents(remote_path)
        new_file = sell_book.to_csv()
        uploaded = False
        if remote_file.decoded_content != new_file.encode('ascii'):
            repo.update_file(remote_path, 'update sell book',
                             sell_book.to_csv(), remote_file.sha)
            RobinhoodUtility.save_sell_book(sell_book)
            uploaded = True
        return uploaded
예제 #33
0
        'date': order['last_transaction_at'],
        'state': order['state']
    }


def get_all_history_orders(rb_client):
    orders = []
    past_orders = rb.order_history()
    orders.extend(past_orders['results'])
    while past_orders['next']:
        print("{} order fetched".format(len(orders)))
        next_url = past_orders['next']
        past_orders = fetch_json_by_url(rb_client, next_url)
        orders.extend(past_orders['results'])
    print("{} order fetched".format(len(orders)))
    return orders


rb = Robinhood()
# !!!!!! change the username and passs, be careful when paste the code to public
rb.login(username="******", password="******")
past_orders = get_all_history_orders(rb)
instruments_db = shelve.open('instruments.db')
orders = [order_item_info(order, rb, instruments_db) for order in past_orders]
keys = ['side', 'symbol', 'shares', 'price', 'date', 'state']
with open('orders.csv', 'w') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(orders)

예제 #34
0
totalTransacts = 0

cash = 0
minCash = cash

netWorth = 0 
minNetWorth = 0
maxNetWorth = 0

cashHistory = []
netHistory = []
shareHistory = []


#Setup
my_trader = Robinhood();
#login

print "\n\nWelcome to MarketMiner\n"
print time.asctime() ,"\n"
#username = raw_input("Robinhood Username: "******"YOUR_USERNAME", password="******")

sys.stdout.flush()



 
start_time = time.time()
예제 #35
0
logged_in = False

# hard code your credentials here to avoid entering them each time you run the script
username = ""
password = ""

parser = argparse.ArgumentParser(description='Export Robinhood trades to a CSV file')
parser.add_argument('--debug', action='store_true', help='store raw JSON output to debug.json')
parser.add_argument('--username', default=username, help='your Robinhood username')
parser.add_argument('--password', default=password, help='your Robinhood password')
args = parser.parse_args()
username = args.username
password = args.password

robinhood = Robinhood();

# login to Robinhood
while not logged_in:
	if username == "":
		print "Robinhood username:"******"":
		password = getpass.getpass()

	logged_in = robinhood.login(username=username, password=password)
	if logged_in == False:
		password = ""
		print "Invalid username or password.  Try again.\n",

fields = collections.defaultdict(dict)
예제 #36
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)


예제 #37
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)
예제 #38
0
from Robinhood import Robinhood

#Setup
my_trader = Robinhood(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)