def rh_login(): print("Logging in to RobinHood...") rs.login(username=robin_user, password=robin_pass, expiresIn=86400, by_sms=True) print("Login Successful")
def login(): username = "******" password = getpass.getpass() totp = pyotp.TOTP("C3NG54ZC7JXQGSGR").now() r.login(username, password, mfa_code=totp)
def __init__(self, usr=None, pwd=None, mfa=None): # Authentication load_dotenv(find_dotenv('config.env')) username = usr or os.environ['RH_USERNAME'] password = pwd or os.environ['RH_PASSWORD'] mfa_code = mfa or pyotp.TOTP(os.environ['RH_2FA']).now() rh.login(username, password, mfa_code=mfa_code) self.api = rh self.writer = FileWriter() self.reader = FileReader() self.finder = PathFinder()
def main(): try : # Login into Robinhood totp = pyotp.TOTP(key).now() rb.login(email, pwd, mfa_code=totp) except Exception as ex : print("Error: Cannot log into to Robinhood") template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) print(message) myStocks = GetStockInfo.build_portfolio() collected_stock_info = GetStockInfo.collect_stock_info(myStocks) GoogleSheetsRead.populate_table(workbookPath, collected_stock_info)
def __init__(self, file): with open(file, 'r') as f: info = f.read().splitlines() totp = pyotp.TOTP(info[0]).now() rh.login(info[1], info[2], mfa_code=totp) self.positions = {} for position in rh.get_open_stock_positions(): with urlopen(position['instrument']) as response: instr = json.loads(response.read()) content = { 'name': instr['simple_name'], 'shares': float(position['quantity']) } self.positions.update({instr['symbol']: content})
def main(): parser = argparse.ArgumentParser() parser.add_argument("--dry-run", help="dry-run mode", action="store_true", default=True) args = parser.parse_args() if args.verbosity: print("dry-run enabled") ruser = os.environ("RH_USER") rpass = os.environ("RH_PASS") login = robinhood.login(ruser, rpass) profile = robinhood.build_user_profile() watchlist = folio.watchlist_symbols() portfolio = folio.portfolio_symbols() holdings = folio.modified_holdings() sells = find.sells(portfolio) for sym in sells: transact.sell(sym, holdings, dry_run=args.dry_run) buys = find.buys(watchlist, portfolio) if args.dry_run: transact.buy(buys, profile, holdings, dry_run=args.dry_run)
def __init__(self): self.loadConfig() if path.exists("state.pickle"): # load state print("Saved state found, loading.") with open('state.pickle', 'rb') as f: self.coinState = pickle.load(f) with open('boughtIn.pickle', 'rb') as f: self.boughtIn = pickle.load(f) else: # create state storage object print("No state saved, starting from scratch.") self.coinState = [] for c in self.coinList: print(c) self.coinState.append(coin(c)) self.data = self.loadDataframe() Result = r.login(self.rh_user, self.rh_pw) #print("\n") #print(loginResult) #print("\n") self.getIncrements() return
def login(args=''): global isLoggedIn if (not isLoggedIn): print('Logging into robinhood') if (not os.path.exists(config['credentialsPath'])): raise Exception("No credentials exist. Please create them") credentials=readJSON(config['credentialsPath']) isLoggedIn = rh.login(credentials['username'],credentials['password'])
def driver_main(m_high_price, m_open_price, m_low_price, m_mark_price): rs.login("*****@*****.**", "13428Carnegie!") DOGE = rs.get_crypto_quote("DOGE") #DOGE = sim_getquote(m_high_price, m_open_price, m_low_price, m_mark_price) m_high_price = float(DOGE['high_price']) m_low_price = float(DOGE['low_price']) m_mark_price = float(DOGE['mark_price']) m_open_price = float(DOGE['open_price']) print("Starting DOGE monitor") notify_open_price(m_high_price, m_open_price, m_low_price, m_mark_price) num_pings = 1 while True: if (1 == (num_pings % 5)): print("number of pings:" + str(num_pings)) num_pings += 1 time.sleep(getWaitTime()) DOGE = rs.get_crypto_quote("DOGE") # Uses API time.sleep(10) #DOGE = sim_getquote(m_high_price, m_low_price, m_mark_price, m_open_price) if (abs(m_open_price - float(DOGE['open_price'])) > .01): print("new open price") m_high_price = float(DOGE['high_price']) m_low_price = float(DOGE['low_price']) m_mark_price = float(DOGE['mark_price']) m_open_price = float(DOGE['open_price']) notify_open_price(m_high_price, m_open_price, m_low_price, m_mark_price) # Checks for market spike m_mark_price = float(DOGE['mark_price']) if ((m_mark_price / m_high_price) >= 1.1): print("new spike " + DOGE['mark_price']) notify_price_spike(m_high_price, m_open_price, m_low_price, m_mark_price) m_high_price = m_mark_price # Checks dip if ((m_mark_price / m_low_price) <= 0.9): print("new dip " + DOGE['mark_price']) notify_price_dip(m_high_price, m_open_price, m_low_price, m_mark_price) m_low_price = float(DOGE['low_price'])
def robinhood_login( robin_user=os.environ.get('robinhood_username'), robin_pass=os.environ.get('robinhood_password'), robin_mfa_auth=os.environ.get('robinhood_mfa_auth'), robin_mfa_code=None, ): """Login to Robinhood.""" if robin_mfa_auth: robin_mfa_code = pyotp.TOTP(robin_mfa_auth).now() rs.login( username=robin_user, password=robin_pass, expiresIn=86400, mfa_code=robin_mfa_code, by_sms=True, )
def log_in_to_robinhood(): # only use mfa login if it is enabled mfa_code=None if "mfa-setup-code" in CONFIG.keys(): # gets current mfa code totp = pyotp.TOTP(CONFIG["mfa-setup-code"]).now() print_with_lock("DEBUG: current mfa code:", totp) login = r.login(USERNAME, PASSWORD, mfa_code=mfa_code) print_with_lock("logged in as user {}".format(USERNAME)) return login
def login(): # load the environment variable file env_path = Path("../../.env") dotenv.load_dotenv(dotenv_path=env_path) # Get OTP & use it to login totp = pyotp.TOTP(os.environ['robin_mfa']).now() login = r.login(os.environ['robin_username'], os.environ['robin_password'], store_session=False, mfa_code=totp)
def export_transactions(ctx): ''' This command will export all your Robinhood transactions to a CSV file. iF you do not inform the file path and name, it will generate a file in the current directory called: robinhood_transactions.csv :return: ''' login = rh.login(ctx.obj['username'],ctx.obj['password']) rc = controller.Controller() transactions = rc.get_all_transactions() for item in transactions: print(item.symbol)
def login(ctx): ''' This command will execute a Robinhood login. :return: ''' login = rh.login(ctx.obj['username'],ctx.obj['password']) if login: click.echo("Logged In") else: click.echo("LogIn Failed")
def initRobinhood(): RH_MFA_TOKEN = os.getenv("RH_MFA_TOKEN") RH_USERNAME = os.getenv("RH_USERNAME") RH_PASSWORD = os.getenv("RH_PASSWORD") if len(RH_MFA_TOKEN) <= 0 or len(RH_USERNAME) <= 0 or len( RH_PASSWORD) <= 0: print("Missing robinhood credentials, skipping") return None # Set up robinhood totp = pyotp.TOTP(RH_MFA_TOKEN).now() login = r.login(RH_USERNAME, RH_PASSWORD, mfa_code=totp) return r
def MFALogin(self, auth_info): """ Login with MFA codes """ totp = pyotp.TOTP(auth_info["token"]).now() try: login = rs.login(auth_info["user_name"], auth_info["user_passwd"], store_session=True, mfa_code=totp) except: print( f"{bColors.FAIL}Fail: Unable to login robinhood by given credentials.{bColors.ENDC}" ) sys.exit() print(f"{bColors.OKGREEN}Info: Login successful.{bColors.ENDC}") f = open(os.devnull, "w") rs.set_output(f)
def connect(): if len(CONNECTIONS) > 0: return module = sys.modules[__name__] secrets = defaultdict(lambda: '_:_', SECRETS) username, password = secrets['robinhood'].split(':') CONNECTIONS['rh'] = rh.login(username, password) rh.helper.set_output(open(os.devnull, "w")) iex_api_key = secrets['iex_api_key'] os.environ['IEX_TOKEN'] = iex_api_key os.environ['IEX_OUTPUT_FORMAT'] = 'json' if iex_api_key[0] == 'T': os.environ['IEX_API_VERSION'] = 'sandbox' finnhub_api_key = secrets['finnhub_api_key'] CONNECTIONS['fh'] = _fh.Client( api_key=finnhub_api_key) if finnhub_api_key else None module.fh = CONNECTIONS['fh'] CONNECTIONS['yec'] = _yec.YahooEarningsCalendar() # use datetime.fromtimestamp() for ^^'s results module.yec = CONNECTIONS['yec'] alpha_vantage_api_key = secrets['alpha_vantage_api_key'] os.environ['ALPHAVANTAGE_API_KEY'] = alpha_vantage_api_key # ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas') # data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full') CONNECTIONS['av'] = dict(fd=FundamentalData()) module.fd = CONNECTIONS['av']['fd'] CONNECTIONS['tii'] = tii.TiingoClient( dict(session=True, api_key=secrets['tiingo_api_key'])) module.tii = CONNECTIONS['tii']
def login(): """Robinhood login""" robinhood.login(user, pw) console.print("")
def start_script(): loop = asyncio.get_event_loop() totp = pyotp.TOTP("My2factorAppHere").now() r.login('EMAIL_HERE', 'PASSWORD', mfa_code=totp) historic_prices = { 'price': [] } historic_ema = { 'ema': [] } # positions = r.crypto.get_crypto_positions(info=None) def sma(): price_frame = pd.DataFrame(historic_prices) x = price_frame['price'].tail(12) list = x.tolist() count = 0 for price in list: count = price + count sma = count / 12 print(f"SMA is {sma}") historic_ema['ema'].append(sma) loop.call_soon(calculateEma) def calculateEma(): price_frame = pd.DataFrame(historic_prices) ema_frame = pd.DataFrame(historic_ema) k = .1538 last_price = price_frame['price'].tail(1).tolist() last_ema = ema_frame['ema'].tail(1).tolist() a = last_price[0] * k b = last_ema[0] * (1 - k) ema = a + b print(f"First EMA is {ema}") historic_ema['ema'].append(ema) loop.call_later(900, calculateEma) def gatherData(): crypto = r.crypto.get_crypto_quote('BTC', info=None) price = float(crypto['mark_price']) historic_prices['price'].append(price) print(f"Current historical price array {historic_prices['price']}") loop.call_later(900, gatherData) def buybitcoin(): ema_frame = pd.DataFrame(historic_ema) crypto = r.crypto.get_crypto_quote('BTC', info=None) price = float(crypto['mark_price']) last_ema = ema_frame['ema'].tail(1).tolist() print(f"Current EMA is {last_ema[0]}") if price > last_ema[0]: profile = r.profiles.load_account_profile(info=None) cash = float(profile['portfolio_cash']) cash = "{:.2f}".format(cash) print(cash) info = r.orders.order_crypto('BTC', 'buy', float(cash), amountIn='price', limitPrice=None, timeInForce='gtc', jsonify=True) print(info) else: sellbitcoin() loop.call_later(900, buybitcoin) def sellbitcoin(): positions = r.crypto.get_crypto_positions(info=None) arr = positions[0] cost_bases = arr['cost_bases'] details = cost_bases[0] quantity = float(details['direct_quantity']) print(quantity) info = r.orders.order_crypto('BTC', 'sell', quantity, amountIn='quantity', limitPrice=None, timeInForce='gtc', jsonify=True) print(info) loop.call_soon(gatherData) loop.call_later(10800, sma) loop.call_later(11700, buybitcoin) loop.run_forever()
This is example code that gets the past 30 days of opening and closing prices for a specific option call or put. As far as I know, there is no way to view past prices for options, so this is a very useful piece of code. This code also plots the data using matplotlib, but the data is contained in the historicalData list and you are free to do whatever you want with it. NOTE: closing prices are plotted in red and opening prices plotted in blue. Matplotlib also has a candlestick option that you can use. ''' #!!! Fill out username and password username = '' password = '' #!!! login = r.login(username, password) #!!! fill out the specific option information symbol = 'AAPL' symbol_name = r.get_name_by_symbol(symbol) expirationDate = '2020-07-02' # format is YYYY-MM-DD. strike = 300 optionType = 'call' # available options are 'call' or 'put' or None. interval = 'hour' # available options are '5minute', '10minute', 'hour', 'day', and 'week'. span = 'week' # available options are 'day', 'week', 'year', and '5year'. bounds = 'regular' # available options are 'regular', 'trading', and 'extended'. info = None #!!! historicalData = r.get_option_historicals(symbol, expirationDate, strike, optionType, interval, span, bounds,
parser.add_argument('--type', type=str, help='specify the kind of holdings you want to snapshot', default='') parser.add_argument('--name', type=str, help='specify the filepath for saving the snapshots') if __name__ == '__main__': args = parser.parse_args() RH_UNAME = os.environ.get("robinhood_username") RH_PWD = os.environ.get("robinhood_password") totp = pyotp.TOTP("authy").now() lg = rh.login(username=RH_UNAME, password=RH_PWD, mfa_code=totp) file_name = None dir_name = None if args.name: try: dir_name = os.path.dirname(args.name) file_name = args.name.split(dir_name)[1][1:] except: pass if args.type == 'crypto': export_crypto(dir_name=dir_name, file_name=file_name, rh=rh) elif args.type == 'stocks': export_stocks(dir_name=dir_name, file_name=file_name, rh=rh) elif args.type == 'both' or args.type == '':
def setup_class(cls): totp = pyotp.TOTP(os.environ['robin_mfa']).now() login = r.login(os.environ['robin_username'], os.environ['robin_password'], mfa_code=totp)
"\"username\" and \"password\" must have key-value pairs in config.json" ) sys.exit(1) username = data['username'] password = data['password'] # log in mfa_code = None if 'mfa-setup-code' in data.keys(): # gets current mfa code totp = pyotp.TOTP(data["mfa-setup-code"]).now() print("current mfa code (this may be requested momentarily):", totp) print("data is being fetched...") login = r.login(username, password, mfa_code=mfa_code) # get and print data pp = pprint.PrettyPrinter(indent=4) top_100 = r.get_top_100() top_100 = [d['symbol'] for d in top_100] print("---------------------- TOP 100 ---------------------") pp.pprint(top_100) print("----------------------------------------------------") top_movers_any = r.get_top_movers() top_movers_any = [d['symbol'] for d in top_movers_any] print("------------ TOP MOVERS (ANY DIRECTION) ------------") pp.pprint(top_movers_any) print("----------------------------------------------------")
''' This is an example script that will withdrawl money to the bank account of your choosing. NOTE: View the two_factor_log_in.py script to see how automatic two-factor loggin in works. ''' ### REPLACE ME amount_to_withdrawl = "REPLACE-ME" ### # Load environment variables load_dotenv() # Login using two-factor code totp = pyotp.TOTP(os.environ['robin_mfa']).now() login = r.login(os.environ['robin_username'], os.environ['robin_password'], store_session=True, mfa_code=totp) # Get the bank account information bank_accounts = r.get_linked_bank_accounts() account_names = r.filter_data(bank_accounts, 'bank_account_nickname') # set up default variable values for business logic count = 1 valid_choice = False bank_choice = -1 # Present the choices in a list starting at 1 # Feel free to delete this whole if loop and just select the ach_relationship url manually if len(account_names) == 0: print("you do not have any linked bank accounts. Exiting...") else: print("=====\navailable banks\n-----") for bank in account_names:
class TestOptions: # have to login to use round_up_price totp = pyotp.TOTP(os.environ['robin_mfa']).now() login = r.login(os.environ['robin_username'], os.environ['robin_password'], mfa_code=totp) # now = datetime.datetime.now() + relativedelta(months=1) expiration_date = third_friday(now.year, now.month, now.day).strftime("%Y-%m-%d") symbol = 'AAPL' strike = round_up_price(symbol, 10) @classmethod def setup_class(cls): totp = pyotp.TOTP(os.environ['robin_mfa']).now() login = r.login(os.environ['robin_username'], os.environ['robin_password'], mfa_code=totp) @classmethod def teardown_class(cls): r.logout() def test_find_tradable_options(self): info = r.find_options_by_expiration(self.symbol, self.expiration_date) first = info[0] assert (first['expiration_date'] == self.expiration_date) assert (len(info) > 50) info = r.find_options_by_expiration(self.symbol, self.expiration_date, info='strike_price') first = info[0] assert (type(first) == str) assert (len(info) > 50) info = r.find_options_by_expiration(self.symbol, self.expiration_date, info='expiration_date') assert (len(set(info)) == 1) def test_find_options_by_strike(self): info = r.find_options_by_strike(self.symbol, self.strike) assert (len(info) >= 24) info = r.find_options_by_strike(self.symbol, self.strike, 'call') assert (info[0]['type'] == 'call') info = r.find_options_by_strike(self.symbol, self.strike, info='expiration_date') assert (len(set(info)) > 1) info = r.find_options_by_strike(self.symbol, self.strike, info='strike_price') assert (len(set(info)) == 1) def test_find_options_by_expiration_and_strike(self): info = r.find_options_by_expiration_and_strike(self.symbol, self.expiration_date, self.strike) assert (len(info) == 2) assert (info[0]['expiration_date'] == self.expiration_date) assert (float(info[0]['strike_price']) == self.strike) info = r.find_options_by_expiration_and_strike(self.symbol, self.expiration_date, self.strike, 'call') assert (len(info) == 1) assert (info[0]['type'] == 'call')
def __init__(self): login = r.login(configs.username, configs.pwd)
import robin_stocks.robinhood as r import pandas as pd import numpy as np import ta as ta from pandas.plotting import register_matplotlib_converters from ta import * from misc import * from tradingstats import * from config import * #Log in to Robinhood #Put your username and password in a config.py file in the same directory (see sample file) login = r.login(rh_username,rh_password) #Safe divide by zero division function def safe_division(n, d): return n / d if d else 0 def get_historicals(ticker, intervalArg, spanArg, boundsArg): history = r.get_stock_historicals(ticker,interval=intervalArg,span=spanArg,bounds=boundsArg) #If it's not a stock ticker, try it as a crypto ticker if(history is None or None in history): history = r.get_crypto_historicals(ticker,interval=intervalArg,span=spanArg,bounds=boundsArg) return history def get_watchlist_symbols(): """ Returns: the symbol for each stock in your watchlist as a list of strings """
def login_robinhood(): user_name = input("Enter User Name: ") password = input("Enter Password: "******"Enter Google Authentication Key.") login = r.login(user_name, password, mfa_code=totp)
def login(): """Robinhood login""" robinhood.login(user, pw)
'BSVUSD': 'BSV', 'BCHUSD': 'BCH', 'ETCUSD': 'ETC' } def get_secret(): get_secret_value_response = client.get_secret_value(SecretId=secret_name) return (get_secret_value_response) LOGGER.info("logging into Robinhood") secret = get_secret() pw = json.loads(secret['SecretString'])[username] totp = pyotp.TOTP(otp).now() login = rh.login(username, pw, mfa_code=totp) def buy_crypto(item): trade_kind = 'buy' amount = float(item['invest']['N']) convert = currency_to_genericpair[item['tick']['S']] buy = rh.order_buy_crypto_by_price(convert, amount) dbput = trade_order_dbupdate(buy, trade_kind, item) return (dbput) def dbputs(data, profit=None): if profit == None: