jmfernandes / robin_stocks

This is a library to use with Robinhood Financial App. It currently supports trading crypto-currencies, options, and stocks. In addition, it can be used to get real time ticker information, assess the performance of your portfolio, and can also get tax documents, total dividends paid, and more. More info at
http://www.robin-stocks.com
MIT License
1.74k stars 468 forks source link

Where do we store our login credentials #396

Open millionarecoin opened 1 year ago

millionarecoin commented 1 year ago

It doesnt matter what password I input. It logs me in. Is there a setting in robin_stocks folder because I am trying to set this up for a 2nd account of mine with a new credentials file and it keeps logging in to first account.

import robin_stocks import pyotp import robin_stocks.robinhood as r

import robin_stocks.tda as t

import json import os import sys import requests import datetime as dt from datetime import datetime

def robinhood_options(ticker, type):

# rh_filename = "/usr/lib/python3/dist-packages/robinhood_code/secrets.txt"
with open(rh_filename) as f:
    lines = f.readlines()
    username = lines[0].strip()
    password = lines[1].strip()
    QR = lines[2].strip()
    print(f"USERNAME={username}, PASSWORD={password}, QR={QR}")

totp = pyotp.TOTP(QR).now()
print('totp: ', totp)
login = r.login(username, password, mfa_code=totp)
print('login:  ', login)

robinhood_options('AAPL', 'call')


secrets.txt contains

test@test.com Test1234$ TESTTTTTTSSSTTTT

Adelantado commented 1 year ago

It happens cause you are trying two run the same script, but with different credentials, under the same "user" . On windows: It keeps logging in to first account because of the .tokens folder found under (Users>Whatever_User) created when logging with the 1st account, which contains the pickle file. You need to figure how to edit it prior logging in with a second account or a way to bypass it; that or log off and run script under another "user". Hope it helps.

millionarecoin commented 1 year ago

@Adelantado how do we generate the access token and pickle file. I had done it long back and dont find any documentation online. This is on ubuntu. Thank you.

Adelantado commented 1 year ago

Guessing under Ubuntu the file/folder structure would be the same, but under Windows .tokens (and the pickle file it contains) , if it does not exist, is created on the fly at login and placed in C:\Users\WhateverUser

ghost commented 11 months ago

@Adelantado According to the above details it means that our login token is saved into pickle and everytime that it used. But there is a issue. I logged into last week adn then I topup my account 3 days ago. But on python api It keep saying that I dont have balance. Its showing old cash in the account. Can you suggest what should be done in a case where I am making a trading bot and I dont want to keep logging everytime but I also want to get updated data on trading bot.

Adelantado commented 11 months ago

Please post your follow up comments / questions in the original thread you created. Let's keep all comments in just one easy to follow conversation.

Thesyjaga commented 5 months ago

is it possible to make the file into creating it into pkl? so 1 user would have a pkl file which it access it through and the other person would have another pkl file to use through which would make this alot easier.

Adelantado commented 5 months ago

Please post your follow up comments / questions in the original thread you created. Let's keep all comments in just one easy to follow conversation.

Thesyjaga commented 5 months ago

this is the method I did. I used "import atexit" and with that what i did is make the first login go through then the atexit would delete the robinhood.pickle file as mentinoed above and then when it goes through second login it automatically makes an pickle file and therefore after that finshes up it would also delete that.

Thesyjaga commented 5 months ago

heres an example code I used

import sys import os import pyotp from robin_stocks import robinhood import time import atexit

First account credentials

FIRST_KEY = "1" FIRST_EMAIL = "2@gmail.com" FIRST_PASSWD = "3"

Second account credentials

SECOND_KEY = "1" SECOND_EMAIL = "2@gmail.com" SECOND_PASSWD = "3"

TOKEN_DIR = "C:\Users\!!!!\.tokens"

def generate_otp(key): totp = pyotp.TOTP(key) return totp.now()

def login(email, passwd, key): otp = generate_otp(key) login_result = robinhood.login(email, passwd, mfa_code=otp) if login_result: print("Login successful!") else: print("Login failed.") return login_result

def logout(): robinhood.logout() print("Logged out.")

def display_price(ticker): login(FIRST_EMAIL, FIRST_PASSWD, FIRST_KEY) try: price = robinhood.stocks.get_latest_price(ticker) if price: print("Successful") else: print(f"Unable to retrieve price for {ticker}.") except Exception as e: print("Error:", e) finally: logout()

def get_all_account_numbers(email, passwd, key): login(email, passwd, key) try: accounts = robinhood.profiles.load_account_profile(dataType="results") account_numbers = [account['account_number'] for account in accounts] except Exception as e: print(f"Error fetching account numbers: {e}") account_numbers = [] finally: logout() return account_numbers

def execute_trade(action, ticker, quantity, email, passwd, key): account_numbers = get_all_account_numbers(email, passwd, key) for account_number in account_numbers: try: login(email, passwd, key) if action == "BUY": r = robinhood.order_buy_market(ticker, quantity, account_number=account_number) elif action == "SELL": r = robinhood.order_sell_market(ticker, quantity, account_number=account_number, timeInForce='gfd') print(r) time.sleep(1) except Exception as e: print(f"Error during {action.lower()}ing:", e) finally: logout()

def cleanup(): if os.path.exists(TOKEN_DIR): for filename in os.listdir(TOKEN_DIR): file_path = os.path.join(TOKEN_DIR, filename) try: if os.path.isfile(file_path): os.unlink(file_path) print(f"Deleted file: {file_path}") except Exception as e: print(f"Error deleting file {file_path}: {e}")

def main(): action = input("Enter 1 to BUY or 2 to SELL: ") ticker = input("Enter the stock ticker: ").upper() quantity = input("Enter the quantity: ")

if action == "1":
    action = "BUY"
elif action == "2":
    action = "SELL"
else:
    print("Invalid choice. Please enter 1 to BUY or 2 to SELL.")
    return

# First account execution
execute_trade(action, ticker, quantity, FIRST_EMAIL, FIRST_PASSWD, FIRST_KEY)
cleanup()

# Second account execution
execute_trade(action, ticker, quantity, SECOND_EMAIL, SECOND_PASSWD, SECOND_KEY)
cleanup()

if name == "main": atexit.register(cleanup) main()

Thesyjaga commented 4 months ago

I wanna update you guys letting you guys know that if i use this code too much robinhood would see I am logging in way too many devices and may lock my account(Didn't happen but just an theory) so now what I do is use an library where when it goes through the first time it has an pickle file and then after its finshed I would have folder and that pickle file would be dumped and then my second account would do the same. But the thing is that it would put the dumped pickle file when it goes through the first login then delete the pickle file that was dumped before and dump the pickle file that i have rn. I would put time.sleep before switching accounts because in the meanwhile it would switch the second acc dumped file into the file.

I know it is pretty long shi

Thesyjaga commented 4 months ago

I tried to make it where it would have 2 pickle files and access the first .pickle for first then the second for the second acc but it has never worked for me.